讓服務器配置爲可以接受客戶端證書的方法
Microsoft.AspNetCore.Authentication.Certificate
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate()
.AddCertificateCache();
Kestrel服務端配置證書
生成證書請看
https://www.cnblogs.com/buchizaodian/p/15483758.html
GrpcService1 是項目名稱,crypticpassword是密碼
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseKestrel(option => { option.ConfigureHttpsDefaults(i => { i.ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("./GrpcService1.pfx", "crypticpassword"); }); }).UseStartup<Startup>(); }); }
報這個錯誤是因爲證書不受信任
IIS服務端配置證書
自定義 web 代理中使用證書身份驗證
如nginx
客戶端使用證書
var cert = new X509Certificate2("./GrpcService1.pfx", "crypticpassword"); var handler = new HttpClientHandler(); handler.ClientCertificates.Add(cert); //來允許在沒有受信任證書的情況下進行調用 handler.ServerCertificateCustomValidationCallback =HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; var channel = GrpcChannel.ForAddress("https://127.0.0.1:5001", new GrpcChannelOptions { HttpHandler = handler }); var client = new Greeter.GreeterClient(channel); HelloRequest helloRequest = new HelloRequest(); helloRequest.Name = "Tom"; HelloReply helloReply = new HelloReply(); Random random = new Random(); while (true) { Thread.Sleep(1000); helloRequest.Name = random.Next().ToString(); helloReply = client.SayHello(helloRequest); }