如何在JWT令牌中包含声明?

时间:2019-09-23 06:24:47

标签: asp.net-core jwt azure-active-directory authorization claims-based-identity

嗨,我正在.Net核心中开发Web应用程序。我已经实现了V2身份验证。现在,我需要添加授权。要求指出,首先,

  

收集索赔不应该是申请的工作   用户,他们应该在用户JWT中可用。第二,   应用程序的权限将根据声明授予。

下面是我的验证码。

 services
               .AddAuthentication(o =>
               {
                   o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

               })
               .AddJwtBearer(o =>
               {
                   o.Authority = azureActiveDirectoryOptions.Authority;

                   o.TokenValidationParameters = new TokenValidationParameters
                   {

                       ValidAudiences = new List<string>
                       {
                          azureActiveDirectoryOptions.AppIdUri,
                          azureActiveDirectoryOptions.ClientId
                       },
                   };
               });

            services.AddMvc(options =>
            {

                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

有人可以帮助我添加基于声明的授权吗?任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码在JWT令牌中添加自定义声明。

public string createToken()
{
    var tokenHandler = new JwtSecurityTokenHandler();

    //create a identity and add claims to the user which we want to log in
    ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
    {
        new Claim("UserName", "joey"),
        new Claim("Email","xxx@test.com")
    });

    const string sec = "yoursecurityKey";
    var now = DateTime.UtcNow;
    var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
    var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

    //create the jwt
    var jwtSecurityToken = handler.CreateJwtSecurityToken(
        "issuer",
        "Audience",
        new ClaimsIdentity(claimsIdentity),
        DateTime.Now,
        DateTime.Now.AddHours(1),
        DateTime.Now,
        signingCredentials);
    var tokenString = tokenHandler.WriteToken(token);

    return tokenString;
}

有关更多详细信息,您可以参考此article

更新:

如果是这样,您可以使用JwtBearerEvents添加声明。

 .AddJwtBearer(o =>
 {
     //Additional config snipped
     o.Events = new JwtBearerEvents
     {
         OnTokenValidated = async ctx =>
         {
             //Get the calling app client id that came from the token produced by Azure AD
             string clientId = ctx.Principal.FindFirstValue("appid");
             var claims = new List<Claim>
             {
                 new Claim("UserName", "joey")
             };
             var appIdentity = new ClaimsIdentity(claims);

             ctx.Principal.AddIdentity(appIdentity);
         }
     };
});

答案 1 :(得分:1)

对于授权部分,您可以add app roles in your application,为用户/组分配角色,以便public static VehicleExtesnion { public SomeType DoStuff(this Vehicle vehicle) { // do stuff with vehicle } } 将在用户登录并获得同意后包含在令牌中,您的应用程序可以根据{ {1}}索赔。

另一种方法是use Azure AD Groups and Group Claims。区别在于您的应用程序应检查roles声明,