首页 文章

ASP.NET Core 2.1如何在没有授权属性的情况下确定声明?

提问于
浏览
1

我正在构建一个使用ASP.NET Core 2.1内置的cookie身份验证的Web应用程序 .

我有自己的登录方法,可以查询我自己的自定义密码验证和设置索赔 . 大致它看起来像这样:

public async Task<ActionResult<LoginResponse>> DoLogin([FromBody] LoginRequest req)
{
    // fetch account and verify password

    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Sid, account.AccountId.ToString(), ClaimValueTypes.Integer),
        new Claim(ClaimTypes.Email, account.EmailAddress, ClaimValueTypes.Email),
        new Claim(ClaimTypes.Role, "member", ClaimValueTypes.String)
    };

    var identity = new ClaimsIdentity(claims, "password");
    var principal = new ClaimsPrincipal(identity);

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

    return new LoginResponse
    {
        Success = true
    };
}

如果用户拥有验证用户身份的cookie,我想在网站的各个部分有条件地呈现“注销”按钮 . 此外,我想获取Sid声明,以便我可以在网站的某些公共部分提供个性化消息 .

我遇到的问题是,只有我的控制器或控制器操作具有 [Authorize] 属性时,我才能获取Sid的方式 . 如果没有 [Authorize] 属性,则缺少声明 .

码:

public static int? GetNullableAccountId(this ClaimsPrincipal principal)
{
    var claim = principal.FindFirst((Claim c) => { return c.Type == ClaimTypes.Sid; });

    if (claim == null)
        return null;

    return int.Parse(claim.Value);
}

// then in the controller I try to get the account id:
var accountId = accessor.HttpContext.User.GetNullableAccountId();
// always null even when I have a valid cookie

我发誓,我不需要 [Authorize] 属性,以便在以前版本的ASP.NET Core中工作,但我在更改日志中找不到任何有意义的内容 .

是否有一些技巧可以让ASP.NET Core在所有调用中构建用户身份,或者我是否采取了错误的方法?

1 回答

相关问题