Search code examples
javaspring-bootspring-securityaccess-tokenbearer-token

How do I use the BearerToken in all subsequent calls to the API after authenticating using username & password


I have a CustomAuthenticationProvider that does a POST request to an API with username and password for authentication and the API returns an access token with expiry time.

Where do I set this token, so I can use the same token to make further calls to the API as long as the user is logged in. I also wanted to validate the token for expiry time before making another request.

Is it right approach to add the token to a customAuthenticationToken that extends UsernamePasswordAuthenticationToken and set it in the SecurityContext.

Please let me know your suggestions.


Solution

  • Well, if you need to call another REST API, then you need to set up an http client. Since you use Spring Boot 3, WebClient is a default option, but the flow is the same for any client.

    You basically store your token anywhere in memory, implement isExpired check and refresh logic.

    class TokenStorage {
        private String token;
    
        void refreshToken() { 
            var newToken = ...;
            this.token = newToken;
        } 
    
        boolean isExpired() { ... }
    
        String getToken() { 
            return token;
        } 
    }
    

    And then setup your client with custom filter so that everytime you call API, it checks whether token is expired and refreshes it if so.