identityserver4 使用自签名证书,client和API访问提示证书无效的解决方法

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;
                });
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值