49

New to OWIN authentication and finding it hard to create my own owin claim types.

Heres the thing. I need to add custom claims like "GroupID" so i can easily access it on the different pages.

I did something like this in my Login

public ActionResult Login(LoginViewModel model, string returnUrl)
{
    UserViewModel userModel = new UserViewModel();
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    if(CommonHelper.ValidateADUser(model.Username,model.Password))
    {

        UserViewModel curUser = userModel.GetUserDetails(model.Username);
        if (curUser != null)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.WindowsAccountName, curUser.Username));
            claims.Add(new Claim(ClaimTypes.Name,curUser.Fullname));
            claims.Add(new Claim(ClaimTypes.Role, ""));
            claims.Add(new Claim("GroupID", curUser.UserGroupID.ToString()));

            var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
            var ctx = Request.GetOwinContext();
            AuthenticationManager.SignIn(id);
            return RedirectToAction("Index", "Home");
        }
    }
    else
    {
        ModelState.AddModelError("", "Invalid login attempt.");
    }

    return View(model);
}

In my login partial I tried to get the value by doing this

public ActionResult _LoginPartial()
{
    var identity = (ClaimsIdentity)User.Identity;
    TempData["curUserFullName"] = identity.FindFirst(ClaimTypes.Name).Value;

    string s= identity.FindFirst("GroupID").Value;
    return PartialView();
}

I can get the username and full name with no problem but group id causes an object null error.

Hoping someone could nudge me to the correct answer.

13
  • are you able to see if the new claim is added to the UserClaims DB table?
    – Jay
    Commented Oct 12, 2015 at 7:18
  • Where is the userclaims db table?
    – TheProvost
    Commented Oct 12, 2015 at 7:22
  • 1
    @TheProvost the question now - can you add any other claim? say add claims.Add(new Claim("MyTestClaim", "Test Value")); Can you retrieve it?
    – trailmax
    Commented Oct 14, 2015 at 9:10
  • 1
    Also try replacing sign-in method with this: AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, id);. I've got pretty much the same set up for one of my projects and have this working fine.
    – trailmax
    Commented Oct 14, 2015 at 9:11
  • 1
    And another thing - try doing sign-out before signing in: AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    – trailmax
    Commented Oct 14, 2015 at 9:12

3 Answers 3

25
+100

As I've checked your Code there are no problem in it.

Here's what I want you to do:

Check if the cache was clear. If your cache was not cleared you can clear it like this: CTRL+SHIFT+DELETE

It's because during your login, it will save in cookies and it was not clear, and it happens that the new claim was not save in the cookies.

Or try to check if your UserGroupID has a value.

2
  • 3
    What the!!!! Rookie mistake. I've used different browsers so I thought cookies was not the issue. Thanks!!!
    – TheProvost
    Commented Oct 14, 2015 at 9:14
  • 3
    Its because otang monggos Commented Oct 14, 2015 at 9:16
11

You can use type and value like this.

claims.Add(new Claim(type: "GroupID", value: curUser.UserGroupID.ToString()));
0

In .NETCore you can use 2 ways.

First One is you must create new class as bottom(reference):

public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public MyUserClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager,
        IOptions<IdentityOptions> optionsAccessor)
        : base(userManager, roleManager, optionsAccessor)
    {
    }

    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
    {
        var identity = await base.GenerateClaimsAsync(user);
        identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FullName ?? ""));
        identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
        identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber ?? ""));
        identity.AddClaim(new Claim("your claims name", "your claim data for this user"));
        return identity;
    }
}

and then in startup.cs of your project add this code(after services.AddIdentity(...);)

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, MyUserClaimsPrincipalFactory>();

Second one in login page after check user and pass use bottom code:

    var user = await _userManager.FindByNameAsync(Input.Email.Substring(0, Input.Email.LastIndexOf(".")));
//create your custom claims list
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.WindowsAccountName, user .Username));
                claims.Add(new Claim(ClaimTypes.Name, user.Username));
                claims.Add(new Claim(ClaimTypes.Email, Username.Email));
                claims.Add(new Claim(ClaimTypes.MobilePhone, user.PhoneNumber));
                claims.Add(new Claim(ClaimTypes.GivenName, user.FullName));
                claims.Add(new Claim("your claims name", "your claim data for this user"));


//add with _signInManager as bellow
                await _signInManager.SignInWithClaimsAsync(user,true, claims);

For usage of this two ways, you can access any of claims data as bellow:

var fullName = User.FindFirstValue(ClaimTypes.GivenName);//User is .net core identityUser
var yourClaimData= User.FindFirstValue("your claims name");//User is .net core identityUser

First way is recommended.

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.