在Angular和.Net Core中,JWT身份验证令牌的受众和发行者无效,并且缺少范围的问题可以通过以下步骤来解决:
在Angular应用程序的环境配置文件中,确保指定了正确的后端API地址作为受众(audience)。
export const environment = {
production: false,
apiUrl: 'https://your-api-url.com' // 替换为你的后端API地址
};
在.Net Core应用程序的Startup.cs文件中,确保正确配置了JWT身份验证的发行者(issuer)和密钥。
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://your-issuer-url.com", // 替换为你的发行者URL
ValidateAudience = true,
ValidAudience = "https://your-audience-url.com", // 替换为你的受众URL
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")) // 替换为你的密钥
};
});
在Angular应用程序中,确保使用正确的受众和发行者创建JWT令牌。
import { JwtHelperService } from '@auth0/angular-jwt';
const helper = new JwtHelperService();
const token = 'your-jwt-token'; // 替换为你的JWT令牌
const decodedToken = helper.decodeToken(token);
const audience = 'https://your-audience-url.com'; // 替换为你的受众URL
const issuer = 'https://your-issuer-url.com'; // 替换为你的发行者URL
if (decodedToken.aud !== audience || decodedToken.iss !== issuer) {
// 令牌的受众或发行者无效
// 处理错误逻辑
} else {
// 令牌有效
// 执行其他操作
}
在.Net Core应用程序中,确保在生成JWT令牌时包含了正确的受众和发行者。
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "your-subject"), // 替换为你的主题
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), // 替换为你的唯一标识符
new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64), // 替换为当前时间的Unix时间戳
new Claim(JwtRegisteredClaimNames.Aud, "https://your-audience-url.com"), // 替换为你的受众URL
new Claim(JwtRegisteredClaimNames.Iss, "https://your-issuer-url.com") // 替换为你的发行者URL
};
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.UtcNow.AddDays(1), // 设置过期时间
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")) , SecurityAlgorithms.HmacSha256) // 替换为你的密钥
);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
在.Net Core应用程序中,可以将范围添加为令牌的自定义声明(Claim)。
var claims = new[]
{
// ...
new Claim("scope", "your-scope") // 替换为你的范围
// ...
};
然后,在.Net Core应用程序的Startup.cs文件中,使用AddJwtBearer方法的ScopeClaim属性来配置正确的范围。