簡體   English   中英

ASP.NET Core 2.1如何確定沒有授權屬性的聲明?

[英]ASP.NET Core 2.1 How to determine Claims without Authorize Attribute?

我正在構建一個Web應用程序,該應用程序使用ASP.NET Core 2.1中內置的cookie身份驗證。

我有自己的登錄方法,可查詢自己的自定義密碼驗證和聲明設置。 大致如下所示:

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在所有調用上構建用戶身份,還是我采取了錯誤的方法?

看來這是一個愚蠢的錯誤。 我被調用app.UseAuthentication()app.UseMvc()配置我的應用程序生成器的時候。

該文檔實際上明確聲明以下內容:

在調用UseMvcWithDefaultRoute或UseMvc之前,先調用UseAuthentication方法

來源: https : //docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2#configuration

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM