添加在spring security中添加请求头的自定义筛选器
我使用spring security通过jwt处理身份验证,jwt在请求头中传递:添加在spring security中添加请求头的自定义筛选器,spring,spring-security,jwt,Spring,Spring Security,Jwt,我使用spring security通过jwt处理身份验证,jwt在请求头中传递: public class JwtAuthConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement() .sessionCre
public class JwtAuthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt();
}
}
现在,JWT令牌以cookie的形式传递给我的应用程序。我编写了一个过滤器,从cookie中获取jwt并将其添加到请求的头中:
@Component
public class JwtCookieFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse)res;
Cookie[] cookies = request.getCookies();
String jwt = this.getTokenFromCookie(cookies); // Inner method
if(jwt == null)
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
HttpRequestWithHeaders requestWithHeaders = new HttpRequestWithHeaders (request);
HttpRequestWithHeaders .addHeader("Authorization",jwt);
chain.doFilter(requestWithHeaders, response);
}
现在我不确定我的过滤器应该运行哪一步(springSecurity中的configure方法)。我尝试使用以下命令,但始终出现401错误(未被忽略):
我建议那些不熟悉Spring Security的人阅读 归根结底,SpringSecurity就像一个防火墙,包含一系列过滤器。您的请求将进入链,并尝试通过那里的过滤器 我创建的过滤器搜索cookie并在请求头中设置cookie的值。因为ServletRequest类没有setter方法,所以需要用 完成所有这些之后,剩下的最后一件事是在configure方法中添加过滤器:
@Configuration
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//configuring strategy
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt();
http.addFilterBefore(new JwtCookieFilter(), UsernamePasswordAuthenticationFilter.class);
}
请注意,configure中的所有调用实际上并没有运行任何东西,它们只是设置了spring将用于传入请求的“链”/“过滤器”
@Configuration
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//configuring strategy
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt();
http.addFilterBefore(new JwtCookieFilter(), UsernamePasswordAuthenticationFilter.class);
}