I have a Spring Boot application that is only exposing a REST API. I need to secure it and I'm using a token-based approach ― specifically JWT.
So far, this is what I have implemented:
//
// The Spring Security configuration class
@EnableGlobalAuthentication
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/login", "/api/logout").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JwtFilter(), BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
//
// The JWT filter class to check for the token in the HTTP request (headers)
public final class JwtFilter extends GenericFilterBean {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws
IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest)request;
final String header = req.getHeader("Authorization");
logger.debug("{} {}", req.getMethod(), req.getRequestURI());
if ((null == header) || !header.startsWith("Bearer ")) {
logger.debug("Missing or invalid Authorization header");
}
try {
// Check the token here; the implementation is not relevant here
/*SecurityContextHolder.getContext()
.setAuthentication(manager.authenticate(new JwtToken(JWTParser.parse(header.substring(7)))));*/
chain.doFilter(request, response);
} catch (final AuthenticationException e) {
SecurityContextHolder.clearContext();
// Do some other stuff here
} catch (final ParseException e) { /* ... */ }
}
}
The issue is that the filter executes correctly for every single URI, but I want to be able to exclude some endpoints from the same set. My API is placed in this context /api/*
and I want to exclude, for instance, /api/login
and /api/logout
.
NOTE: My Spring Boot application.yml
file doesn't have settings to enable/modify any security-related features.
What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern. Just would like to add you have to extend WebSecurityConfigurerAdapter and override this method in it.
Spring Security's web infrastructure is based entirely on standard servlet filters. It doesn't use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology.
Class AuthenticationFilterA Filter that performs authentication of a particular request. An outline of the logic: A request comes in and if it does not match setRequestMatcher(RequestMatcher) , then this filter does nothing and the FilterChain is continued.
How Security Filters Works We got the basics about the Spring security and it’s workflow. Spring security performs most of its core logic using servlet filters, and it’s very important that we understand the workflow. This can help us debug or customize the security behaviour. Let’s look at the entire filters stack closely:
The addFilterBefore () method of the HttpSecurity class will register the custom filter before Spring security filter. 2. Advanced Before Authentication Filter Configuration Here, you can see the filter requires an instance of the CustomerService class, which will be injected by Spring framework as @Autowired is used.
Spring security uses the filter chain to execute most of the security features. In this article, we will look at the Spring security filters chain. We will learn how these filters works and how they executed internally by Spring security.
And finally it should call super.attemptAuthentication () to delegate processing to the Spring Security filter. In this example, it just prints the email of the user who is about to login. And configure this filter in the Spring security configuration class as follows: ... ... ...
Filters will be executed for all the endpoints that are configured through HttpSecurity. If you do not want filters to be applied for certain endpoints, include them in a method that configures WebSecurity. For example,
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/api/login", "/api/logout");
}
Please read this post for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With