Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security bypass URL or Filter

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.

like image 929
x80486 Avatar asked Mar 09 '16 15:03

x80486


People also ask

How do I bypass Spring Security?

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.

Which filter class is required for Spring Security?

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.

What is authentication filter in Spring Security?

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 does spring security work?

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:

How to configure httpsecurity filter before spring security filter?

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.

What is the spring security filters chain?

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.

How to delegate processing to the spring security filter?

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: ... ... ...


1 Answers

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.

like image 165
Pankaj Avatar answered Oct 17 '22 02:10

Pankaj