[英]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.我有一个 CustomAuthenticationProvider,它使用用户名和密码向 API 发出 POST 请求以进行身份验证,API 返回一个带有到期时间的访问令牌。
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.我在哪里设置这个令牌,所以只要用户登录,我就可以使用相同的令牌进一步调用 API。我还想在发出另一个请求之前验证令牌的到期时间。
Is it right approach to add the token to a customAuthenticationToken that extends UsernamePasswordAuthenticationToken and set it in the SecurityContext.将令牌添加到扩展 UsernamePasswordAuthenticationToken 的 customAuthenticationToken 并将其设置在 SecurityContext 中是否是正确的方法。
Please let me know your suggestions.请让我知道您的建议。
The token needs to be in the 'authorization' header for all calls.令牌需要在所有调用的“授权”header 中。 The value should be 'Bearer ' + token.
该值应为“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将授权承载 header 添加到来自 Spring 的所有调用引导取决于客户端的种类,例如
HttpClient httpClient= new HttpClient()
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
Where the token
is stored as a, probably static
, variable somewhere. token
在某处存储为变量的位置,可能是static
。
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在服务器端,您需要一个过滤器来验证令牌并将请求标记为已授权 - 相当多的工作 - 看这里
Well, if you need to call another REST API, then you need to set up an http client.那么,如果你需要调用另一个REST API,那么你需要设置一个http客户端。 Since you use Spring Boot 3, WebClient is a default option, but the flow is the same for any client.
由于您使用 Spring Boot 3, WebClient是默认选项,但流程对于任何客户端都是相同的。
You basically store your token anywhere in memory, implement isExpired check and refresh logic.您基本上将令牌存储在 memory 中的任何位置,实施 isExpired 检查和刷新逻辑。
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.然后使用自定义过滤器设置您的客户端,以便每次调用 API 时,它都会检查令牌是否过期并在过期时刷新它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.