no

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

This class intercepts REST requests, gets the bearer token, and store it in memory. public class BearerTokenInterceptor extends HandlerInte...

This class intercepts REST requests, gets the bearer token, and store it in memory.
public class BearerTokenInterceptor extends HandlerInterceptorAdapter {

  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 with.
@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()

Related

coding 2159054288686233203

Post a Comment Default Comments

item