Reputation: 3151
Currently, I'm making a SPA using angular 4 & net core 1.1 . My system uses JWT for checking user identity. Everytime user accesses into my system, I want to check his/her identity (status, role) in database and update to HttpContext.Identity.
Here is my code:
OnTokenValidated = async context =>
{
// Find unit of work.
var unitOfWork = context.HttpContext.RequestServices.GetService<IUnitOfWork>();
var identityService = context.HttpContext.RequestServices.GetService<IIdentityService>();
// Find claim identity attached to principal.
var claimIdentity = (ClaimsIdentity)context.Ticket.Principal.Identity;
// Find email from claims list.
var email =
claimIdentity.Claims.Where(x => x.Type.Equals(ClaimTypes.Email))
.Select(x => x.Value)
.FirstOrDefault();
// Email is invalid.
if (string.IsNullOrEmpty(email))
return;
// Find account information.
var condition = new SearchAccountViewModel();
condition.Email = new TextSearch();
condition.Email.Value = email;
condition.Email.Mode = TextComparision.Equal;
// Find accounts based on conditions.
var accounts = unitOfWork.RepositoryAccounts.Search();
accounts = unitOfWork.RepositoryAccounts.Search(accounts, condition);
// Find the first matched account in the system.
var account = await accounts.FirstOrDefaultAsync();
// Account is not found.
if (account == null)
return;
var identity = (ClaimsIdentity) identityService.InitiateIdentity(account);
identity.AddClaim(new Claim(ClaimTypes.Role, Enum.GetName(typeof(Roles), account.Role)));
identity.AddClaim(new Claim(ClaimTypes.Authentication, Enum.GetName(typeof(Statuses), account.Status)));
context.HttpContext.User = new ClaimsPrincipal(identity);
}
In my AccountController.cs I have a function:
/// <summary>
/// Find personal profile.
/// </summary>
/// <returns></returns>
[HttpGet("personal-profile")]
public IActionResult FindProfile()
{
var identity = (ClaimsIdentity) Request.HttpContext.User.Identity;
var claims = identity.Claims.ToDictionary(x => x.Type, x => x.Value);
return Ok(claims);
}
Here is the result I have:
{
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "[email protected]",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Goldarina Wharrier",
"auth_time": "1494072536661.38",
"nbf": "1494043736",
"exp": "1494047336",
"iss": "iConfess Ordinary",
"aud": "http://localhost:5001"
}
No role or status had been included into identity. My question is: - How can I add more claims into request identity after validating token and searching user information in database.
Could anyone help me please ?
Thank you,
Upvotes: 4
Views: 6532