views:

154

answers:

3

Hello

I'm using asp.net and trying to assign roles for a user with forms authentication like this:

    public ActionResult AdminLogin(string password, string username)
    {
        User _user = _us.GetUsers(username, password).FirstOrDefault();

        if (_user != null)
        {
            string _username = _user.Username;

            FormsAuthentication.SetAuthCookie(_username, false);

            string[] _roles = _us.GetUserRoles(_username);


            HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, _roles);


            return RedirectToAction("Index", "Admin");

When I debug HttpContext.User.Identity always is null, but _username and _roles contains the proper data. Howto fix this?

/M

A: 

I believe the issue is that you are just setting the user as authenticated, and therefore, the HttpContext is not updated yet since the auth cookie has not yet been set on the users side of the request.

Mitchel Sellers
so FormsAuthentication.SetAuthCookie(_username, false); doesnt set it?
molgan
it sets the identity, but for FUTURE requests, by writing a client cookie.
Mitchel Sellers
+1  A: 

Your action is setting the User IPrincipal for the current context. As soon as you redirect to your other action (and all subsequent requests) a new HttpContext is created with a null User IPrincipal.

What you could do is persist the information in the authentication cookie and then extract that data in the Application_AuthenticateRequest method in your Global.asax file and set the User property of the HttpContext there.

This answer contains more details and example code

David G
A: 

I was struggling too.

I was trying to carryout my authentication and authorization inside a WCF service using standard ASP.Net Membership and Role providers.

I wanted to pass in credentials and a 'requested app' to determine if the user 'authenticated' for that app. (not the ASP.Net APP, but an app in my own database).

To do this, I wanted access to the roles, but didn't want to 'redirect' or have a second call to my WCF service.

Here is some code that works for me:

First I determine if the user is valid as follows:

if (Membership.ValidateUser(CompanyCn, CompanyPwd))
{
    sbLogText.AppendFormat("\r\n\r\n\tValid User UID/PWD: '{0}'/'{1}'", CompanyCn, CompanyPwd);
    FormsAuthentication.SetAuthCookie(CompanyCn, false);
}

Then the following code workes nicely for getting the list of roles:

List<string> roleList = new List<string>(Roles.GetRolesForUser(CompanyCn));
sbLogText.AppendFormat("\r\n\r\n\tUser ('{0}'): Roles ({1}):", CompanyCn, roleList.Count);
foreach (string s in roleList)
    sbLogText.AppendFormat("\r\n\t\tRole: {0}", s);
Mike Graham