可以通过自定义 ClaimSerializer 来解决。在 Startup.cs 中添加下面的代码:
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = YourSecurityKey,
ValidateIssuer = true,
ValidIssuer = "your-issuer",
ValidateAudience = true,
ValidAudience = "your-audience",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
options.ClaimActions.MapJsonKey(ClaimTypes.Role, ClaimTypes.Role, "string");
options.ClaimActions.MapJsonKey(ClaimTypes.Name, ClaimTypes.Name, "string");
// Add this line to change the claim value type to JsonArray
options.ClaimActions.Add(new JsonArrayClaimAction("your-claim", "value"));
});
需要注意的是,在上面的代码中,我们通过添加 JsonArrayClaimAction
将指定的 Claim 的值类型更改为 JsonArray。您需要将 your-claim
和 value
替换为您自己的 Claim 和值。
假设您的 JWT Token 包含 your-claim
:["value1","value2"],那么现在您可以通过以下代码来获取该 Claim:
var claim = User.FindFirst("your-claim");
var values = JsonConvert.DeserializeObject(claim.Value);