identityserver4 使用自签名证书,client和API访问提示错误:The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot,查阅了很多资料,得知须得在HttpClient中将ServerCertificateCustomValidationCallback属性设为true。
Client端
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback =
(
HttpRequestMessage message,
X509Certificate2 cert,
X509Chain chain,
SslPolicyErrors errors
) => { return true; };//remove if this makes it to production
HttpClient client = new HttpClient(handler);
var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
{
Address = "https://192.168.1.234:5001/",
Policy =
{
ValidateIssuerName = true
}
});
API端
当客户端带着token来访问API资源时,API会到鉴权中心验证token的有效性。
鉴权中心使用自签名证书时,需要在ConfigureServices中进行配置
services.AddAuthentication("Bearer") //将身份认证服务添加到DI,并将"Bearer"配置为默认方案。
.AddJwtBearer("Bearer", options => //将JWT认证处理程序添加到DI中以供身份认证服务使用。
{
options.Authority = "https://192.168.1.234:5001";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false//验证访问令牌内的aud声明是否与访问群体参数匹配。
};
//加了下面两行后,当accesstoken失效,api会拒绝访问,显示401错误
//Token 验证间隔为,且 Token 必须包含过期时间。默认是300S
options.TokenValidationParameters.ClockSkew = TimeSpan.FromSeconds(5);//验证cookie的时间
options.TokenValidationParameters.RequireExpirationTime = true;//要求必须有超时时间
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
options.BackchannelHttpHandler = handler;
});