【问题标题】:How to set filter to process not all requests?如何设置过滤器以处理并非所有请求?
【发布时间】:2020-06-14 20:50:45
【问题描述】:

我正在使用 Spring Core、Spring MVC、Spring REST、JWT。

大家好!

我在学习 Spring Security,遇到了一个问题。

我想做一个基于 JWT 的认证;我有一个带有 3 个简单方法的 Rest 控制器:

第一种方法应该对所有人都可用,第二种方法仅适用于登录用户,第三种方法仅适用于管理员。虽然这样可行,但我还有另一个问题。

问题是我的过滤器每次启动后都会抛出(不是直接,因为 null 是由token = header.substring(7) 返回的)NullPointerException,即使它还没有收到任何请求(我可能是错的,我希望代码能澄清它)。是否可以设置过滤器以仅处理选定的请求,或者我的方法可能是错误的?

感谢您的帮助!

错误:

java.lang.NullPointerException
    at com.sample.config.JwtFilter.getAuthenticationByToken(JwtFilter.java:50)
    at com.sample.config.JwtFilter.doFilterInternal(JwtFilter.java:36)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Unknown Source)

我的JwtFilter

public class JwtFilter extends BasicAuthenticationFilter {

    public JwtFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);

    }

    @Override   
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String header=request.getHeader("authorization");
        UsernamePasswordAuthenticationToken authResult=getAuthenticationByToken(header);

        SecurityContextHolder.getContext().setAuthentication(authResult);

        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthenticationByToken(String header) {
            String token = header.substring(7);
            Jws<Claims> claims = Jwts.parser().setSigningKey("fQx]n}YmL)WuHjL".getBytes()).parseClaimsJws(token);

            String username=claims.getBody().get("name").toString();
            String role = claims.getBody().get("role").toString();
    return new UsernamePasswordAuthenticationToken(username,null,Collections.singleton(new SimpleGrantedAuthority(role)));      
    }

}

我的配置:


@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return new AuthenticationManager() {

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                return null;
            }
        };
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/test2").authenticated()      .antMatchers("/api/test3").hasRole("ADMIN")
        .and()
        .addFilter(new JwtFilter(authenticationManager())); }
}

public class SpringSecurityWebInitializer extends AbstractSecurityWebApplicationInitializer{

}

控制器:


@RestController
@RequestMapping("/api")
public class TestApi {

    @GetMapping("/test1")
    public String test1()
    {
        return "test1";//for everyone
    }

    @GetMapping("/test2")
    public String test2()
    {
        return "test2";//only for logged in
    }

    @GetMapping("/test3")
    public String test3()
    {
        return "test3";//only for admins 
    }   
}

【问题讨论】:

    标签: rest spring-mvc spring-security jwt spring-rest


    【解决方案1】:

    按照您配置应用程序的方式,将为每个请求调用您的过滤器,因为安全性FilterChain“适用于”每个请求。

    这一行:

    http.authorizeRequests()
            .antMatchers("/api/test2").authenticated()      
            .antMatchers("/api/test3").hasRole("ADMIN")
            ...
    

    ... 不会阻止请求通过FilterChain。它只是允许匹配这些路径的请求通过过滤器而不经过身份验证。但是您注册的每个过滤器(例如JwtFilter)都会被调用。

    解决方案

    您可以通过覆盖WebSecurityConfigurerAdapter 中的configure(WebSecurity) 方法来为某些请求禁用整个FilterChain

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().mvcMatchers(...);
    }
    

    但在您的情况下,最好更改您的过滤器,以便它根据传入请求的路径跳过某些请求。您可以执行以下操作:

    public class JwtFilter extends BasicAuthenticationFilter {
        private AntPathRequestMatcher filterPath;
    
        // the path you provide will restrict the filter to only be "applied"
        // to requests with that path
        public JwtFilter(AuthenticationManager authenticationManager, String path) {
            super(authenticationManager);
            this.filterPath = new AntPathRequestMatcher(path);
        }
    
        @Override   
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    
            // the filter will do nothing if the request doesn't match
            if(!filterPath.matches(request) {
                chain.doFilter(request, response);
            }
    
            // your filter logic goes here...
    
            chain.doFilter(request, response);
        }
    
        // ...
    }
    
    
    

    【讨论】:

    • 非常感谢!根据您的建议,我做了一些更正: if (header == null) { chain.doFilter(request, response); } 现在它开始工作了!
    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2013-07-15
    • 2012-09-16
    • 1970-01-01
    • 2013-05-25
    相关资源
    最近更新 更多