撤销用户的所有刷新令牌

Revoke All Refresh Tokens of User

我正在使用密码授予流程,具有 asp.net 身份。

我想在每次执行登录时终止用户的所有刷新令牌。 我需要这个来杀死它 "session" 即使他使用不同的设备登录,比如其他电脑或智能手机。

那么,我该怎么做呢?

我可以只做一个 UserManager.UpdateSecurityStampAsync(user.Id);,还是我需要其他东西?

非常感谢您的帮助!

Can I just do a UserManager.UpdateSecurityStampAsync(user.Id); or I need something else?

这绝对有可能。为此,只需调整您的令牌端点以要求 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);
}