Apache Shiro Permissions: How to implement any of permission check - shiro

I have a list of the following permissions:
book:download:red,
book:download:blue,
book:download:green
Now, I want to check whether the subject has any of those permissions set. If at least one of them is present, - permit.
So, on my REST controller, I am slapping this annotation with value:
#RequiresPermissions(value = book:download:*)
It means in my case, the subject has at minimum one valid book it can download, - let him in!
But, to my surprise, I get 403 with:
Subject does not have permission [book:download:*]
I would expect Shiro to use this wildcard and compare it against submitted permission like a REGEX check. And a result would have been - access allowed.
Please correct me if my understanding is wrong. And is there is a way to achieve what I am asking here?

Think of the match the other way, your resource has a specific permission "book:download:red" and your user can download any book because they have a more general permission book:download or book:download:* (or the same specific red permission)
You can also configure the annotation to use a logical "OR", where you could use your list of red, blue, or green
https://shiro.apache.org/static/1.7.1/apidocs/org/apache/shiro/authz/annotation/RequiresPermissions.html
See more: https://shiro.apache.org/permissions.html

you can use something like following:
#RequiresPermissions(value=
{PermissionsConstants.BOOK_DOWNLOAD_RED,
PermissionsConstants.BOOK_DOWNLOAD_BLUE,
PermissionsConstants.BOOK_DOWNLOAD_GREEN}, logical = Logical.OR)

Related

How to trigger multiple Intent in Webhook api.ai?

I am developing an api.ai bot that will search for the Vendor name in the database.
a ) if vendor exist -> provide username -> provide password
b) if vendor doesn't exist -> (add vendor -> yes ) or (add vendor -> No)
I have a webhook which is checking the vendor exist in database or not .
Bot Scenario: (Example )
Case1:
User: Do Alpha exist as a vendor?
Bot: yes, Alpha exist in Database. Please Provide User Name.
User: abc#gmail.com
Bot: Please Provide Password?
User: abcdef
Bot : Welcome
Case 2:
User: Do Beta exist as a vendor ?
Bot: No Beta is not a vendor. Do you want to Register?
Case 1:
User: Yes
Bot: Please fill this Form.
Case 2:
User: No
Bot: Is there any other way I can help
One thing I have figured out, I have to use output context to trigger the intent. But how can I do it in this complex case? and how can I call multiple to follow up intent using Output Context?
I might be using a bad approach, Is there any other way to solve this ?
I do have a follow-up question.
when we pass the fulfillment response back to dialogue flow. The response print on bot console will be the default text response, how can I get "fulfillmentText" to be the Response.
Thank you Guys. This is the followup Intent scenario.
This is not complex, you are doing it wrong by having two intents for collecting username/password.
Try the following way
When you detect that your vendor is present - set the context in webhook, as say, "vendor-present"
When the vendor is not present - set the context in webhook, as say, "vendor-new"
Use lifespan (the number at the left side of the context) to set the lifetime or validity of the context.
Create a separate intent for existing vendor - say "Vendor Data Collection" for collecting username and password. Set input context as "vendor-present" in the Dialogflow. Here you will collect these as parameters in the same intent (see image below). Mark these parameters as 'required' so that they must be collected by your bot. Use the Prompt section to put your response question for collecting information like "Please provide username".
If the vendor is not present, use existing intents and set input context as "vendor-new" in the Dialogflow.
Now, few things to note - the username parameter can be collected using the system entity #sys.given-name. But it is not very accurate with the Non-American/English names. I am not sure if this is improved or not. Secondly, there is no system entity to collect passwords, so you need to set the entity as #sys.any and in the webhook, you need to use regex to extract passwords on your own. BTW - you are not supposed to share passwords!
Hope this helped you!

How to represent a read-only property in a REST Api

if you have a REST API that is hypermedia-driven (HATEOAS) you can easily change a client's behavior by including or omitting links in the response (_links). That enables a client to completely forget about testing permissions for the operations that are possible in the current state of a resource (the link to the operation is present or not).
Additionally you can leave out properties in the response if the current user doesn't have permission to see it.
That way authorization is done entirely on the server (and controls actions and properties that are eligible to execute/view).
But what if I want to a have a read-only property? It is no problem for the REST API to ignore the property if it is present in the request (_POST_ OR _PUT_). it just won't get saved. But how can a client distinguish between write and read-only properties to present the user appropriate controls (like a disabled input field in HTML)?
The goal is to never ever have the client request a user's permissions, but to have a completely resource driven client/frontend.
Any help is greatly appreciated :-)
If I misunderstood your question, I apologize upfront. With that being said...
But how can a client distinguish between write and read-only
properties to present the user appropriate controls (like a disabled
input field in HTML)
Well, there are multiple solutions to this. The simplest one I can personally think of is to make each property an object having a simple structure of something like:
...
someProperty: {
value: 'some value',
access: 'read-only'
},
someOtherProperty: {
value: 'some value',
access: 'write'
}
...
You can obviously get as creative as you want with how you represent the "access" level of the property (using enums, booleans, changing access to be isReadOnly or whatever).
After that, the person using the API now knows they are read-only or not. If they submit a "write" value for a "read-only" property as part of the POST payload, then they should expect nothing less than a 403 response.
Edit:
In case you can't alter the properties in this manner, there are a number of other ways you can still achieve this:
write documentation that explains what access each property has
create a route that the user can submit 1 or more properties to in order to receive a response that indicates the access level of each property (response: { propName: 'read-only', propName2: 'write', etc.)
Return a propertyAccess map as part of the response (mapping properties to access levels).
end of the day, you just need a way to map a property with an access level. however that's done depends on what your restrictions and requirements are for the api, what changes you can make, and what is acceptable to both your client(s) and the business requirements.

REST Resource route naming for get and ResourceByID and ResourceByName

I am trying to write 2 Rest GET methods.
Get user by Id
Get user by userName.
I need to know if there is any resource naming convention for this. Both my id and username are strings.
I came up with:
/api/{v}/users/{userid}
/api/{v}/users/username/{username}
However, 2) doesn't seem correct and if I change 2) to /api/{v}/users/{username}, I am mapping to 1) as both id and username are strings. Or is it considered acceptable to use /api/{v}/userbyName/{username}?
How should I name my resource route in case 2) ?
First of all: https://vimeo.com/17785736 (15 minutes which will solve all your questions)
And what is unique? Is the username unique or only the id or both are unique?
There is a simple rule for all that:
/collection/item
However, 2) doesn't seem correct and if I change 2) to /api/{v}/users/{username}, I am mapping to 1) as both id and username are strings.
If your item can be identified with an id and also with an unique username - it doesn't matter if it's the username or the id - simply look for both (of course your backend needs to handle that) and retrieve it.
According to your needs this would be correct:
/api/{v}/users/{userid}
/api/{v}/users/{username}
but I would choose only to use: /api/{v}/users/{userid} and filter by username only with a query parameter (description for that down there below)
Also will I break any rules if I come up with
/api/{v}/userbyName/{username}
Yes - /api/{v}/userbyName/{username} will break the rule about /collection/item because userByName is clearly not a collection it would be a function - but with a real restful thinking api there is no function in the path.
Another way to get the user by name would be using a filter/query paramter - so the ID will be available for the PathParameter and the username only as filter. which than would look like this:
/api/{v}/users/?username={username}
This also don't break any rules - because the query parameter simply filters the whole collection and retrieves only the one where username = username.
How should I name my resource route in case 2) ?
Your 2) will break a rule - so I can't/won't suggest you a way to do it like this.
Have a look at this: https://vimeo.com/17785736 this simple presentation will help you a lot about understanding rest.
Why would you go this way?
Ever had a look at a javascript framework like - let's say ember. (Ember Rest-Adapter). If you follow the idea described up there and maybe also have a look at the json format used by ember and their rest adapter - you can make your frontend developer speed up their process and save a lot of money + time.
By REST you send back links, which can contain URI templates. For example: /api/{v}/users/{userid} in your case, where v and userid are template variables. Since the URI structure does not matter from a client perspective you can use whatever structure you want. Ofc. it is more convenient to use nice and short URIs, because it is easier to write the routing with them.
According to the URI standard the path contains the hierarchical while the query contains the non-hierarchical part of the URI, but this is just a loose constraint, in practice ppl use both one.
/api/{v}/users/name/{username}
/api/{v}/users/name:{username}
/api/{v}/users?name="{username}"
Ofc. you can use a custom convention, for example I use the following:
I don't use plural resource name by collections
I end collection path with slash
I use slash by reducing a collection to sub-collections or individual items
I don't use slash to give the value of a variable in the path, I use colon instead
I use as few variables and as short URI as I can
I use query by reducing a collection to sub-collections especially by defining complex filters with logical operators
So in you case my solution would be
/api/{v}/user/
/api/{v}/user/name:{username}
/api/{v}/user/{userid}
and
/api/{v}/user/?firstName="John"
/api/{v}/user/?firstName="John|Susan"&birthYear="1980-2005"
or
/api/{v}/user/firstName:John/
/api/{v}/user/firstName:John|Susan/birthYear:1980-2005/
etc...
But that's just my own set of constraints.
Each resource should have a unique URI.
GET /users/7
{
"id": 7,
"username": "jsmith",
"country": "USA"
}
Finding the user(s) that satisfy a certain predicate should be done with query parameters.
GET /users?username=jsmith
[
"/users/7"
]

Why use selectors and not a new URI?

I have a doubt, I have a URI that will bring me all user's account from another rest service. Example:
GET /users/21212/account
Now I have the need to bring 3 kinds of different groups of user's account, something like: "low-account", "medium-account" and "high-account".
But the discussion is, how should I enable this on my endpoint ?
GET /users/21212/accounts/low-account
GET /users/21212/accounts/medium-account
GET /users/21212/accounts/high-account
or
GET /users/21212/accounts/1?selector=low-account
GET /users/21212/accounts/1?selector=medium-account
GET /users/21212/accounts/1?selector=high-account
I'm inclinated to follow the first approach, I think is more intuitive and the manutenability of the code will be easily preserved... What do you think is conceptual right/better and why ?
I would choose the following option:
GET /users/12345/accounts?group=low-account
It will return you all accounts that belong to 'low-account' group for user 12345.
I tend to use query params if they represent something like filtering. Also I would recommend you to take a look at HATEOAS principle. Then you will be more flexible with your URIs.

How to do role-based authorization with Apache Shiro depending on HTTP request method

I'm struggling to figure out how I can do role-based authorization depending on what HTTP method a request is using. I use HTTP basic auth and depending on the users role and the HTTP method used a request should succeed or fail.
Example:
a GET request to http://localhost/rest/ should always be allowed, even to non-authenticated users (anon access)
a PUT request to http://localhost/rest/ (same resource!) should only be allowed if user is authenticated
a DELETE request to http://localhost/rest/ (same resource!) should only be allowed if user is authenticated and has the role ADMINISTRATOR
My current (non-working) attempt of configuring shiro.ini looks like this:
/rest = authcBasic[PUT], roles[SERVICE_PROVIDER]
/rest = authcBasic[POST], roles[EXPERIMENTER]
/rest = authcBasic[DELETE], roles[ADMINISTRATOR]
/rest = authcBasic
Update
I've just found https://issues.apache.org/jira/browse/SHIRO-107 and updated my shiro.ini to be
/rest/**:put = authcBasic, roles[SERVICE_PROVIDER]
/rest/**:post = authcBasic, roles[EXPERIMENTER]
/rest/**:delete = authcBasic, roles[ADMINISTRATOR]
/rest/** = authcBasic
but it still doesn't work. It seems that only the last rule matches. Also, the commit comment also seems to indicate that this only works with permission-based authorization. Is there no equivalent implementation for role-based authz?
I think HttpMethodPermissionFilter is the one you need to configure: http://shiro.apache.org/static/1.2.2/apidocs/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.html This should enable you to map the HTTP method to Shiro's "create,read,update,delete" permissions as outlined in the javadoc for the class.
I had a similar situation with Shiro and my REST application. While there may be a better way (I hadn't seen SHIRO-107), my solution was to create a custom filter extending the Authc filter (org.apache.shiro.web.filter.authc.FormAuthenticationFilter). You could do something similar extending the authcBasic filter or the Roles filter (although I think authcBasic would be better as it is probably more complicated).
The method you want to override is "protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)". Your argument (e.g. "ADMINISTRATOR") will come in on the mappedValue as String[] where the arguments were split by commas.
Since I needed the possibility of both a method and a role, I ended up have my arguements looks like "-". For example:
/rest/** = customFilter[DELETE-ADMINISTRATOR]
That let me split out the role required to perform a delete from the role required for a POST by doing something like:
/rest/** = customFilter[DELETE-ADMINISTRATOR,POST-EXPERIMENTER]
I think if you play with this, you'll be able to get the functionality you need.
BTW, I hadn't seen SHIRO-107, so I've not tried that technique and probably won't since I've already invented my own custom filter. However that may provide a cleaner solution than what I did.
Hope that helps!