Spring MVC authorization in REST resources - rest

I have REST api for accessing "parties" and the URL's look like this:
/parties
/parties/{partyId}
Using Spring controllers and #PathVariable I'm able to implement this interface. But to prevent users from accessing parties they don't have access to, I have to add checks to every method call which is kind of repeating myself and I might forget to add it everywhere:
#RequestMapping(value="/parties/{partyId}", method=RequestMethod.GET)
public #ResponseBody Party getParty(#PathVariable Integer partyId){
authorizeForParty(partyId);
...
Now what I would like to do is create a check that would be called every time that user enters url like this:
/parties/{partyId}/**
How would I do something like this? Do I have to create some servlet filter and parse the url myself? If I have to parse the url then is there atleast tools that would make it easy? I wish there was a way to add a method to controller that would be called before methods but could still use #PathVariables and such...

What I ended up with is using the Spring MVC interceptors and parsing the path variables in the same way that Spring does. So I define an interceptor for the REST url:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/parties/*/**" />
<bean class="PartyAuthorizationInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
The PartyAuthorizationInterceptor has to implement HandlerInterceptor in which we have to implement preHandle. It has HttpServletRequest as a parameter so we can get the request URL but we still have to parse the partyId from the url. After reading how Spring MVC does it, I found out they have a class named org.springframework.util.AntPathMatcher. It can read the path variables from the URL and place the values in a map. The method is called extractUriTemplateVariables.
So the result looks like this:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String partyIdStr = new AntPathMatcher().extractUriTemplateVariables("/parties/{partyId}/**", request.getPathInfo()).get("partyId");
...
That makes the parsing almost as easy as using #PathVariable in MVC Controller methods. You still have to do conversions yourself(e.g. String -> Integer).
Now I can implement authorization logic on all urls that access a party in this interceptor and keep that logic out of the individual controller methods. Not as easy as I would have hoped but it gets the job done.

Are you already using some kind of security library in your application, e. g. Spring Security?
Because the kind of logic you want to implement is a classic case for an AccessDecisionVoter in an authentication chain. You would just put your API behind Spring Security's protection and implement the custom check as part of the security chain.
If you are not using a security framework at all, your idea of implementing a HandlerInterceptor may be the best alternative, though. But it would require you (as you mentioned) to take into account all kinds of obfuscation the user may use in order to gain access to other URLs (e. g. %-encoding of letters, ../../ patterns etc.).

Related

I want to expose my existing controller as a Restful service

I have an application where I'm registering a user so user will enter his data on JSP page and the data will be save into DB, the flow will be JSP->dispatcher->controller->Service->Dao.
Now in MemberController which is delegating the request to the Service, has a method register() which will take the MemberDto as a parameter now and return the Successfull msg to the success.jsp page. Sometihng like user registered successfully.
public String Register(MemberDto memberDto)
Now I want to expose this same method as RestFul service using Jersey for partners and also use this same method within my application as a normal MVC flow. How can I acheive this
So u want to use Jersey so import the jersey library to support JAX-RS.
#Path("/classlevelpath")
public class MyController {
#POST
#Produces(MediaType.APPLICATION-XML)
#Path("/register")
public String Register(MemberDto memberDto) {
}
}
Be careful JAX-RS (Jersey is an implementaion) and Spring REST annotations are different.
Annotate your rest class with #RestController. The best practice is to create another controller. By you can see this answer if you want to transform your existing controller: https://stackoverflow.com/questions/33062509/returning-view-from-spring-mvc-restcontroller

how to get HTTP request object in class implementing jackrabbit ExternalIdentityProvider

I am implementing custom external identity provider and to do this I need to implement ExternalIdentityProvider class from jackrabbit.
http://jackrabbit.apache.org/oak/docs/security/authentication/externalloginmodule.html
In normal case you would need to pass j_username and j_password and you can get these from values SimpleCredentials object
My question is that since I need to pass additional form parameter say for instance linkedin ID in my case, how do I achieve that?
#Component(
policy = ConfigurationPolicy.REQUIRE
)
#Service
public class RDBMSIdentityProvider implements ExternalIdentityProvider {
#Override
public ExternalUser authenticate(Credentials credentials)
throws ExternalIdentityException, LoginException {
//i can get username / password from credentials object
//how to get additional parameters from http request object?
}
Any input is highly appreciated.
Thanks!
The correct way to handle this is to have a custom AuthenticationHandler which creates an instance of a specific Credentials object with whatever parameters you need in it.
That said, if you are integrating with LinkedIn (and this is in AEM), you would be better served by integrating with the existing OAuth AuthenticationHandler. There is OOTB support for Facebook and Twitter, but the OAuth provider is designed to be pluggable for different OAuth Service Providers.

Dancer Hooks on a per-request method basis?

I'm working on a CRUD application using Dancer. One of the things I need to do is check a user is authorized to perform POST (create) and PUT (update) / DELETE (remove) operations.
I've read up on before hooks in the Dancer documentation, but have been unable to figure out the best way to do varying types of authorization.
For a POST operation, all I want to do is check that a valid API key has been submitted with the request, but for a PUT/DELETE operation, I want to check that the API key submitted matches the user who is attached to the record to be updated or deleted.
I understand how to do the logic behind checking the API keys, but I'm wondering if hooks (or something else) would allow me to call that logic without having to add the same boilerplate function call to every single PUT/POST/DELETE function on every route.
like I told the poster on IRC, I think a combination of https://metacpan.org/pod/Dancer#request (the Dancer request object) and its HTTP verbs querying things should do the trick. See for example: https://metacpan.org/pod/Dancer::Request#is_post .
I'm not sure if it's a very elegant solution, but I think it should work.
Here's another take on this issue, based on experience:
Since Dancer has not had the opportunity to parse your input parameters when the 'before' hook executes, you may not have a consistent way to read in your authentication credentials, if your application allows them to be provided in a variety of ways.
In particular, if you're using input parameters to pass a nonce to prevent CSRF attacks (which you should definitely consider!), you won't have a consistent way to obtain that nonce. You could do your own mini-parameter-parsing within 'before', but that could be messy too.
I ran into this problem when I worked on an application some time ago, and remember having to add the dreaded boilerplate authentication function to every PUT/POST/DELETE route. Then, if you're doing that, it becomes irrelevant to check request->is_post because you're already deciding whether to place the boilerplate authentication function within the route.
I haven't tried this yet, but it may be possible to handle the pre-requisite action in your Route base class, then pass upon success. This will leave your specific packages to handle the request as normal once your base class has verified authentication.
An action can choose not to serve the current request and ask Dancer to process the request with the next matching route. This is done with the pass keyword, like in the following example
get '/say/:word' => sub {
return pass if (params->{word} =~ /^\d+$/);
"I say a word: ".params->{word};
};
get '/say/:number' => sub {
"I say a number: ".params->{number};
};

User roles in GWT applications

I'm wondering if you could suggest me any way to implement "user roles" in GWT applications. I would like to implement a GWT application where users log in and are assigned "roles". Based on their role, they would be able to see and use different application areas.
Here are two possible solution I thought:
1) A possible solution could be to make an RPC call to the server during onModuleLoad. This RPC call would generate the necessary Widgets and/or place them on a panel and then return this panel to the client end.
2) Another possible solution could be to make an RPC call on login retrieving from server users roles and inspecting them to see what the user can do.
What do you think about?
Thank you very much in advance for your help!
Another way is to host your GWT app in a JSP page. Your JSP might contain a snippet of code like this
<script type="text/javascript">
var role = unescape("${role}");
</script>
Where ${role} is expression language expanded from value you computed from the associated servlet / controller and exposed to the JSP.
When your GWT app runs in the browser, the value will be filled out. Your GWT app can easily call out into JS to obtain this value from a native method call, e.g.
public native String getRole() { /*-{ return $wnd.role; }-*/;
So your module could invoke getRole(), test the value and do what it likes to hide / show elements.
Obviously your backend should also enforce the role (e.g. by storing it in the session and testing it where appropriate) since someone could run the page through a JS debugger, setting breakpoint or similar that modifies the value before it is evaluated allowing them to access things they shouldn't be accessing.
Following scenario works for me:
GWT app is behind security constraint.
On module load I make RPC call to retrieve roles from the container. I store them in main GWT module's class as static field, to make it easy for other classes to use it.
Each widget (especially menu) can use roles (e.g. call Main.getRoles()) and construct itself according to roles. I don't pass roles in constructor. Each widget knows how to behave depending on role.
If it's crucial to not only hide things but also enforce them you can use container security and check roles and rights while invoking business methods.
While using GIN you can also create singleton class to store roles retrieved during login and inject it wherever you need it.

How to RESTful delete record Asp.Net Mvc 2

I have delete links in my Asp.Net Mvc2 application.
/{controller}/Delete/{id}
It seems using link to delete has a security risk. Don’t use Delete Links because they create Security Holes
I found this Implementing RESTful Routes & Controllers in ASP.NET MVC 2.0 but I am not sure how to implement a simple delete functionality using the new HttpDeleteAttribute class.
Are there any examples on deleting, the RESTful approach?
The RESTful approach to a Delete is to send enough information to identify the resource and use the HTTP command DELETE (or some alternative for web pages). But all of that is detailed in the article, so I don't think that's what you're really asking.
If you mean "What do I do instead of a Delete link?", the answer is usually to go to a "Are you sure you want to delete Product 8496?" form where the button's action POSTs the delete request. That form can either be on a new page or a modal popup, or both if you want to combine usability and accessibility.
It's a (more of) a security risk if you dont use the [HttpPost] attribute on the controller.
Besides that, your approach isn't a restful one.
The idea is that you have just one Url that can be passed different Http Verbs which are implicit
Return all: /Product/ [HttpGet]
Return One: /Product/43 [HttpGet]
Add : /Product/ (Product info in form post) [HttpPut] or [HttpPost]
Delete: /Product/43 [HttpDelete]
You can do this using MVC in the standard form or JQuery
And to answer the question:
Add a delete link like this Delete Product but hook into it using the JQuery live events so that it hijacks the click using .preventDefault, then call the url as an ajax request with a DELETE verb.
Need more help let me know