2

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

3 Answers 3

3

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

0

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.

2
  • so FormsAuthentication.SetAuthCookie(_username, false); doesnt set it? Feb 1, 2010 at 15:52
  • 2
    it sets the identity, but for FUTURE requests, by writing a client cookie. Feb 1, 2010 at 16:08
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.