Java webapps security constraints & custom security providers - java

I'm creating a restful web service using Resteasy. One thing I need to do is to secure the service using a standard HTTP auth request. The tricky part is that the service is multi-tenant and needs to use one of the path parameters to determine the security realm.
There are a lot of articles typical of this link which describe setting up a single-tenant service. What I can't find is what to configure, and what interfaces to implement to describe my own security which is based on a path parameter + the username in the HTTP authentication method.
I envision that prior to calling any of the application logic, tomcat/resteasy would call a SecurityProvider (or whatever) interface with the HttpServletRequest and have me either throw a 401 or return a SecurityContext that gets passed to the JAX-RS handlers. In that routine, I would inspect the path parameters, and make a determination based on parameter+username+password given in the Basic/Digest/Form.
Is there any such beast?

I thought I'd update this since there's bee little activity on this question.
It looks like there's no baked in feature to do what I envisioned, so instead I extended the RestEasy servlet and added the security checks in my override before passing control back to the stock RestEasy servlet.
Seems to work well.

Related

Tomcat web.xml: restrict access to specific methods of a servlet

I'm running a web application under Tomcat server. Different servlets are configured using Tomcat's web.xml.
I'm looking for a convenient way to restrict access to specific METHODS of specific URLS so that only these METHODS can be accessed using an Authorization header while others can be accessed without any restriction.
For instance, for url http://localhost:8080/my/servlet1 - GET and OPTIONS can be accessed by any user, while POST and PUT must be authorized with a username and a password, but for url http://localhost:8080/my/servlet2- all methods are open.
How can I implement that?
Thanks
The most low level API that allows you to do all sorts of filtering based on the context of the HTTP request in the javax/servlet/Filter
You implement a filter class that can restrict on the basis of HTTP method and any other criteria you choose. You register the filter on your web.xml and you add rules for which paths it is filtering.
Here is an walk through on applying such a filter.
If you happen to be using more than just a naked Tomcat for your application and you are using Spring Boot on top of it you could use their flavor of filters. This is an example for that case.

Securing a jersey RESTful web service

I'm developing a restful web service that will be consumed by an Android application later on.
Right now, I'm seeking a way to secure the access to my resources:
I found several ways for implementing that on the net, but I can't figure out what is the most appropriate one.
For example, I found that Oauth specifications are more convenient for third-party applications which is not my case.
So what are the most suitable ways for securing jersey APIs, and I'll be glad if someone can provide me with any tutorials/documentations on that.
I'm using a Glassfish v4 server and the Jersey JAX-RS implementation.
After looking at different options I used an authentication filter and basic auth. Very easy to implement.
Some example code:
You need a filter
public class AuthFilter implements ResourceFilter, ContainerRequestFilter {
...
}
And a security context:
public class MySecurityContext implements SecurityContext {
...
}
And a user class:
public class User implements Serializable, Principal {
...
}
Finally, you can add the filters you need like so: (pass your ResourceConfig object to this function)
private void prepareFilters(ResourceConfig rc) {
rc.getProperties().put("com.sun.jersey.spi.container.ContainerRequestFilters",
getClassListing(new Class[]{
AuthFilter.class
}));
rc.getProperties().put("com.sun.jersey.spi.container.ContainerResponseFilters",
getClassListing(new Class[]{
CORSFilter.class, //You might not need this
GZIPContentEncodingFilter.class //You might not need this
}));
rc.getProperties().put("com.sun.jersey.spi.container.ResourceFilters",
getClassListing(new Class[]{
RolesAllowedResourceFilterFactory.class
}));
}
BTW, you can add #Context SecurityContext securityContext; to your resource class(es) or the individual methods for more fine grained access control. The SecurityContext will be injected into the context of your resource so you can access the User object per request with
With this setup you can annotate your REST methods with #PermitAll, #RolesAllowed, etc which gives you a good level of control over your RESTful interface.
I just finished my stateless (without sessions) user auth and management with Jersey.
Let me know if you want a full example or if you want to give it a try yourself ;)
The simplest way would be using the Java EE build-in Container Managed Security model to secure your rest resources as described in this tutorial. It allows you to configure the security based on users and roles stored in a database or file realm in the web.xml or the the classes themselves.
The disadvantage would be that you must start a session, extract the JSESSIONID and send it in each of your requests so that the server can verify it, but that makes your services more 'stateful' and violates the statelessness of the rest architecture.
Another way would be implementing custom security by using WebFilters, like sending the user name and password with each of your requests and verity them based on the information in a special db. If the information doesn't match the information stored in the database a redirect or a special error code can be returend in the Response object.
The best approach I think is using OAuth2 as described in this specification. Dependend on what kind of client you are using (desktop, web page, mobile client) there are different workflows and apart from that lots of benefits like creating tokens for special scopes of your application (read-only or full access,...). Google provides many different apis that can be accessed by the same account. If an applications only needs data from the calendar api, the requested token only gives you access to this special api and not to the entire resources of the account (like mail data, notes, etc). Another point would be that the security handling is decoupled from the client and no password must be stored in the client application.
You can either implement everything on your own or use a open source project like this. It provides a description on how it works and the code is very good but it has many dependencies to spring frameworks. For my use case I've startend replacing them by vanilla Java EE 7 code and create a solution based on the idea of this open source project. The reason behind the replacements was that it's more future-proof and it avoids class loader problems during the deployment.
In the Android app a Authenticator can be implemented for secure storing of the token.

Dynamically extend Spring MVC powered REST api with access to application jar only

I am in a situation where I have a nascent rest api architecture where each method has tons of ceremony (validation, db connection acquisition/release, authentication), raw request/response objects as the parameters, and hard-coded json strings as the output. I want to use spring mvc to help with at least some of these issues (auth & db stuff i'll need to hold off on). This would render a lot of the current architecture unnecessary. This is pretty easy except for one feature of the current architecture: dynamically adding api calls.
The entry point (servlet) for the architecture reads from an xml file that contains the path for a request and a corresponding class to load. The class must implement an interface that contains an 'execute' method which has the logic for the request. The servlet calls this execute method after loading the class. This allows dynamic extension of the api as follows. The app is packaged as a jar together with the associated config (xml) files and given to a client. The client includes this jar in his project, creates a class that implements the aforementioned interface, and adds a mapping from request url to that class in the included xml file. He then runs the app and gets access to both the original api and his custom api.
Example:
Client is given app.war, interface.jar and custom-mappings.xml. app.war contains the implementation of the core api (rest webservice), and interface.jar exposes the interface BaseController that has the method 'execute' (app.jar also uses this interface in its controller). Client then defines his own class as follows.
package custapi.controllers;
public class ExtendedController implements BaseController {
public void execute(HttpServletRequest request, HttpServletResponse response) {
// LOGIC
}
}
He compiles this class and adds it to app.war. Next, he updates custom-mappings.xml with the following entry.
/custcall/mycall
custapi.controllers.ExtendedController
He then deploys the app. The controller provided with the core api receives the request /custcall/mycall, looks it up in custom-mappings.xml, finds the class is custapi.controllers.ExtendedController, loads that class, and finally runs its 'execute' method. This allows the logic defined by the client to be run.
Ideal:
Current architecture is replaced with spring-mvc. That is, there is no more 'super' controller that parses requests and delegates to the appropriate class and, finally, method. Spring handles this. For the app that uses this new architecture, the client would receive the app.war and the spring mvc deps that expose controller annotations. The client would then create a new spring mvc controller (taking advantage of validation, parameter -> pojo mapping, object -> json conversion), compile it, and add the resulting class file to app.war. His controller would then become an extension to the core api exposed by the app. When the app is deployed, he would be able to make a request /custcall/mycall like before and have it execute the logic he defined. This ideal scenario allows clean code for the core api (which I and others programmed) and an extended api. (A downside to this approach is that the client is tied to spring. In an even more ideal scenario, the client would use framework-agnostic annotations which are mapped to spring annotations by the app. I'm not sure how easy this would be.)
I'm not sure how the above would be realized with a spring-aware controller without sacrificing the benefits of spring. I don't believe the client could simply define another spring-aware controller (correct me if I'm wrong on this). The only solution I can think of is to have a spring-aware controller that has a wildcard path (e.g., /cust_rest/*) which acts exactly the same as the current controller. The client would not get any advantages that spring has to offer, but the core api would be a lot cleaner. I was hoping there was a better solution, however. Ideally the client would get the benefits of spring without having access to the core api source code. Any ideas on this, or is my solution the best that can be hoped for?
Thanks.
(NOTE: For both scenarios, I am only guessing how the client actually gains access to the dependencies/interfaces and deploys. I have only had access to the core api project for one day, and so my understanding of it is not complete.)
Related: Runtime loading of Controllers for Spring MVC and dynamically mapping requests/URLs
The above question looks pretty similar to mine. Replies are sparse (second one is just off topic, I believe).
Provided you setup classpath scanning properly there's no need for interface. Your clients can just annotate classes with #Controller #RequestMapping("/foo/bar"). Even if this class is located in its own jar it will still be scanned. If this is a REST service consider using #RestController instead to avoid having to place #ResponseBody on each handler method.
Use spring security to do declarative authentication & authorization (what you're doing now is programmatic security)

Spring security #PreAuthorize("hasAnyRole('....')")

I am using spring security #PreAuthorise to check who and who cannot access methods in my service layer. It works really well. Usually my service methods are annotated with
#PreAuthorize("hasAnyRole('MY_USER_ROLE')")
My problem is that I have a war file made up of several jar files. Each of these jar files is responsible for a segment of business logic. I now want one of the services in one jar file to access another service in another jar file. This gets rejected because of the permissions. If I comment out the permission then everything works.
Is there anyway I can authenticate via spring before calling this service? (Perhaps with a dummy user?) Or perhaps turn off the security for jars within the same application? Or is my design wrong?
Anyone else has this sort of problem? What design should I use instead?
You need to give the thread that invokes the service (in the other jar) the permissions that are required by #PreAuthorize (for the invoked service).
If the thread is triggered in an web application by an user request, then this are normally the users permissions.
But if the thread is triggered by some timer service then you need to give them the right authentication
Authentication authentication = new UsernamePasswordAuthenticationToken("dummy", "password");
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
I believe this is a good example where you should use Spring security #Secured annotation
What is #Secured annotation?
From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It
provides support for JSR-250 annotation security as well as the
framework's original #Secured annotation.
Source: Spring Security 3.1 Reference 2.4 Method Security
#Secured annotation allows you to put restrictions in your methods. For example, you can authorize a get() method to be accessible by all
registered users. But for the edit() method, you can mark it be
accessible by admins only.
Check out some tutorials at:
http://burtbeckwith.com/blog/?p=1398
http://krams915.blogspot.in/2010/12/spring-security-3-mvc-using-secured.html

Using JaaS with Jersey on Grizzly

I'm trying to find a simple, flexible way to add JaaS authentication to REST. I found a post that I think leads me in the right direction (See StevenC's answer). It sounds like the servlet container is responsible for security, not the Jersey code itself. I like this idea, but need a little guidance on implementation.
Grizzly is my servlet container and I want to configure it to use JaaS for authentication. For now, a simple username/password combination would be fine, and hard-coding the username/password pairs directly in code is fine. As long as it uses JaaS, we can refine those details later.
As far as what is sent over HTTP, I'm thinking that storing a cookie would be the easiest way to make this all work. Whatever it takes to keep authentication junk away from my Jersey code.
Here's the code to start Grizzly so far:
final String baseUri = "http://localhost:9998/";
final Map initParams = new HashMap();
initParams.put("com.sun.jersey.config.property.packages",
"my.jersey.Service");
System.out.println("Starting grizzly...");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format(
"Jersey app started with WADL available at %sapplication.wadl\n"
+ "Try out %shelloworld\nHit enter to stop it...", baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
If this whole process works, what's the best way to check permissions for the user? I would probably want my REST code to actually validate permissions at certain points. Am I even on the right track? Is there an easier way? A link to a tutorial would be a great answer. Even an answer like "I did that and it worked" would give me a warm fuzzy that I'm heading in the right direction.
Thanks for any help.
EDIT: Some clarifications for StevenC's comment:
Do you still want to use servlet filters to protect your resources? I'll use whatever can separate out the authentication detail from the Jersey code. It doesn't have to be servlet filters.
What is mean by "configure it to use JaaS"? The original plan was to protect the current API using JaaS. The next phase would be to make the entire API available online. It seemed to make sense to have a Jersey wrapper around the API calls, but keep authentication handled by Grizzly. Grizzly would have to interact with JaaS at that point I believe.
Are you thinking there should be some config that simply causes grizzly to protect your resources? I was considering a two-step process of authenticating the user and based on roles, authorizing the user to access resources. The idea was to have Grizzly handle authentication (using JaaS) and Jersey handle authorization.
"I don't see the need for the usage of cookies with a RESTful resource." It would be wonderful to remove the use of cookies, but how can the be accomplished? The system needs to know if the user is authenticated. I'd rather not ask them to pass a username/password/etc for each call. Even passing a session token as a parameter with every call seems "ugly".
Also, please note that I'm fairly new to REST. I've been doing SOAP for a couple of years, so I may have a "SOAP bias" that may be blinding me from some obvious, simple solution that everyone uses. If there's an easier way, please feel free to share. I'm just trying to learn as much as possible.
I'm not entirely clear what is meant by "configure it to use JaaS for authentication". If there's a simple configuration to have grizzly enforce HTTP authentication protecting URLs, I don't know about it.
I'm assuming from the other question and answer you reference that you want to use a servlet filter. Normally that's configured in the web.xml file of a servlet project. Grizzly is of course often used to start up a server from code as opposed to application config. When I used grizzly in this way I noticed that GrizzlyWebContainerFactory didn't offer any versions of create() that allowed you to specify servlet filters. However I did notice ServletAdapter [1] in the same project that does give you that ability.
As for the filter itself, I unfortunately don't know of a pre-built servlet filter that simply plugs JaaS configured login modules into your application, so you'll likely have to write a bit of code there. It's not much though, just choose the HTTP based authentication method (e.g. HTTP BASIC, DIGEST, etc.), extract credentials from the request accordingly, and login using the JaaS framework. I don't see that a cookie would specifically be needed for RESTful resources. The RESTful architectural style frowns upon keeping sessions. There are plenty of tutorials about JaaS otherwise, so I won't elaborate on that here.
Once a JaaS subject is active (consumer successfully logged in) you can simply get the current subject and check the active principals and credentials using the Subject.getSubject method.
Anyway, this answer is specifically to give a bit more of the details around doing auth with servlet filters, as you requested in the other (linked) question. This isn't necessarily the only way to do auth in a jersey webapp, but it's a fairly straightforward way to do it. I like it because it keeps me from injecting repetitive auth code in each resource that needs it.
[1] https://grizzly.dev.java.net/nonav/apidocs/com/sun/grizzly/http/servlet/ServletAdapter.html
Not sure if you are asking how to secure each resource, but I found a presentation on javapassion that sounds like what you are looking for. He says to use #Context SecurityContext as a parameter.
#Path("basket")
// Sub-resource locator could return a different resource if a user
// is a preferred customer:
public ShoppingBasketResource get(#Context SecurityContext sc) {
if (sc.isUserInRole("PreferredCustomer") {
return new PreferredCustomerShoppingBaskestResource();
} else {
return new ShoppingBasketResource();
}
}

Categories