How to store a bearer token in memory during a REST request in Spring
Learn one of the ways in which we can intercept a REST request to get the bearer token and store it in memory for later use.
1. What is a bearer token?
The bearer token is a type of access token that is used with OAuth 2.0. It is a single string that is passed in the HTTP header commonly used to authenticate a REST API request.
You can read the content of a bearer token by using this decoder https://jwt.io.
2. Java Classes
public class BearerTokenInterceptor implements HandlerInterceptor {
private BearerTokenWrapper tokenWrapper;
public BearerTokenInterceptor(BearerTokenWrapper tokenWrapper) {
this.tokenWrapper = tokenWrapper;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
final String authorizationHeaderValue = request.getHeader(“Authorization”);
if (authorizationHeaderValue != null && authorizationHeaderValue.startsWith(“Bearer”)) {
String token = authorizationHeaderValue.substring(7, authorizationHeaderValue.length());
if (tokenWrapper.getToken() == null || !token.equals(tokenWrapper.getToken())) {
tokenWrapper.setToken(token);
}
}
return true;
}
}
We need to register the interceptor class in Spring so that it can filter the REST requests we are interested in.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// register the interceptor
registry.addInterceptor(bearerTokenInterceptor());
// you can exclude certain URL patterns here, for example
// .excludePathPatterns(“/health”)
}
// the 2 methods below produces the bean for token wrapper and interceptor in request scope
@Bean
public BearerTokenInterceptor bearerTokenInterceptor() {
return new BearerTokenInterceptor(bearerTokenWrapper());
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public BearerTokenWrapper bearerTokenWrapper() {
return new BearerTokenWrapper();
}
}
To use, simply inject the token wrapper and unwrap the token.
@Autowired
private BearerTokenWrapper tokenWrapper;
tokenWrapper.getToken()
3. Testing
- Download and install Postman.
- Create a new GET request with URL http://localhost:8080/books.
- Under the Authorization tab, set the Token value. It could be any string for this demo.
- Under the Headers tab, you should be able to see an entry with Key=Authorization and Value=Bearer xxx.
- Send the request and you should be able to see a log, token=xxx.
Originally published with Git repository and video at https://www.czetsuyatech.com/2021/04/how-to-store-bearer-token-in-memory-during-a-rest-request-in-spring.html.