I'm currently implementing the authentication between several Spring Boot applications. At the moment, the jwt access token is sent in the authorization header and it is picked up by the resource server. However I would like to use HttpOnly cookies to send the tokens and was wondering how do you configure Spring Boot to get the token from cookies instead of the headers.
I should mention that I'm using the spring-security-oauth2 and spring-security-jwt libraries.
Thank you!
Managed to get the token from the cookies by creating my custom TokenExtractor and passing that in configuration class (the one with @EnableResourceServer) like the following:
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenExtractor(new CustomTokenExtractor());
}
The CustomExtractor from the accepted answer might look like this:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With