IdentityServer4在nginx反向代理后https引发的问题
问题描述:
开发的时候都是http协议的,线上环境用nginx进行了转发,并启用了https跳转。
{"issuer":"null","jwks_uri":"http://xxx:443/identity/.well-known/openid-configuration/jwks","authorization_endpoint":"http://xxx:443/identity/connect/authorize","token_endpoint":"http://xxx:443/identity/connect/token","userinfo_endpoint":"http://xxx:443/identity/connect/userinfo","end_session_endpoint":"http://xxx:443/identity/connect/endsession","check_session_iframe":"http://xxx:443/identity/connect/checksession","revocation_endpoint":"http://xxx:443/identity/connect/revocation","introspection_endpoint":"http://xxx:443/identity/connect/introspect","device_authorization_endpoint":"http://xxx:443/identity/connect/deviceauthorization","frontchannel_logout_supported":true,"frontchannel_logout_session_supported":true,"backchannel_logout_supported":true,"backchannel_logout_session_supported":true,"scopes_supported":["openid","profile","clearingagg","financingagg","recordingagg","bank","message","user","configure","file","customer","virtualaccount","apiauth","schedule","offline_access"],"claims_supported":["sub","name","family_name","given_name","middle_name","nickname","preferred_username","profile","picture","website","gender","birthdate","zoneinfo","locale","updated_at"],"grant_types_supported":["authorization_code","client_credentials","refresh_token","implicit","urn:ietf:params:oauth:grant-type:device_code"],"response_types_supported":["code","token","id_token","id_token token","code id_token","code token","code id_token token"],"response_modes_supported":["form_post","query","fragment"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"],"subject_types_supported":["public"],"code_challenge_methods_supported":["plain","S256"],"request_parameter_supported":true}
注意返回的连接都是http的,原因在于
nginx请求是https,然后转发到了后端服务是http的。由于http和https混用,所以会被浏览器阻止。如下
解决方法:
方法一
在startup.cs文件中添加中间件代码如下
app.Use((context, next) => { context.Request.Scheme = "https"; context.Request.IsHttps = true; return next(); });
注意放在 app.UseAuthorization(); 之前。它会强制转换成https的协议。
方法二
但为了优雅可控,我们使用nginx等反向代理服务器,把请求的scheme转发到后端服务器上,自动适配。需要在nginx中添加
proxy_set_header X-Forwarded-Proto $scheme;
然后在startup.cs文件中,把之前的中间件替换存如下代码:
var fordwardedHeaderOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; fordwardedHeaderOptions.KnownNetworks.Clear(); fordwardedHeaderOptions.KnownProxies.Clear(); app.UseForwardedHeaders(fordwardedHeaderOptions);
它会读取nginx等反向代理服务器传来的头参数 X-Forwarded-Proto ,来做到自适配。
验证
在fiddler中,添加 X-Forwarded-Proto: https 头,能成功返回https的URL;
参考资料