gpt4 book ai didi

c# - ASP.NET Core 2.1 如何确定没有授权属性的声明?

转载 作者:行者123 更新时间:2023-11-30 21:31:08 25 4
gpt4 key购买 nike

我正在构建一个 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 声明,以便我可以在网站的某些公共(public)部分提供个性化消息。

我遇到的问题是,只有当我的 Controller 或 Controller 操作具有 [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.UseMvc() 之后调用了 app.UseAuthentication()

文档实际上明确说明了以下内容:

Call the UseAuthentication method before calling UseMvcWithDefaultRoute or UseMvc

来源:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2#configuration

关于c# - ASP.NET Core 2.1 如何确定没有授权属性的声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com