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. ...

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?   

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

2. Java Classes

public class BearerTokenInterceptor implements HandlerInterceptor {

  private BearerTokenWrapper tokenWrapper;

  public BearerTokenInterceptor(BearerTokenWrapper tokenWrapper) {
    this.tokenWrapper = tokenWrapper;

  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())) {

    return true;
We need to register the interceptor class in Spring so that it can filter the REST requests we are interested in.
public class WebMvcConfig implements WebMvcConfigurer {

  public void addInterceptors(InterceptorRegistry registry) {
  	// register the interceptor
    // 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
  public BearerTokenInterceptor bearerTokenInterceptor() {
    return new BearerTokenInterceptor(bearerTokenWrapper());

  @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.
private BearerTokenWrapper tokenWrapper;


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. 
Github Repository:


spring-rest 2159054288686233203

Post a Comment Default Comments