我正在使用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
}
}
您配置应用程序的方式,将为每个请求调用过滤器,因为安全性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);
}
// ...
}