bhaidar
3/13/2017 - 7:18 PM

Adding a new property to session

Adding a new property to session

//Add new property to claims on login

private async Task SignInAsync(User user, ClaimsIdentity identity = null, bool rememberMe = false)
{
    if (identity == null)
    {
        identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    }

    identity.AddClaim(new Claim("Application_UserEmail", user.EmailAddress)); //SETTING NEW PROPERTY

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberMe }, identity);
}
//Create a custom session class 

public class MyAppSession : ITransientDependency
{
    public string UserEmail
    {
        get
        {
            var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
            if (claimsPrincipal == null)
            {
                return null;
            }

            var emailClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "Application_UserEmail");
            if (emailClaim == null || string.IsNullOrEmpty(emailClaim.Value))
            {
                return null;
            }

            return emailClaim.Value;
        }
    }
}
//Getting session property using MyAppSession

[AbpAuthorize]
public class SessionAppService
{
    private readonly MyAppSession _mySession;

    public SessionAppService(MyAppSession mySession)
    {
        _mySession = mySession;
    }

    public void Test()
    {
        var userEmailFromSession = _mySession.UserEmail;
    }
}