views:

37

answers:

1

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?....

+1  A: 

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;
    }
}
Clicktricity
Hi Clicktricity, thanks for the reply. I think this won't work since I'm using ADFS to authenticate my users. Because of that, I authentication mode isn't form based so the "if" statement will always be false. Am I mistaken?
TriFu
Fair enough - just adapt to your needs. The key is that the current user assignment takes place during the OnPostAuthenticationRequest
Clicktricity
Wouldn't this method always check the user's role ever time you try to access certain controllers? isn't there a way to store the user's role in a session object or cookie of some sort? That way you wouldn't need to always hit up the DB for the user's role?
TriFu
Its up to you how you determine the user's role. A cookie would be reasonable, as long as its encrypted to prevent someone faking it and gaining admin access. You also need to determine how long the cookie persists otherwise someone who no longer should have admin access could still access the admin areas.
Clicktricity
Good advice! I was wondering if you had any links or resources you could send me? I have no idea how to go about encrypting a cookie with admin role authentication? Any help would be greatly appreciated.
TriFu
Good question - I suggest you pose that as a separate question so everyone can benefit from the information.
Clicktricity