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
Related
I'm developing application in Spring Boot and I need jwt authentication there. I decide to use that github project, but when I'm looking at code I don't understand sense of SecurityContextHolder.
Here are 2 classes which are using it:
AuthenticationRestController.java
JwtAuthenticationTokenFilter.java
Can you tell me what is purpose of SecurityContextHolder? I want stateless authentication without session. So I just need generate jwt and next check it before requests.
This git project also has disable session:
...
httpSeccurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
...
I've tried delete code with SecurityContextHolder and applicatin still works fine.
Thanks for answers.
Here is a quote from Learning Spring 5.0:
One major aspect of security is storing the information of the principal currently used by the application. It is held by the security context of the application. SecurityContextHolder is the most important object of the framework as it stores the details about security context in ThreadLocal. It means the security context will be available to the methods that are executed in the same thread. However, in a few circumstances, all the threads in the application may need to use other strategies for using the security context. The framework provides two ways to change the default nature of using ThreadLocal. The developers can either set the system property or they can invoke the static method on SecurityContextHolder.
The reason your application still works after deleting code with SecurityContextHolder is that by using the SessionCreationPolicy.STATELESS creation policy you request Spring Security to not create an HTTP session and not store logged in user’s SecurityContext in the session.
When to use SessionCreationPolicy.STATELESS
to stop creating sessions during the entire lifespan of the application
to stop using sessions during the entire lifespan of the application
I'm trying to understand how uel-interception works in spring security. Let assume that we write the following rule in our security config:
<security:intercept-url pattern="/secure/super/**" access="ROLE_WE_DONT_HAVE"/>
My question is is Spring Security going to create the object of AbstractSecurityInterceptor or what? I need to understand that because if my assumption about creation an object for each rule right I'm going to create the instances dynamically by myself in order to control authentication rule dynamically in runtime.
basically spring security will create one instance of FilterSecurityInterceptor
this filter will read the url pattern and will try to protected the mapped url
more information here spring security core
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.
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.
Can I use Spring Security annotations in my ZKGrails composers to secure the ajax-callbacks, or can/do i have to inject springSecurityService (and check the principal's authorities, in every method manually)?
Update: According to http://felipecypriano.com/2009/10/26/tweak-zk-to-make-event-processing-call-groovys-invokemethod/ , the annotations should work, and I found the modification mentioned in this post in the current ZKGrails plugin version (1.0.4). Still, when I try to secure methods in my composer, they remain fully accessible.
Because "#Secured" annotation is not supported by spring security plug-in. I think you should implement your own method interceptor according http://felipecypriano.com/2009/10/19/enable-secured-annotation-with-grails-spring-security-plugin/ to enable it.