Please I need assistance in implementing a custom way of assigning claims to authenticated users. On successful login,
var result = await SignInManager.Pass
You must add your claims before login not after. Consider this example:
public async Task Login(LoginViewModel model,string returnUrl)
{
var user = UserManager.Find(model.Email, model.Password);
if(user!=null)
{
var ident = UserManager.CreateIdentity(user,
DefaultAuthenticationTypes.ApplicationCookie);
ident.AddClaims(new[] {
new Claim("MyClaimName","MyClaimValue"),
new Claim("YetAnotherClaim","YetAnotherValue"),
});
AuthenticationManager.SignIn(
new AuthenticationProperties() { IsPersistent = true },
ident);
return RedirectToLocal(returnUrl);
}
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
Now since we have injected our claims while signing in, we have access to claims wherever we want:
((ClaimsIdentity)User.Identity).FindFirst("MyClaimName");
Also you could add your claims in ApplicationUser.GenerateUserIdentityAsync() method. By adding your claims in this method you could use SignInManager.PasswordSignInAsync() method to sign in users without any modification to default Login action method.
public class ApplicationUser : IdentityUser
{
public async Task GenerateUserIdentityAsync(UserManager manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity .AddClaims(new[] {
new Claim("MyClaimName","MyClaimValue"),
new Claim("YetAnotherClaim","YetAnotherValue"),
});
return userIdentity;
}
}