c# - Add Claim On Successful Login -


i need add claim user's identity after successful user login. think needs happen:

public async task<actionresult> login(loginviewmodel model, string returnurl, string myclaimvalue) {    if (!modelstate.isvalid)    {       return view(model);    }     var result = await signinmanager.passwordsigninasync(model.username, model.password, model.rememberme, shouldlockout: false);    switch (result)    {       case signinstatus.success:          usermanager.addclaim(user.identity.getuserid(), new claim("myclaim", myclaimvalue));          return redirecttolocal(returnurl);       case signinstatus.lockedout:          return view("lockout");       case signinstatus.requiresverification:          return redirecttoaction("sendcode", new { returnurl = returnurl, rememberme = model.rememberme });       case signinstatus.failure:       default:          modelstate.addmodelerror("", "invalid login attempt.");          return view(model);    } } 

i think right approach, call user.identity.getuserid() throws exception. looks user.identity not updated successful signin. in lieu of reality, best way me newly signed in user's id can add claim?

or doing wrong?

additional claims must set before signinmanager.passwordsigninasync triggered. can done custom claimsidentityfactory:

public class applicationclaimsidentityfactory : claimsidentityfactory<applicationuser> {     // claim value taken login view     public static readonly string myclaimkey = "app:myclaimkey";     public string myclaimvalue { get; set; }      public async override task<claimsidentity> createasync(usermanager<applicationuser, string> manager, applicationuser user, string authenticationtype)     {         var identity = await base.createasync(manager, user, authenticationtype);         identity.addclaim(new claim(myclaimkey, myclaimvalue));         return identity;     } } 

apply factory before sign in step:

usermanager.claimsidentityfactory = new applicationclaimsidentityfactory()          {              myclaimvalue = loginmodel.myclaimvalue         }; var result = await signinmanager.passwordsigninasync(model.username, model.password, model.rememberme, shouldlockout: false); 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -