gpt4 book ai didi

.net - IdentityServer4 - 按照混合 MVC 快速入门后使用刷新 token

转载 作者:行者123 更新时间:2023-12-02 18:04:09 25 4
gpt4 key购买 nike

我已按照文档页面中的快速入门进行操作,并使用 IdentityServer 进行身份验证,对三项服务(IdentityServer、一项 Api 服务、一项 ASPNET MVC 应用程序)进行了工作配置。

一切正常(登录、登录、授权等),直到 1 小时后 access_token 过期。此时,MVC 应用程序开始(正确)从 API 服务接收 401(因为 token 已过期)。那时,我知道我应该使用refresh_token来获取新的access_token。

我正在寻找一种自动刷新 access_token 的机制,并偶然发现了这个:https://github.com/mderriey/TokenRenewal/blob/master/src/MvcClient/Startup.cs (来自this answer)。我尝试使用它,但它不起作用(即使身份验证成功,TokenEndpointResponse 仍为 null)。

我了解如何使用refresh_token来获取新的access_token,但是在我拥有它之后,我将如何将它插入回cookie中,以便将来的请求有权使用新代币吗?

最佳答案

McvHybrid 示例提供了一个很好的示例,用于将新的 access_tokenrefresh_token 返回主体。这是 link将代码复制到 github 文件,该文件位于 RenewTokens() 中,如下所示。

    public async Task<IActionResult> RenewTokens()
{
var disco = await DiscoveryClient.GetAsync(Constants.Authority);
if (disco.IsError) throw new Exception(disco.Error);

var tokenClient = new TokenClient(disco.TokenEndpoint, "mvc.hybrid", "secret");
var rt = await HttpContext.Authentication.GetTokenAsync("refresh_token");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(rt);

if (!tokenResult.IsError)
{
var old_id_token = await HttpContext.Authentication.GetTokenAsync("id_token");
var new_access_token = tokenResult.AccessToken;
var new_refresh_token = tokenResult.RefreshToken;

var tokens = new List<AuthenticationToken>();
tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token });
tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token });
tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token });

var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });

var info = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies");
info.Properties.StoreTokens(tokens);
await HttpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties);

return Redirect("~/Home/Secure");
}

ViewData["Error"] = tokenResult.Error;
return View("Error");
}

关于.net - IdentityServer4 - 按照混合 MVC 快速入门后使用刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41741982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com