/// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="audience">我是谁,即jwt是颁发给谁的</param> /// <param name="authority">当局。我该去向谁核实,即是谁颁发了这个jwt</param> /// <returns></returns> /// <exception cref="WebApiException"></exception> public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration, Func <JwtBearerChallengeContext, Task> onChallenge, Func <TokenValidatedContext, Task> onTokenValidated, Func <AuthenticationFailedContext, Task> onAuthenticationFailed, Func <ForbiddenContext, Task> onForbidden, Func <MessageReceivedContext, Task> onMessageReceived) { JwtClientSettings jwtSettings = new JwtClientSettings(); configuration.Bind(jwtSettings); X509Certificate2 encryptCert = CertificateUtil.GetCertificateFromSubjectOrFile( jwtSettings.JwtContentCertificateSubject, jwtSettings.JwtContentCertificateFileName, jwtSettings.JwtContentCertificateFilePassword); return (services .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(jwtOptions => { //#if DEBUG // jwtOptions.RequireHttpsMetadata = false; //#endif jwtOptions.Audience = jwtSettings.Audience; jwtOptions.Authority = jwtSettings.Authority; jwtOptions.TokenValidationParameters = new TokenValidationParameters { RequireExpirationTime = true, RequireSignedTokens = true, RequireAudience = true, TryAllIssuerSigningKeys = true, ValidateAudience = true, ValidateIssuer = true, ValidateIssuerSigningKey = true, ValidateLifetime = true, TokenDecryptionKey = CredentialHelper.GetSecurityKey(encryptCert) }; jwtOptions.Events = new JwtBearerEvents { OnChallenge = onChallenge, OnAuthenticationFailed = onAuthenticationFailed, OnMessageReceived = onMessageReceived, OnTokenValidated = onTokenValidated, OnForbidden = onForbidden }; //#if DEBUG // //这是为了ubuntu这货,在开发阶段不认开发证书。这个http请求,是由jwt audience 发向 jwt authority的。authority配置了正式证书后,就没问题了 // jwtOptions.BackchannelHttpHandler = new HttpClientHandler // { // ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => // { // if (cert!.Issuer.Equals("CN=localhost", GlobalSettings.Comparison)) // return true; // return errors == System.Net.Security.SslPolicyErrors.None; // } // }; //#endif })); }