【问题标题】:How to manually set value of HttpContext.User.Identity.IsAuthenticated如何手动设置 HttpContext.User.Identity.IsAuthenticated 的值
【发布时间】:2019-03-12 12:31:15
【问题描述】:

我正在创建一个 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

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

【问题讨论】:

  • 是的,这是一篇很棒的文章,但它涵盖了提供商的完全替代,事实上,这超出了我对该主题的了解。但我会记住这一点。谢谢。
  • @emumcu 以下任何答案有帮助吗?一个赞成或接受的答案真的很有帮助。

标签: c# model-view-controller


【解决方案1】:

可以通过手动设置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;

【讨论】:

  • 我试图设置Identity.Name,如果你愿意,可以这样做:创建声明为new Claim(ClaimTypes.Name, "TheNameYouWant")
【解决方案2】:

我的回答可能并不完全适合你,但它可能会有所帮助。 在我的 ASP.NET Core MVC 应用程序中,管理员需要模拟其他用户。 它是一个 Intranet 应用程序,显然用户通过 Windows 身份验证进行身份验证。 这要归功于对此控制器操作的 ajax 请求:

public async Task<JsonResult> UserImpersonation(IdentityExtension userIdentity)

IdentityExtension 是一个自定义类,您可以观察下面的签名:

public class IdentityExtension : IIdentity
{       
    public IdentityExtension()
    { }
    public IdentityExtension(string name)
    {
        this.Name = name;
    }
    public string AuthenticationType => "Kerberos";

    public bool IsAuthenticated => true;

    public string Name { get; set; }
}

UserImpersonation 方法返回 ReplaceUser 方法的成功状态,以这种方式更新 HttpContext.User :

this.HttpContext.User = identity as ClaimsPrincipal;
return true;

identity 是 IdentityExtension 的一个实例。

我希望我的解决方案可以适应您的用例!

【讨论】:

    【解决方案3】:

    从源码中我们可以看出:

     /// <summary>
     /// Gets a value that indicates if the user has been authenticated.
     /// </summary>
     public virtual bool IsAuthenticated
     {
         get { return !string.IsNullOrEmpty(_authenticationType); }
     }
    

    所以,这意味着当我们有一个 null _authenticationType 时,IsAuthenticated 将始终为 false; 否则,它会是真的。

    【讨论】:

      【解决方案4】:

      如果您希望 HttpContext 持续存在并能够在之后获取声明,请执行以下操作。我将使用 Cookie 身份验证作为 authenticationType。

      var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
      identity.AddClaim(new Claim(ClaimTypes.Name, TempData["Username"].ToString()));
      var principal = new ClaimsPrincipal(identity);
      await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
      

      【讨论】:

        【解决方案5】:

        【讨论】:

        • 当然这是可能的解决方案之一,但我不喜欢使用它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 2011-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多