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

emu*_*mcu 4 c# model-view-controller

我正在创建一个 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的登录操作中,我试图更改的值

HttpContext.User.Identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ika 6

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

var identity = new ClaimsIdentity("Custom");
HttpContext.User = new ClaimsPrincipal(identity);
Run Code Online (Sandbox Code Playgroud)

设置自定义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);
Run Code Online (Sandbox Code Playgroud)

这导致:

HttpContext.User.Identity.IsAuthenticated == true;
int.Parse(((ClaimsIdentity)HttpContext.User.Identity).ValueFromType("UserId")) == 123;
Run Code Online (Sandbox Code Playgroud)

  • 我试图设置 `Identity.Name`,如果您愿意,可以这样做:将声明创建为 `new Claim(ClaimTypes.Name, "TheNameYouWant")` (6认同)