4
votes

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!

2
Hi, I'm quite new to the Spring Boot framework, so I don't really know where to start to be honest :). I've set up a configuration class (following a tutorial) which configures the httpSecurit and tokenServices. But I don't know at which point the token get's extracted from the request.ionutt93
Why do you want to use the cookie instead of the HTTP Authorization header (bearer)? You probably want to send the token only with API calls, not every request (cookies).Ján Halaša
I've been reading articles on JWT tokens and most of them recommend storing the token in a httpOnly cookie as it can't be accessed through js and is more secure. What do you think?ionutt93
i dont think this is good approach but why did you do that ?Mithat Konuk

2 Answers

8
votes

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());
}
3
votes

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);
    }
}