What is the correct way to configure spring security to accept JSON based requests - ajax

I'm trying to figure out what the correct way to configure SpringSecurity is to receive, respond to json based authentication requests.
There appear to be two ways to do this :
Use the spring security configuration to route authentication requests to a Controller...see http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery
Create a new AuthenticationFilter, AuthenticationSuccessHandler, AuthenticationFailureHandler...see https://github.com/loiane/spring-security-extjs-login
It looks like the AuthenticationFilter method fits into the framework better, and ensures that filters that come afterward in the chain execute.
Anyone know what the pros/cons of either approach are?

Related

Why does Spring's `AuthenticationWebFilter` have it's own matcher for checking if a request needs authentication?

As the title says; AuthenticationWebFilter has it's own set of matchers to determine if a request needs authentication. This seems to work against spring security's way of doing things.
If an endpoint is set in spring securty config to .permitAll() it would also have to be excluded in the AuthenticationWebFilter, why doesn't the filter just let the request through and let the rest of spring security handle it?
EDIT: To reframe my question in response answer by Steve Riesenberg:
Why does AuthenticationWebFilter, an authentication filter, control access to resources? Shouldn't that be handled by the authorization filters?
EDIT: I just figured out that the filter actually doesn't block access when there is not authentication, only when verification fails, which makes sense.
I think the answer to your question lies in an understanding of filter ordering and purpose within Spring Security. Your question specifically references AuthenticationWebFilter, which is used in reactive applications. The Spring Security docs have a comprehensive list of filters in order for servlet applications, but you can refer to the SecurityWebFiltersOrder enumeration for a similar ordering in reactive applications.
In both cases, you can see that "authorization" (FilterSecurityInterceptor in servlet, AuthorizationWebFilter in reactive) is effectively the last filter in the list. Therefore, if you set a route to .permitAll() in http.authorizeExchange(), you are instructing the authorization manager to allow that request, assuming it passes all other filters in the filter chain. By setting the matcher in AuthenticationWebFilter to the same route, you are asking that filter to attempt authentication for that route, which will terminate processing and never reach the authorization step. Only authorized requests will reach your application code, but some requests can be processed by the filter chain prior to (and instead of) your application needing to handle them.
Put simply, authentication is attempted/handled prior to authorization.
I figured out that my confusion was due to a misunderstanding of how AuthenticationWebFilter works. My understanding was that it would block any request not sucessfully authenticated, but it turns out it only blocks request for which authentication failed. Requests with no authentication at all are let through.
This actually makes sense.
I didn't look too closely at this filter since I remembered that a similar servlet filter works this way, AbstractAuthenticationFilter or something I think. I'm still pretty sure that one works that way, and I still wonder why, but as I'm not sure I will close this question by answering it myself. If it comes up in the future I might post another question.
My thanks to the people who answered!

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

Use #EnableResourceServer with custom Authorization Provider

I'm trying to find what classes I need to implement in order to use the #EnableResourceServer annotation and interact with our custom OAuth2 server and token storage.
The goal is to package it as a library and share it across other services. So basically I need to implement:
Custom Token endpoint.
Custom Refresh endpoint.
Custom token validation filter (to avoid the call to /check_token) since we are using JWT, we are ok with just making sure the token is properly signed.
Save the token (on the resource service) in Redis.
The custom endpoint to retrieve the user information.
So far I've seen the following classes:
TokenEndpoint
RefreshTokenGranter
OAuth2AuthenticationProcessingFilter
But since I haven't been able to find much documentation, I'm wondering whether I'm a bit lost or these classes are not intended to be overridden and it will be better to create my custom logic and not rely on the #EnableResourceServer.
I believe where you might want to start looking is ResourceServerSecurityConfigurer and ResourceServerConfigurerAdapter. This follows a similar programming model to WebSecurityConfigurerAdapter and will give you some context for what can be configured.
From there, take a look at ResourceServerTokenServices and TokenStore for points 1, 3, 4, and 5.
Now, regarding #2, since you'd also like to have applications refresh tokens, it sounds like you might want to create two libraries, one for services that want to authorize requests using OAuth2 (#EnableResourceServer) and one for services that want to address those resource servers (#EnableOAuthClient). In that case, also take a look at OAuth2RestTemplate and ClientTokenServices.
Also, take a look at http://projects.spring.io/spring-security-oauth/docs/oauth2.html if you haven't already as this is where I pulled most of the above from.
There are some examples at https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2 that you might find helpful on the Resource Server side, specifically https://github.com/spring-projects/spring-security-oauth/blob/master/samples/oauth2/sparklr/src/main/java/org/springframework/security/oauth/examples/sparklr/config/OAuth2ServerConfig.java
And there is an example of a client at https://github.com/spring-projects/spring-security-oauth/blob/master/tests/annotation/client/src/main/java/client/ClientApplication.java
Hope that helps!

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.

Resources