我目前正在根据授权服务器的JWK对请求进行身份验证。
我在spring-boot 2.3上使用spring-boot-starter-oauth2-resource-server
软件包。
JWT从Authorization: Bearer <token>
标头中取出,并针对JWK端点进行了验证。
我的安全配置如下:
SecurityConfig.java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
protected Environment env;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/logs").permitAll();
http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
http.oauth2ResourceServer().jwt();
}
}
application.properties
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://auth.work.com/v1/jwk
外部用户的请求中没有Authorization: ...
标头,但是具有组成JWT的以下2个cookie:
auth.token_type = Bearer
auth.access_token = <token>
如果缺少Authorization: ...
标头,是否可以从cookie中提取JWT并针对身份验证服务器进行验证?
我可以提取Cookie并在请求授权之前向请求添加标头吗?
或者它甚至可能是身份验证链中的第二种方法。
答案 0 :(得分:1)
我认为您可以使用自定义过滤器,拦截请求并从HttpServletRequest获取cookie。
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
Cookie[] cookies = request.getCookies();
// Your validation logic
}
只需将其添加到Spring Security过滤器链中即可。
更多详细信息,请点击此处:https://www.baeldung.com/spring-security-custom-filter
答案 1 :(得分:0)
我发现了有关自定义令牌解析器的信息,并最终创建了一个用于验证标头和cookie的解析器。我不确定这是否是最干净的解决方案,但是可以。
我唯一遇到的问题是它不再自动验证Authorization: Bearer ...
标头,因此我也必须为其添加代码。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/logs").permitAll();
http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
http.oauth2ResourceServer().jwt().and().bearerTokenResolver(this::tokenExtractor);
}
public String tokenExtractor(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null)
return token.replace("Bearer ", "");
Cookie cookie = WebUtils.getCookie(request, "auth.access_token");
if (cookie != null)
return cookie.getValue();
return null;
}
}