gpt4 book ai didi

c# - MVC 5 自定义 AuthorizeAttribute

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:00 26 4
gpt4 key购买 nike

我想实现自定义 AuthorizeAttribute

我有自定义用户:

    public class MyUser : IPrincipal
{
public List<string> Roles { get; set; }
public IIdentity Identity{ get; set; }
public bool IsInRole(string role){ return Roles.Contains(role); }
}

global.asax

    protected void Session_Start(object sender, EventArgs e)
{
MyUser user = new MyUser();
user.Identity = User.Identity;
user.Roles = new List<string>();
user.Roles.Add("MyRole");//I will get them from AD
HttpContext.Current.User = user;
}

和属性

    public class AuthorizeADAttribute : AuthorizeAttribute
{
public string Roles { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
MyUser user = (MyUser)httpContext.User;//User is not MyUser
if (user.Roles.Contains(Roles))
{
return true;
}
return false;
}

protected override void HandleUnauthorizedRequest(
AuthorizationContext filterContext)
{
...
}
}

问题是 httpContext.User 返回 System.Security.Claims.ClaimsPrincipal。为什么会发生这种情况以及如何从 session_start 访问我的用户?

最佳答案

您需要在 Global.asax.csApplication_PostAuthenticateRequest 事件处理程序中覆盖它的值。

例如,请参阅此答案:https://stackoverflow.com/a/10524305/54937

关于c# - MVC 5 自定义 AuthorizeAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023014/

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