我目前正在实现几个Spring Boot应用程序之间的身份验证。此时,jwt访问令牌在authorization头中发送,并由资源服务器拾取。然而,我想使用HttpOnly cookies来发送令牌,我想知道如何配置Spring Boot来从cookies而不是头文件中获取令牌。
值得一提的是,我使用了spring-security-oauth2和spring-security-jwt库。
谢谢!
发布于 2018-01-26 01:11:13
通过创建我的自定义TokenExtractor并将其传递到configuration类(带有@EnableResourceServer的那个)中,我成功地从cookies中获取了令牌,如下所示:
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenExtractor(new CustomTokenExtractor());
}
发布于 2019-11-06 23:13:13
来自接受答案的CustomExtractor可能如下所示:
private class CustomExtractor implements TokenExtractor {
private static final String TOKEN_KEY_JWT = "token";
@Override
public Authentication extract(HttpServletRequest request) {
return new PreAuthenticatedAuthenticationToken(getTokenFromRequest(request), "");
}
private String getTokenFromRequest(HttpServletRequest request) {
final Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
return Arrays.stream(cookies)
.filter(cookie -> cookie.getName().equals(TOKEN_KEY_JWT))
.findFirst()
.map(Cookie::getValue).orElse(null);
}
}
https://stackoverflow.com/questions/48444906
复制相似问题