相关疑难解决方法(0)

在MVC3中使用自定义IPrincipal和IIdentity

创建我自己的IPrincipal,并IIdentity实现如下图所示:

[ComVisible(true)]
[Serializable]
public sealed class CustomIdentity : IIdentity {

    private readonly string _name;
    private readonly string _email;
    // and other stuffs

    public CustomIdentity(string name) {
        _name = name.Trim();
        if(string.IsNullOrWhiteSpace(name))
            return;
        _email = (connect to database and read email and other stuffs);
    }

    public string Name {
        get { return _name; }
    }

    public string Email {
        get { return _email; }
    }

    public string AuthenticationType {
        get { return "CustomIdentity"; }
    }

    public bool IsAuthenticated …
Run Code Online (Sandbox Code Playgroud)

forms-authentication iprincipal iidentity custom-authentication asp.net-mvc-3

21
推荐指数
1
解决办法
1万
查看次数

MVC5中无法访问自定义IPrincipal

我已经阅读了很多关于这个主题的问题和答案,但没有一个能帮助我解决这个问题.

我遇到的问题是,HttpContext.Current.User或者只是User属性是类型RolePrincipal而不是我的自定义主体.

这是一个使用Windows身份验证(仅限Intranet的应用程序)的MVC 5 Web应用程序.我的自定义主体是一个子类,WindowsPrincipal我确实实现了自己的RoleProvider用于Authorize属性标记.

当我尝试通过IPrincipal在当前的HttpContext上将它转换为我的自定义主体来使用主体时,我得到一个错误,指出它的类型为RolePrincipal,显然无法将其转换为我的自定义主体.我在Application_PostAuthenticationRequest事件中设置我的自定义主体:

protected void Application_PostAuthenticationRequest(object sender, EventArgs e)
{
    if (User == null)
        return;

    using(EntityContext db = new EntityContext ())
    {
        var user = db.Users.SingleOrDefault(u => u.ADName.Equals(User.Identity.Name));
        HttpContext.Current.User = new PcsPrincipal((WindowsIdentity)User.Identity, user);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在该方法中放置一个断点时,似乎永远不会被调用,这可以解释为什么它没有被设置为我的自定义主体.

我已经审核了以下QA,但他们无法解决此问题:

如果没有设置Principal,我做错了什么?如果需要发布更多代码,请告诉我.

编辑: 在WindowsAuthentication.OnAuthenticate事件中将HttpContext.Current.User设置为我的自定义主体不能解决此问题.使用该方法表现出完全相同的行为.

c# asp.net windows-authentication asp.net-mvc-5 asp.net-identity

5
推荐指数
1
解决办法
1317
查看次数