【问题标题】:Exclude authentication to pass by filter In spring security在spring security中排除身份验证以通过过滤器
【发布时间】:2020-04-06 18:18:28
【问题描述】:

我想从过滤器中排除一个 url。除了每次我发出身份验证请求时,我都添加了许可,它通过了过滤器。顺便说一句,当我删除过滤器时,它会进行身份验证。我的目标是排除一些网址通过过滤器。这是我的配置和过滤器的代码:

@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);

    }
}

这是我的过滤器代码:

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);
        }
    }

}

【问题讨论】:

  • 您要从过滤器中排除哪种 URL

标签: java spring-boot spring-security jwt


【解决方案1】:

如果请求的路径与您想要绕过的路径列表匹配并委托给下一个过滤器,您可以在自定义过滤器本身中提供逻辑以跳过

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



}

【讨论】:

    【解决方案2】:

    如果你想从 Spring Security 的 filterChain 中完全排除 URL,只需覆盖

    configure(WebSecurity web) 
    

    方法。

    例子:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(final WebSecurity web) throws Exception {
            web.ignoring()
               .antMatchers("/yourUrls/**");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 2013-02-23
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多