.net – IdentityServer4 – 在遵循Hybrid MVC的快速入门之后使用刷新令牌

我已经跟踪了文档页面中的Quickstart,并使用IdentityServer进行了三种服务(IdentityServer,一种Api服务,一种ASPNET MVC应用程序)的工作配置进行身份验证.

一切正常(登录,登录,授权等),直到access_token到期后1小时.此时,MVC应用程序开始(正确地)从API服务接收401(因为令牌已过期).那时,我知道我应该使用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_token和refresh_token恢复为主体.这是带有代码的github文件的 link,它位于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");
    }

相关文章

1.小程序的优缺点优点:不需下载、卸载使用方便缺点:嵌套在...
端口类型-HybridHybrid端口是交换机上既可以连接用户主机,又...
不同vlan同段IP通信LSW1vlan1vlan2vlan3interfaceEthernet0/...
VLAN中access、Trunk和Hybrid三种端口区别:acesss:1、发送...
这系列文章内容包括:STP、RSTP、MSTP、VLAN、LACP、SuperVL...