我已经跟踪了文档页面中的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中以便将来的请求可以访问新的令牌?
5 回答
McvHybrid样本有一个很好的例子,可以让新的
access_token
和refresh_token
重新进入校长 . 这是带有代码的github文件的link,该文件位于RenewTokens()
,如下所示 .作为来自MVC Client example的RenewTokens方法的一个选项,我做了一个过滤器,当令牌大约10分钟或更短时间到期时,该过滤器自动生成作业 .
用法:
首先,一定要使用IdentityModel库(nuget it) . 其次,由于Auth 2.0已经出现,因此Rafaels解决方案中使用的HttpContext.Authentication现在已经过时 . 以下是应该进行的更改,以便再次将其作为过滤器运行
应成为:
应成为:
应该成为
应该成为
应该成为
这是一个完整的代码:
Usage和Rafael所说的相同 .
当令牌的一半以上生命通过时,我制作了自动完成工作的中间件 . 因此,您无需调用任何方法或应用任何过滤器 . 只需将其插入Startup.cs并涵盖整个应用程序:
UseAutomaticSilentRenew - 续订访问权限并刷新令牌
UseAccessTokenLifetime - 如果访问令牌已过期,则退出用户 . 只需在UseAutomaticSilentRenew之前无法获取新的访问令牌时,将其放在第二位 .
执行:
Note :我没有't set cookie expiration time because in our case it depends on refresh token lifetime witch is not provided by identity server. If I aligned the expiration of the cookie with the expiration of the access token I would'能够在到期后刷新访问令牌 .
哦,还有一件事 . UseAccessTokenLifetime清除cookie但不会注销用户 . 重新加载页面后退出 . 没有找到解决方法 .
你提供给https://github.com/mderriey/TokenRenewal/blob/master/src/MvcClient/Startup.cs的链接对我有帮助!
问题出在AddOpenIdConnect部分 . 您想要的事件不是OnTokenValidated事件 . 您应该使用OnTokenResponseReceived事件 . 就在这时,您将有一个适当的access_token和refresh_token来添加到cookie .