如何在IdentityServer 4中使用"refresh_token"? [英] How to use 'refresh_token' in IdentityServer 4?
问题描述
我将Identity Server 4与.net core一起使用.我有一个Web api,还有一个MVC应用程序,可以访问api上的安全端点.设置与IdentityServer快速入门非常相似:
I'm using .net core with IdentityServer 4. I have a Web api, and an MVC app which accesses secure endpoints on the api. It's very similar in setup to the IdentityServer quickstart:
https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/6_AspNetIdentity
我发现我的access_tokens
即将到期,并且我想了解如何重新协商refresh_tokens
.
I'm finding that my access_tokens
are expiring, and I'd like to understand how to renegotiate refresh_tokens
.
以以下代码为例(摘自快速入门此处):
Take the following code for example (taken from the quickstart here):
public async Task<IActionResult> CallApiUsingUserAccessToken()
{
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
var client = new HttpClient();
client.SetBearerToken(accessToken);
var content = await client.GetStringAsync("http://localhost:5001/identity");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
如果access_token
已过期,它将失败并显示401响应.是否有内置的机制可以使用refresh_token
重新协商access_token
?
If the access_token
has expired, it will fail with 401 response. Is there a built-in mechanism for re-negotiating the access_token
using the refresh_token
?
推荐答案
没有内置的系统可以刷新access_token
.但是,您可以使用IdentityModel
包来请求带有refresh_token
的新的access_token
.
There is not a build in system to refresh the access_token
. However you can use the IdentityModel
package to request a new access_token
with a refresh_token
.
Client
具有属性AllowOfflineAccess
,您应该在IdentityServer中将其设置为true.请注意,对于隐式/客户端凭据流,这不不起作用.
The Client
has a property AllowOfflineAccess
which you should set to true in the IdentityServer. Note that this does not work for the implicit/client credentials flow.
- 始终在调用受保护资源之前刷新access_token
- 通过检查其寿命来检查当前
access_token
是否即将到期,并使用refresh_token
(个人喜好)请求新的access_token
(个人喜好) - 等待API返回带有
refresh_token
的新access_token
的401广告请求
- Always refresh the access_token prior to making the call to the protected resource
- Check if the current
access_token
is about to expire by checking its lifetime and request a newaccess_token
with therefresh_token
(personal preference) - Wait for the API to return the 401 ad request a new
access_token
with therefresh_token
在此代码之前,您可以检查access_token
生存期和/或将此代码包装在服务中,然后再请求新的access_token
Prior to this code you can check the access_token
lifetime and/or wrap this code in a service before you request a new access_token
var discoveryResponse = await DiscoveryClient.GetAsync("IdentityServer url");
if (discoveryResponse.IsError)
{
throw new Exception(discoveryResponse.Error);
}
var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "ClientId", "ClientSecret");
// This will request a new access_token and a new refresh token.
var tokenResponse = await tokenClient.RequestRefreshTokenAsync(await httpContext.Authentication.GetTokenAsync("refresh_token"));
if (tokenResponse.IsError)
{
// Handle error.
}
var oldIdToken = await httpContext.Authentication.GetTokenAsync("id_token");
var tokens = new List<AuthenticationToken>
{
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.IdToken,
Value = oldIdToken
},
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.AccessToken,
Value = tokenResult.AccessToken
},
new AuthenticationToken
{
Name = OpenIdConnectParameterNames.RefreshToken,
Value = tokenResult.RefreshToken
}
};
var expiresAt = DateTime.UtcNow.AddSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken
{
Name = "expires_at",
Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
});
// Sign in the user with a new refresh_token and new access_token.
var info = await httpContext.Authentication.GetAuthenticateInfoAsync("Cookies");
info.Properties.StoreTokens(tokens);
await httpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties);
取自并稍作修改:来源
这篇关于如何在IdentityServer 4中使用"refresh_token"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!