2

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

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

那么,我该怎么做呢?

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

非常感谢你的帮助!

4

1 回答 1

2

我可以做一个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);
}
于 2017-01-30T20:08:28.417 回答