撤消用户的所有刷新令牌

时间:2017-01-30 18:00:40

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

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

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

那么,我该怎么做呢?

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

非常感谢你的帮助!

1 个答案:

答案 0 :(得分: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);
}