25

I am using mvc 5 with identity 2.0. I want use custom claim values over the application but I get null values. What am I doing wrong?

Updated code

Login Code in account controller

if (!string.IsNullOrEmpty(model.UserName) && !string.IsNullOrEmpty(model.Password))
            {
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                var result = SignInManager.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false);


                //Generate verification token
                Dictionary<string, string> acceccToken = null;
                if (SignInStatus.Success == 0)
                {
                    var userDeatails = FindUser(model.UserName, model.Password).Result;
                    if (userDeatails != null)
                        acceccToken = GetTokenDictionary(model.UserName, model.Password, userDeatails.Id);
                }
                if (model.RememberMe)
                {
                    HttpCookie userid = new HttpCookie("rembemberTrue", "1");
                    userid.Expires.AddDays(1);
                    Response.Cookies.Add(userid);
                }
                else
                {

                    HttpCookie userid = new HttpCookie("rembemberTrue", "0");
                    userid.Expires.AddDays(1);
                    Response.Cookies.Add(userid);

                }
                #region custom claims


                var claims = new Claim[]
                           {
                    new Claim("urn:Custom:MasterUniqueId", Convert.ToString(Guid.NewGuid()))
                                };
                ClaimsIdentity identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                IAuthenticationManager authenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
                authenticationManager.SignIn(identity);

Starup.Auth.cs

 public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                },
                SlidingExpiration = true,
                ExpireTimeSpan = TimeSpan.FromMinutes(60)
            });

another controller

Here I am trying to fetch that claim values but it shows null

var identity = (ClaimsIdentity)User.Identity;
var res= identity.FindFirst("urn:Custom:MasterUniqueId");

res is null

Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76
Neeraj Sharma
  • 568
  • 6
  • 18
  • Can you show the full sign in code that you're using? Is the method that this code in in properly async? Also, are you missing a `app.UseCookieAuthentication(...)` in your startup? – Brendan Green May 17 '16 at 05:25
  • @BrendanGreen, I have updated my question, Please have a look – Neeraj Sharma Sep 15 '16 at 13:08
  • Can you see what the output of `User.Identity.IsAuthenticated` and `User.Identity.Name` is? – Matti Price Sep 21 '16 at 21:18
  • [here](http://stackoverflow.com/questions/38846816/how-to-get-custom-property-value-of-the-applicationuser-in-the-asp-net-mvc-5-vie/38847016#38847016) is an example. – tmg Sep 22 '16 at 11:19
  • Approach is right , if you are getting User.Identity , you are on right Track , further then you can cast `User.Identity.Claims` to `ClaimsIdentity` and fetch requests keys. – Vishal Sharma Nov 29 '17 at 14:27

3 Answers3

1

You should add those claims on identity validation phase. Please check similar implementation here: Server side claims caching with Owin Authentication

Community
  • 1
  • 1
Burak SARICA
  • 721
  • 1
  • 7
  • 27
1

In your account controller, to get a valid authenticationManager, you should use Request.GetOwinContext().Authentication. Im affraid System.Web.HttpContext.Current.GetOwinContext().Authentication gets you a fresh authenticationManager instead of the current Owin context one

Minus
  • 729
  • 8
  • 20
1

First you need to convert identity to claims identity and then try to get claim using identity type

(HttpContext.Current?.User?.Identity as ClaimsIdentity)?.Claims?.FirstOrDefault(x => x.Type == "urn:Custom:MasterUniqueId")?.Value
Hammad Shabbir
  • 722
  • 1
  • 6
  • 13