Principal get lost after one request

1.4k Views Asked by At

I have the function AffiliateLogin in a controller that sets the Principal.
the row principal.User = user; is actually the one storing the Principal. But after I redirect to another controller, and test my AuthorizeWithRolesAttribute attribute, the principal is reset.
This is one second after the login, you can see the red arrow:

enter image description here

this is the function that stores it.
What am I doing wrong?
Thanks

public JsonResult AffiliateLogin(string email, string password)
        {
            if (ModelState.IsValid)
            {
                Affiliate user = api.GetUserByCredencials<Affiliate>(email, password);
                if (user != null)
                {

                     IIdentity identity = new UserIdentity(true,user.Email);
                    UserPrincipal principal = new UserPrincipal(identity, new string[] {"Affiliate"});
                    principal.User = user;

                    HttpContext.User = principal;
                    return Json("Login success");
                }
            }
            return Json("Fail To Login");
        }
2

There are 2 best solutions below

7
On

The principal property won't survive between web requests. You had to set it again in the next request after redirection.

0
On

If your doing doing custom authentication/forms authentication you should call

 FormsAuthentication.SetAuthCookie 

The next http from the browser with that cookie , Asp.net will process the cookie and set the current claims principal. So you can check

var principal = ClaimsPrincipal.Current;  //normally this reverts to Thread.CurrentPrincipal,

Here is a good place to learn a bit more http://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal.current