Home > Back-end >  How do I use the BearerToken in all subsequent calls to the API after authenticating using username
How do I use the BearerToken in all subsequent calls to the API after authenticating using username

Time:01-28

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.

CodePudding user response:

The token needs to be in the 'authorization' header for all calls. The value should be 'Bearer ' token. If you are using a browser it gets a bit messy - let me know.

To add the authorization bearer header to all calls from Spring Boot depends on the sort of client, eg

HttpClient httpClient= new HttpClient()
httpClient.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", token);

Where the token is stored as a, probably static, variable somewhere.

In the server side you need a Filter that validates the token and marks the request as authorised - quite a bit of work - look here

CodePudding user response:

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.

  • Related