rest - 如何设置过滤器以处理并非所有请求?
问题描述
我正在使用 Spring Core、Spring MVC、Spring REST、JWT。
大家好!
我正在学习 Spring Security,但遇到了问题。
我想做一个基于 JWT 的认证;我有一个带有 3 种简单方法的 Rest 控制器:
第一种方法应该适用于所有人,第二种方法仅适用于登录用户,第三种方法仅适用于管理员。虽然这有效,但我还有另一个问题。
问题是我的过滤器在每次启动后都会抛出(不是直接的,因为 null 是由返回的token = header.substring(7)
)a 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
“适用于”每个请求。
这一行:
http.authorizeRequests()
.antMatchers("/api/test2").authenticated()
.antMatchers("/api/test3").hasRole("ADMIN")
...
...不会阻止请求通过FilterChain
. 它只是允许匹配这些路径的请求通过过滤器而不经过身份验证。但是您注册的每个过滤器(如JwtFilter
)都会被调用。
解决方案
您可以通过覆盖以下方法来禁用整个FilterChain
请求:configure(WebSecurity)
WebSecurityConfigurerAdapter
@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);
}
// ...
}
推荐阅读
- ios - UITableViewRowAction 的图标在 iOS 13 上显示,但在 iOS 12 上不显示
- python-3.x - 未知时区警告的任何解决方案?
- java - JDialog弹出警告未显示
- openlayers - wkt字符串中的openlayer点符号
- angular - Angular 8:如何获取表的过滤值的索引
- javascript - 使用 S3 Select 数据的 Alexa Skill
- scala - 基于Spark Scala中的条件转置Dataframe中的特定列和行
- c# - 向我在代码 c# wpf 中创建的椭圆添加动画
- react-native - 签名的发布 apk 未使用 android studio 生成本机反应
- haskell - 类型安全模块化算法无注释