fbm fatma
fbm fatma

Reputation: 450

Exclude authentication to pass by filter In spring security

I want to exclude an url from passing by the filter. I added the permit all but every time I make an authentication request it passes by the filter. By the way, when I remove the filter it makes an authentication. The goal for me is excluding some urls from passing through the filter. This is my config and my filter 's code :

@EnableWebSecurity
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter{

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
      return authenticationManager();
    }   
    @Autowired
    private JwtRequestFilter jwtRequestFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/AuthentificationController/**").permitAll()
        .antMatchers("/swagger-ui.html").permitAll()
        .anyRequest().authenticated()
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterAfter(jwtRequestFilter,  UsernamePasswordAuthenticationFilter.class);

    }
}

This is my filter's code:

package tn.afriquecarglass.gestionstock.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import tn.afriquecarglass.gestionstock.util.JwtUtil;
import tn.afriquecarglass.gestionstock.util.MyUserDetailsService;

@Component
public class JwtRequestFilter extends OncePerRequestFilter{

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");
        String username = null;
        String jwt = null;
        if(authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }
        if(username!=null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(username);
            if(jwtUtil.validateToken(jwt, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
            filterChain.doFilter(request, response);
        }
    }

}

Upvotes: 0

Views: 3369

Answers (2)

Marco Behler
Marco Behler

Reputation: 3724

If you want to completely exclude the URL from Spring Security's filterChain, simply override the

configure(WebSecurity web) 

method.

Example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(final WebSecurity web) throws Exception {
        web.ignoring()
           .antMatchers("/yourUrls/**");
    }
}

Upvotes: 0

S.Step
S.Step

Reputation: 439

You can provide logic in your custom filter itself to be skipped if requested path matches your list of paths you want to be bypassed and delegate to the next filter

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse 
response, FilterChain filterChain)
        throws ServletException, IOException {

    final String authorizationHeader = request.getHeader("Authorization");
    String username = null;
    String jwt = null;

    String reqPath = request.getRequestURI();

    // If not matched then continue to the next filter
    if ("/path_to_skipp".equals(reqPath )) {
         filterChain.doFilter(request, response);
       return;
    }

   // rest of your logic
   ...



}

Upvotes: 1

Related Questions