How to store a bearer token in memory during a REST request in Spring

czetsuya
2 min readMay 16, 2021

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

  1. Download and install Postman.
  2. Create a new GET request with URL http://localhost:8080/books.
  3. Under the Authorization tab, set the Token value. It could be any string for this demo.
  4. Under the Headers tab, you should be able to see an entry with Key=Authorization and Value=Bearer xxx.
  5. 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.

--

--

czetsuya

Open for Collaboration | Senior Java Backend Developer