Skip to content

Instantly share code, notes, and snippets.

@ismcagdas
Last active April 27, 2021 13:18
Show Gist options
  • Save ismcagdas/6f2a9a3b5d7b907cb8d94a72124d59a1 to your computer and use it in GitHub Desktop.
Save ismcagdas/6f2a9a3b5d7b907cb8d94a72124d59a1 to your computer and use it in GitHub Desktop.
How to add custom field to AbpSession in ASP.NET Core
//Define your own session and add your custom field to it
//Then, you can inject MyAppSession and use it's new property in your project.
public class MyAppSession : ClaimsAbpSession, ITransientDependency
{
public MyAppSession(
IPrincipalAccessor principalAccessor,
IMultiTenancyConfig multiTenancy,
ITenantResolver tenantResolver,
IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider) :
base(principalAccessor, multiTenancy, tenantResolver, sessionOverrideScopeProvider)
{
}
public string UserEmail
{
get
{
var userEmailClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == "Application_UserEmail");
if (string.IsNullOrEmpty(userEmailClaim?.Value))
{
return null;
}
return userEmailClaim.Value;
}
}
}
//Override CreateAsync method to add your custom claim
public override async Task<ClaimsPrincipal> CreateAsync(User user)
{
var claim = await base.CreateAsync(user);
claim.Identities.First().AddClaim(new Claim("Application_UserEmail", user.EmailAddress));
return claim;
}
@danghung-dev
Copy link

danghung-dev commented Feb 16, 2020

@lyling you can't replace it. You need to use MyAppSession in your own code.

@ismcagdas May you give me an example, how can I use it in my own code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment