【问题标题】:Revoke All Refresh Tokens of User撤销用户的所有刷新令牌
【发布时间】:2017-06-15 23:57:46
【问题描述】:

我正在使用带有 asp.net Identity 的密码授予流程。

每次执行登录时,我都想杀死用户的所有刷新令牌。 即使他使用其他设备(例如其他电脑或智能手机)登录,我也需要它来终止其“会话”。

那么,我该怎么做呢?

我可以只写一个UserManager.UpdateSecurityStampAsync(user.Id);,还是我需要别的东西?

非常感谢您的帮助!

【问题讨论】:

    标签: asp.net-core openid-connect openiddict


    【解决方案1】:

    我可以做一个UserManager.UpdateSecurityStampAsync(user.Id); 还是我需要别的东西?

    这绝对是可能的。为此,只需调整您的令牌端点以要求 Identity 在返回有效令牌响应之前验证安全标记。这是一个例子:

    [HttpPost("~/connect/token"), Produces("application/json")]
    public async Task<IActionResult> Exchange(OpenIdConnectRequest request) {
        // ...
    
        if (request.IsRefreshTokenGrantType()) {
            // Retrieve the claims principal stored in the refresh token.
            var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(
                OpenIdConnectServerDefaults.AuthenticationScheme);
    
            // Retrieve the user profile and validate the
            // security stamp stored in the refresh token.
            var user = await _signInManager.ValidateSecurityStampAsync(info.Principal);
            if (user == null) {
                return BadRequest(new OpenIdConnectResponse {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The refresh token is no longer valid."
                });
            }
    
            // Ensure the user is still allowed to sign in.
            if (!await _signInManager.CanSignInAsync(user)) {
                return BadRequest(new OpenIdConnectResponse {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "The user is no longer allowed to sign in."
                });
            }
    
            // Create a new authentication ticket, but reuse the properties stored
            // in the refresh token, including the scopes originally granted.
            var ticket = await CreateTicketAsync(request, user, info.Properties);
    
            return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
        }
    
        // ...
    }
    

    或者,您也可以使用OpenIddictTokenManager 撤销与用户关联的所有刷新令牌:

    foreach (var token in await manager.FindBySubjectAsync("[userid]", cancellationToken)) {
        await manager.RevokeAsync(token, cancellationToken);
    }
    

    【讨论】:

    • 已解决...但我的代码略有不同,我想了解原因...您提到了request.IsRefreshTokenGrantType(),但我使用OpenIddictTokenManager将我的代码放入request.IsPasswordGrantType() ,因为我认为当用户进行新登录时我必须清除所有令牌。是对的,还是我做错了?
    • 第一个 sn-p 适用于您不撤销刷新令牌但由于安全标记更改而将其视为无效的情况。为了达到你想要的,第二个sn -p确实可以放在密码令牌处理代码中。
    猜你喜欢
    • 2021-11-14
    • 2021-09-24
    • 2019-04-12
    • 2015-12-13
    • 1970-01-01
    • 2018-11-14
    • 2021-07-05
    • 2022-07-05
    • 2013-09-05
    相关资源
    最近更新 更多