【问题标题】:ASP.NET Identity and validation of a custom claim自定义声明的 ASP.NET 标识和验证
【发布时间】:2018-04-26 08:13:12
【问题描述】:

我将 ASP.NET Identity 与 MVC 结合使用,并且我为每个登录用户的每个设备设置了一个 sessionId(GuId 字符串)。这个想法是用户可以删除设备会话,然后该设备将不再登录(就像在 Dropbox 和 google 中所做的那样)。

目前,我将此 sessionId 设置为 ASP.NET Identity 中的声明,因此它在身份验证 cookie 中传递。

对于身份验证,我使用 ASP.NET Identity 作为示例:app.UseCookieAuthentication(new CookieAuthenticationOptions{....

我的问题:

  1. 在这里将我的 sessionId 设置为声明是否正确?

  2. 另外,在整个身份验证过程中,我可以在哪里验证该 sessionId 的声明?

  3. 我目前的想法是针对每个请求的数据库表验证此 sessionId。我应该使用 Request.Sessions 来存储 sessionId,还是这里有任何其他想法?

谢谢,

【问题讨论】:

  • 不确定,否则这会对您有所帮助。但是在创建 MVC 项目时,您可以选择设置身份验证方法。那应该生成示例代码。对于跟踪用户的情况,我认为这应该是一种可接受的方法。
  • 通过 ASP.NET Identity 我使用 app.UseCookieAuthentication(new CookieAuthenticationOptions{.... 我应该如何使用这个选项来验证我的 sessionIds?
  • 我在之前的回答中应该提到的一点:如果您想在任何地方为用户签名,您所要做的就是更改 AspNetUser 表中安全标记的值。 SecurityStampValidator 根据这个值检查 auth cookie,如果它发生变化,则将其注销

标签: c# asp.net-mvc asp.net-identity-2


【解决方案1】:

由于用户可以拥有多个有效会话,因此您需要将它们存储为声明或创建自己的表来存储它们。由于声明已经由 Identity 创建,这将是最简单的。

您可以在 Startup.Auth.cs 中的 CookieAuthenticationProviderOnValidateIdentity 方法中验证这一点。目前这会调用SecurityStampValidatorOnValidateIdentity 方法,因此您需要编写一个包装器方法,该方法首先检查您的会话ID,然后调用原始安全标记验证器。例如,您可以将这些方法添加到 Startup 类中:

private Func<CookieValidateIdentityContext, System.Threading.Tasks.Task> _validate=SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
           validateInterval: TimeSpan.FromMinutes(30),
           regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager));
private async Task validate(CookieValidateIdentityContext context)
{
    var usermanager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    var claims = await usermanager.GetClaimsAsync(context.Identity.GetUserId());

    //instead of setting to true, add your session validation logic here
    bool sessionIsValid=true;

    if (!sessionIsValid) {
        context.RejectIdentity();
        context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType);
    }

    await _validate(context);
}

其中_validate 只是原始方法,validate 是您的新方法,它还检查会话 ID。然后您的app.UseCookieAuthentication 代码将引用新的validate 方法,如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = validate

    }
});  

为了完成这项工作,我认为您每次都需要检查数据库中的声明,但我相信 usermanager.GetClaimsAsync 最终会这样做。

【讨论】:

    猜你喜欢
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多