Servlet principal in high precedence filter, using Spring Security - spring

Our Spring Boot 1.3.3 application uses Spring Security. We need to log HTTP requests including requested URL, HTTP verb, processing time, user principal.
This is done using a custom servlet filter.
The custom filter must have higher precedence (i.e. smaller order) than Spring Security filter chain, or else it won't be executed for requests rejected by Spring Security.
But then in the custom filter, HttpServletRequest:getUserPrincipal is always null. It seems that Spring Security removes security information once his security chain is done.
Is there a standard way (meaning without thread local magic) to always get the user principal from a custom filter when using Spring Security?
Thank you for your time.

Well as you are using Spring Security, the principal is likely to be set precisely by the Spring Security machinery. But what's even worse, is that it uses request wrapping, so you will not find the principal neither before calling the FilterChain because it has not been set, nor after because it was set in a HttpServletRequestWrapper that is no longer here.
So IMHO your best choice is to put a custom filter inside the Spring Security chain, just before the ExceptionTranslationFilter, log after chaining and pass along any exception.

Related

Setup Spring Filter using annotation

I am really new to spring and wanted to make a simple web application that uses JWT based authentication.
I have an endpoint on my server (/token) that returns JWT tokens to my client.
These clients then make requests to my server using that token. I was wondering how I could implement something like this:
#Secured("Admin")
#RequestMapping("/users", method=RequestMethod.DELETE)
public #ResponseBody String deleteUsers(){
...
}
From what I could gather, I would need a filter that would validate my JWT token that is sent along with every request the client makes. Is there any way in which only requests that have a #Secured annotation are passed through that filter?
Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required. The ordering of the filters is important as there are dependencies between them. If you have been using namespace configuration, then the filters are automatically configured for you and you don't have to define any Spring beans explicitly but here may be times when you want full control over the security filter chain, either because you are using features which aren't supported in the namespace, or you are using your own customized versions of classes.
link

How does filters interact with authentication providers in Spring Security?

If I understand correctly, the AuthenticationProvider authenticate Authentication that they support, but how does the Authentication object gets created in the first place?
Is it the filter's responsibility to initialize them?
At what point are they passed into the providers?
See JavaDoc:
In most cases, the framework transparently takes care of managing the security context and authentication objects for you.
Authentication is a Spring managed bean. It´s initializated by the Spring framework and passed to the Authentication provider by default when the context is created.

Authentication and authorization in Spring Data REST

I am implementing a Spring Data REST based app and I would like to know if there is an elegant way to implement authentication and authorization rules using this framework or related frameworks.
All HTTP requests to the REST server must carry authentication headers, I need to check them and decide to authorize or not based on the HTTP method and the association of the authenticated user with the resource being requested. For example, (the app is the REST server of an e-learning system), the instructors can access only their own course sections, students can access only the courses sections they are subscribed, etc.
I would like to know if there is a default way to implement authorization in Spring Data REST. If the answer is no, could you make a suggestion for my issue? I am thinking about:
Servlet Filters
Spring Security
Spring Data REST Handlers (how to access the HTTP headers?)
The best bet for you is Spring Security.
That would help you achieve authorization is much simpler manner.
Spring Security would require you an implementation that looks at request headers and performs the log-in operation programmatically.
Refer the accepted answer here.. I had followed the same and implemented the security layer in front of my rest services ( which were build using RestEasy )
RESTful Authentication via Spring
There is an alternate method as well..
Refer
http://www.baeldung.com/spring-security-authentication-provider
In both cases you can disable the session creation by declaring the stateless authentication in spring security, this would help you improve the performance considerably when large volume of hits are made to the state-less REST services..

Spring security filter after request processing

How can I make my spring security filter get executed after request is processed by Controller/JAX-RS endpoint?
A normal java filter chain is supposed to get control when the request is processed both ways. How to do that with spring security filters? I tried calling chain.doFilter() at the start and adding my logic after the call. However, after request is processed, the control doesn't come back.
Any pointers on how this can be achieved, is it possible with spring security filters at all?
Answering my question -
Spring security filter chain processes filters registered with and does not give control back to normal filters configured.
The resolution I used was to define my filters before spring securityFilterChain.

How to do Concurrent Session Control without authentication and authorization in Spring Secuirty 3.1

I need to use Concurrent Session Control features of Spring Security. I need to invalidate the previous session of the logged in user(single user sign in). I do not need the feature of authentication and authorization, since it was already implemented by the application using Servlet(Filter) which calls serice layer that calls dao layer(Hibernate).
Please guide me how to implement Concurrent Session Control without authentication and authorization.
Thanks,
balachandar
One option (hack) would be to use Spring's pre-authentication feature. i.e. you would perform your authentication in your filter and set an attribute on the request object which is the username. The request would then be passed down to Spring and Spring where the concurrent session control feature could be enabled.
But really the best option would be to implement concurrent session control in your filter. You could even "borrow" some code from the spring source.
Short answer: you can't unless you refactor your application to use spring-security fully.
Slightly longer answer: you can "fake" a Java EE container login (pre-authenticated). That would entail specifying a login-filter derived from AbstractPreAuthenticatedProcessingFilter in your spring security http configuration. For instance, you could wrap your request in your filter and add a header values and use the RequestHeaderAuthenticationFilter, or you could write your own that pulls the principal from a request attribute you set on the request in your own login filter. Combine with a PreAuthenticatedAuthenticationProvider.
Slightly longer answer #2: you could use an allow-all kind of setup where you configure spring-security with session concurrency as usual but set the access to permitAll for all URLs (is <intercept-url pattern="/*" access="permitAll" />). You would, however, have to implement essentially what the ConcurrentSessionControlStrategy does in your own login logic, to get the sessions registered into the spring security SessionRegistry. You will most likely run into any number of other snags along the way as well.
Note however that since spring-security works on the basis of a servlet filter (not a servlet like Spring MVC), you will need to refactor your own login as a filter and place it before the spring security filter in the chain, if you are to go with some combination of your own auth logic and spring security.
My advice, if you want to leverage spring-security for concurrent session control, you should really go all the way and build your auth on top of spring-security instead of some custom servlet. Don't fight the framework, use it as intended. Or, don't use it at all.

Resources