如何设置过滤器以处理并非所有请求?
How to set filter to process not all requests?
我正在使用 Spring Core,Spring MVC,Spring REST,JWT。
大家好!
我正在学习 Spring 安全,但我遇到了问题。
我想做基于JWT的鉴权;我有一个带有 3 个简单方法的 Rest 控制器:
第一种方法应该适用于所有人,第二种方法仅适用于登录用户,第三种方法仅适用于管理员。虽然这很有效,但我还有另一个问题。
问题是我的过滤器每次启动后都会抛出(不是直接抛出,因为 token = header.substring(7)
返回 null)一个 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
}
}
按照您配置应用程序的方式,将为每个请求调用您的过滤器,因为每个请求的安全性 FilterChain
"applies"。
这一行:
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);
}
// ...
}
我正在使用 Spring Core,Spring MVC,Spring REST,JWT。
大家好!
我正在学习 Spring 安全,但我遇到了问题。
我想做基于JWT的鉴权;我有一个带有 3 个简单方法的 Rest 控制器:
第一种方法应该适用于所有人,第二种方法仅适用于登录用户,第三种方法仅适用于管理员。虽然这很有效,但我还有另一个问题。
问题是我的过滤器每次启动后都会抛出(不是直接抛出,因为 token = header.substring(7)
返回 null)一个 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
}
}
按照您配置应用程序的方式,将为每个请求调用您的过滤器,因为每个请求的安全性 FilterChain
"applies"。
这一行:
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);
}
// ...
}