在JWT Bearer

时间:2017-05-06 04:12:01

标签: c# asp.net-core jwt asp.net-core-webapi json-web-token

目前,我正在使用角4& amp;净核心1.1。我的系统使用JWT来检查用户身份。每当用户访问我的系统时,我想检查他/她在数据库中的身份(状态,角色)并更新到HttpContext.Identity。

这是我的代码:

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);
}

在我的 AccountController.cs 中,我有一个功能:

/// <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);
}

以下是我的结果:

{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "linhndse03150@gmail.com.vn",
  "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"
}

身份中未包含任何角色或身份。 我的问题是: - 在验证令牌和在数据库中搜索用户信息后,如何将更多声明添加到请求标识中。

有人可以帮我吗?

谢谢,

1 个答案:

答案 0 :(得分:0)

试试这个:

context.Principal.AddIdentity(identity);