无法访问WebApi授权令牌中的JWT声明

时间:2018-11-14 09:03:01

标签: c# asp.net-mvc asp.net-web-api authorization jwt

通过下面的链接JWT Authentication for Asp.Net Web Api,我能够在我的MVC WebApi中实现以下JWT解决方案

现在,我想访问控制器中的声明,但是所有声明都为空。我尝试了一些事情,所有这些都返回null。

如何在JwtAuthenticationAttribute中添加声明:

protected Task<IPrincipal> AuthenticateJwtToken(string token)
        {
            string username;

            if (ValidateToken(token, out username))
            {
                //Getting user department to add to claim.
                eTaskEntities _db = new eTaskEntities();
                var _user = (from u in _db.tblUsers join d in _db.tblDepartments on u.DepartmentID equals d.DepartmentID select u).FirstOrDefault();
                var department = _user.DepartmentID;

                // based on username to get more information from database in order to build local identity
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim(ClaimTypes.SerialNumber, department.ToString())
                    // Add more claims if needed: Roles, ...
                };

                var identity = new ClaimsIdentity(claims, "Jwt");
                IPrincipal user = new ClaimsPrincipal(identity);

                return Task.FromResult(user);
            }

            return Task.FromResult<IPrincipal>(null);
        }

到目前为止我尝试过的事情

获取索赔的扩展方法:

public static class IPrincipleExtension
{
    public static String GetDepartment(this IIdentity principal)
    {
        var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
        if (identity != null)
        {
            return identity.FindFirst("SerialNumber").Value;
        }
        else
            return null;
    }
}

使用帖子中定义的功能(上面的链接):

TokenManager.GetPrincipal(Request.Headers.Authorization.Parameter).FindFirst("SerialNumber")

尝试通过线程访问Claim:

((ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal.Identity).FindFirst("SerialNumber")

对于所有上述情况,索赔始终为空。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您应该尝试此操作以获得索赔:

if (HttpContext.User.Identity is System.Security.Claims.ClaimsIdentity identity)
{                   
    var serialNum = identity.FindFirst(System.Security.Claims.ClaimTypes.SerialNumber).Value;
}

当我这样设置声明时,我保留identity.FindFirst("string_here").Value

var usersClaims = new[]
{               
    new Claim("string_here", "value_of_string", ClaimValueTypes.String),
    ...
};

而不是使用像这样的“预构建”值:

var usersClaims = new[]
{               
    new Claim(ClaimTypes.Name, "value_of_name", ClaimValueTypes.String),
    ...
};