Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I am trying to implement Asp.net Identity in my web (MVC5) application. In User Authentication method I am authenticating user, if user exist then I am manually creating Claims Identity and Principal in my application (Authentication.cs). After that I am assigning the Claims Principal to current HttpContext and Thread. So now I am able to see Identity in the same request httpcontext. But if I am trying to access Claims Identity from different action/page then it will show a null values in the User.Identity object, that is, Identity is not maintaing in the subsequent request.

In my application I set AuthenticationMode="None" in web.config so I removed LoginPath attribute from OWIN Startup class.

C#
//OWIN startup.cs
[assembly: OwinStartup(typeof(Web.Startup))]
namespace Web
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieSecure = CookieSecureOption.Always
            });

        }
    }
}


C#
//Authentication.cs
//After user authentication, setting Thread and http context.
if (user != null)
{
	var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

	var claims = new List<Claim>();
	claims.Add(new Claim(ClaimTypes.Name, "username"));
	claims.Add(new Claim(ClaimTypes.Email, "username@gmail.com"));
	var userIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        ClaimsPrincipal principal2 = new ClaimsPrincipal(userIdentity);

	authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, userIdentity);

	var test = HttpContext.Current.User.Identity.IsAuthenticated; //return false

	System.Threading.Thread.CurrentPrincipal = principal2;
	HttpContext.Current.User = principal2;

	test = userIdentity.IsAuthenticated; // User Identity is authenticated return true

	test = HttpContext.Current.User.Identity.IsAuthenticated; //return true
}


I am not sure why Identity values are not maintaining in httpcontext or can I access the identity in some other ways in other pages/actions?

I assume that I missed something in the identity implementation. :(

Thanks
Selvakumar R
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900