gpt4 book ai didi

c# - 如何手动设置 HttpContext.User.Identity.IsAuthenticated 的值

转载 作者:行者123 更新时间:2023-12-04 01:46:19 24 4
gpt4 key购买 nike

我正在创建一个 Asp.NET MVC 5 应用程序。对于这个项目,我正在尝试实现自定义身份验证机制(我不想使用表单例份验证/OWIN 等外部提供程序)

我创建了一个自定义授权属性,如下所示:

[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class myAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!HttpContext.Current.Request.IsAuthenticated)
{
httpContext.Response.Redirect("~/Account/Login");
}

return base.AuthorizeCore(httpContext);
}
}

在我的登录操作中,我试图更改的值
HttpContext.User.Identity.IsAuthenticated

但它是只读的,我无法更改该值。我可以手动更改它的值还是我犯了一个逻辑错误。

最佳答案

您可以通过手动设置 HttpContext.User 来实现:

var identity = new ClaimsIdentity("Custom");
HttpContext.User = new ClaimsPrincipal(identity);

设置自定义很重要 authenticationType .在上面的例子中,我只使用了字符串“Custom”,但它可以是任何你想要的。

这样, HttpContext.User.Identity.IsAuthenticated将是 true .

对于更复杂的事情,您可以添加如下声明:
var identity = new ClaimsIdentity(new List<Claim>
{
new Claim("UserId", "123", ClaimValueTypes.Integer32)
}, "Custom");

HttpContext.User = new ClaimsPrincipal(identity);

这导致:
HttpContext.User.Identity.IsAuthenticated == true;
int.Parse(((ClaimsIdentity)HttpContext.User.Identity).ValueFromType("UserId")) == 123;

关于c# - 如何手动设置 HttpContext.User.Identity.IsAuthenticated 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55121548/

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