开发者

Setting user roles in controllers?

I need to be able to manually authorize my users in my controller.

I get my authentication from an AD, and then in my controller,

I want to map up the userID I get from the AD, to my application's internal userID.

Grab the userId from the UserRole table, and then set it in the controller, however,

I don't know how to set the role in the controller?

开发者_运维技巧

I've tried doing this in my home controller:

HttpContext.User = new System.Security.Principal.GenericPrincipal(User.Identity, roleName);

roleName is set to "Admin", but this doesn't seem to work as it always fails authorization.

Help please?....


Assuming you are using [Authorize] in your controller methods, this will run before the action method and therefore will not reach the code you have to set the role name - it needs to be set before the controller is called.

Add a method like this to your Global.asax:

protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e)
{
    IPrincipal contextUser = Context.User;

    if (contextUser.Identity.AuthenticationType == "Forms")
    {
        // determine role name

        // attach to context
        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(User.Identity, roleName);
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜