问题
On servicestack it says that for regular client it should be like that but for typescript it should be somehow different. Anyone knows how to do it?
var client = new JsonServiceClient(baseUrl);
client.OnAuthenticationRequired = () => {
client.BearerToken = authClient.Send(new Authenticate()).BearerToken;
};
回答1:
Support for onAuthenticationRequired
and refreshToken
was added to the TypeScript servicestack-client in v0.0.32 where they can be used to transparently handle 401 Unauthorized Responses and re-authenticate the JsonServiceClient
from within the callback before it automatically retries the original failed request:
Transparently handle 401 Unauthorized Responses
If the server returns a 401 Unauthorized Response either because the client was Unauthenticated or the configured Bearer Token or API Key used had expired (or was invalidated), you can use onAuthenticationRequired
callback to re-configure the client before automatically retrying the original request, e.g:
client.onAuthenticationRequired = async () => {
const authClient = new JsonServiceClient(authBaseUrl);
authClient.userName = userName;
authClient.password = password;
const response = await authClient.get(new Authenticate());
client.bearerToken = response.bearerToken;
};
//Automatically retries requests returning 401 Responses with new bearerToken
var response = await client.get(new Secured());
Automatically refresh JWT Tokens
With the Refresh Token support in JWT you can use the refreshToken
property to instruct the Service Client to automatically fetch new JWT Tokens behind-the-scenes before automatically retrying failed requests due to invalid or expired JWTs, e.g:
//Authenticate to get a new Refresh Token
const authClient = new JsonServiceClient(authBaseUrl);
authClient.userName = userName;
authClient.password = password;
const authResponse = await authClient.get(new Authenticate());
//Configure client with RefreshToken
client.refreshToken = authResponse.RefreshToken;
//Clients will automatically retrieve new JWT Tokens as needed
var response = await client.get(new Secured());
Send Refresh Tokens to an alternate server
Use the refreshTokenUri
property when refresh tokens need to be sent to a different ServiceStack Server that issues new JWT Tokens, e.g:
client.refreshToken = refreshToken;
client.refreshTokenUri = authBaseUrl + "/access-token";
来源:https://stackoverflow.com/questions/43095377/how-to-refresh-token-servicestack-typescript