所以这就是我在后端验证JWT承载令牌的方式:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = $"https://{Configuration["Auth0:Authority"]}";
options.Audience = Configuration["Auth0:Audience"];
});
当.Net核心咨询权威以获取所需的信息(例如签名密钥)时,它工作正常。就我而言,它通过https://
问题是,当我在无法访问Internet的Intranet中部署它时,我的应用程序无法与Auth0服务器通信。这是我得到的错误:
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://< My TENANT >.auth0.com/.well-known/openid-configuration'.
我尝试手动输入RSA密钥,但不走运,出现相同错误:
AddJwtBearer(options =>
{
options.Authority = $"https://{Configuration["Auth0:Domain"]}";
options.Audience = Configuration["Auth0:Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = GetRsaKey(),
};
});
private SecurityKey GetRsaKey()
{
byte[] modulus = Decode("r5cpJ....-fUGjJCH1QQ");
byte[] exponent = Decode("A...AB");
var rsaParameters = new RSAParameters
{
Modulus = modulus,
Exponent = exponent
};
using var rsaProvider = new RSACryptoServiceProvider();
rsaProvider.ImportParameters(rsaParameters);
return new RsaSecurityKey(rsaProvider);
}
任何解决方法?
由于您do not have access to the internet
,您需要具有内部身份和访问控制,例如Identity Server
,或如下创建自己的JWT Issuer/Validator
:
private JwtSecurityToken GetJwtSecurityToken(List<Claim> user_claims)
{
string privateKey = "YOUR_PRIVATE_KEY";
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(privateKey));
var credentials = new SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256);
return new JwtSecurityToken
(
issuer: "ISSUER_NAME",
audience: "AUDIENCE",
claims: user_claims,
signingCredentials: credentials
);
}
var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
将令牌发送给用户或将其添加到cookie。
在您的startup file
:
services.AddAuthentication()
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, config =>
{
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "ISSUER",
ValidAudience = "AUDIENCE",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YOUR_PRIVATE_KEY"))
};
});
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
就这些。希望有人能告诉我们是否有更好的解决方案。