Setup Spring Filter using annotation - spring

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

Related

What is the differences between Spring Boot API without Filter and Spring Boot API with Filter?

From the beginning, I often write Spring Boot API with many API depend on what my application needs. I know there is a type like Filter Servlet, what is it? Can anyone help me to find the difference between API with Filter and without Filter?
I have go through some research: https://www.baeldung.com/spring-boot-add-filter and https://www.tutorialspoint.com/spring_boot/spring_boot_servlet_filter.htm
I have a sample for using Servlet Filter: https://help.shopify.com/en/api/reference/products/product#create-2019-10
A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances −
Before sending the request to the controller
Before sending a response to the client.
so its depends on requirement of your app if you need to do some work before sending request to controller or not.
Take an example below:
if we need to create an application where we need to authenticate and authorization of user with help of token so in each api we need to verify token before sending request to controller so we can use filter their.
and sending response back to client if we want to append some token then we can add same in filter.
example of filter:
https://www.javadevjournal.com/spring-boot/spring-boot-add-filter/
below method use for next call:
filterChain.doFilter(request, response);

Servlet principal in high precedence filter, using Spring Security

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.

#EnableGlobalMethodSecurity vs #EnableWebSecurity

I am developing a REST API using Spring 4. I would like to secure some of the endpoints using Spring Security, but based on what I've read this can be done with either #EnableGlobalMethodSecurity or #EnableWebSecurity. Unfortunately, the documentation that I have found for these don't clearly explain what they do (or how they compare). If I want to secure a Spring REST API with authentication and authorization based on data and relationships declared in a standard relational database, what is the recommended method for achieving this in Spring 4?
EnableWebSecurity will provide configuration via HttpSecurity. It's the configuration you could find with <http></http> tag in xml configuration, it allows you to configure your access based on urls patterns, the authentication endpoints, handlers etc...
EnableGlobalMethodSecurity provides AOP security on methods. Some of the annotations that it provides are PreAuthorize, PostAuthorize. It also has support for JSR-250. There are more parameters in the configuration for you
For your needs, it's better to mix the two. With REST you can achieve everything you need only by using #EnableWebSecurity since HttpSecurity#antMatchers(HttpMethod,String...) accepts control over Http methods

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

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?

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