asp.net-core - 如何在 JWT token 中包含声明?

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

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

It should not be the job of the application to gather the claims of the user, they should be available in the users JWT. Second, Permissions with an application will be granted based on claims.

下面是我的验证码。

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

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

最佳答案

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

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

关于asp.net-core - 如何在 JWT token 中包含声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58056676/

相关文章:

c# - 如何包装和替换 ASP.NET 5 配置中的默认组件之一

c# - Serilog 不记录信息日志

ajax - 如何优雅地处理 Ajax 调用的登录过期?

asp.net-web-api - 无法加载文件或程序集“Microsoft.IdentityModel.Tokens,版本=5.2.0.0

azure - 如何在Azure Ad中实现代表流?

http - Service Fabric - 具有相同端点的多个服务

c# - 在 Entity Framework Core 中编写实体 POCO 类的正确方法是什么?

c# - C# 中是否有任何 JSON Web token (JWT) 示例?

azure - 如何使用 Azure AD 对 PC 及其中安装的应用程序进行身份验证

python - 如何使用应用程序 ID(服务主体)的 token 向 Azure Devops 进行身份验证?