Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot security oauth2 get access_token from cookie

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!

like image 352
ionutt93 Avatar asked Dec 19 '22 01:12

ionutt93


2 Answers

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());
}
like image 110
ionutt93 Avatar answered Dec 28 '22 07:12

ionutt93


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);
    }
}
like image 43
DerM Avatar answered Dec 28 '22 08:12

DerM