简体   繁体   English

在运行 HTTPS 的应用程序中重定向 URI 作为 HTTP 而不是 HTTPS 发送

[英]Redirect URI sent as HTTP and not HTTPS in app running HTTPS

I have an Asp .net core MVC app.我有一个 Asp .net 核心 MVC 应用程序。 Which connects to an Identity Server 4 for authentication.它连接到 Identity Server 4 以进行身份验证。 Hosted in a docker swarm托管在 docker 群中

MVC app is hosted on https://XXXXXXX MVC 应用托管在https://XXXXXXX

ConfigurServies配置服务

services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
             .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                //options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));
                // when the identity has been created from the data we receive,
                // persist it with this authentication scheme, hence in a cookie
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                // Identity server endpoint
                options.Authority = settingsSetup.IdentityServerEndpoint;

                // Client id to login with
                options.ClientId = settingsSetup.ClientId;
                // Client secret.
                options.ClientSecret = settingsSetup.Secret;

                // Scope of our API
                options.Scope.Add("testapi");
                options.Scope.Add("devconsole");
                // adding offline_access to get a refresh token
                options.Scope.Add("offline_access");

                options.ResponseType = "code id_token";
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
            });

When I try to run the app I get a redirect uri miss match error.当我尝试运行该应用程序时,出现重定向 uri 未匹配错误。

Invalid redirect_uri: http://developerconsole.XXXXX.io/signin-oidc
{
  "ClientId": "BB1D2DA8-D7E4-4AF5-94FA-19EAD6B7D711.apps.XXXXX.biz",
  "ClientName": "Developer Console",
  "AllowedRedirectUris": [
    "http://localhost:55000/signin-oidc",
    "http://localhost:55000/auth.html",
    "http://localhost:55000/auth-silent.html"
    "https://developerconsole.XXXXX.io/signin-oidc"
  ],
  "SubjectId": "21379983",
  "RequestedScopes": "",
  "Raw": {
    "client_id": "BB1D2DA8-D7E4-4AF5-94FA-19EAD6B7D711.apps.XXXXX.biz",
    "redirect_uri": "http://developerconsole.XXXXX.io/signin-oidc",
    "response_type": "code id_token",
    "scope": "openid profile testapi devconsole offline_access",
    "response_mode": "form_post",
    "nonce": "636625889658410682.MjNlMmQwNjgtZmY0MC00MmVkLWFiNmMtN2M2YmQ5YTM5ZTQ3NjFiYzI2ZjktZWM0Yi00NDk3LTk1ZWMtNjJkYjViMDYwMTJm",
    "state": "CfDJ8Pwa8A3ipXlKtuyxNMpMxAz5QUFmdSunRKdlKS9sS390AKp8gIUZShQUMMCkFAhYLytitgsXUBgwlQDJaJvtHFqzHygLCPwS8Jab6IJzhpry90qS51E1y_eRlppamRDOzYDZ6fcDFzWV1U43BTP2B6pnPTSLNcZRaooyGBXtNokeUqOJ--u-_MOQB8Bw3n2cRyV4kisHNkslD1Gsi2wn1Cx6aTVlqzw_pxHelAXm1P8FyDJpD7G0azFgKgpQF0DRJtC5penRJQzHIHvQN8v4ECGeuSD1zlyfJYClLO2r6kY_R2OYqtBkV0r_SNc9h7xUYmnVaHKQzYqVc_mJO4iLLSMTZrBUICZWR8c4PZw0Os3N",
    "x-client-SKU": "ID_NET",
    "x-client-ver": "2.1.4.0"
  }
}

The error is coming because i have "https://developerconsole.XXXXX.io/signin-oidc" as a redirect uri and not "http://developerconsole.XXXXX.io/signin-oidc" I dont want to add HTTP redirect uris.出现错误是因为我有"https://developerconsole.XXXXX.io/signin-oidc"作为重定向 uri 而不是"http://developerconsole.XXXXX.io/signin-oidc"我不想添加 HTTP 重定向尿。

Why is my app building the redirect uri has http and not https?为什么我的应用程序构建重定向 uri 具有 http 而不是 https?

If i do add the HTTP on i am getting an annoying Correlation error.如果我确实添加了 HTTP,我会收到一个恼人的关联错误。 which i think is due to the fact that its being returned by the server as https since the server automatically converts http to https.我认为这是由于它被服务器返回为 https,因为服务器自动将 http 转换为 https。

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。 Exception: Correlation failed.异常:关联失败。 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

Stack Query Cookies Headers Exception: Correlation failed.堆栈查询 Cookies 标头异常:关联失败。 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext() Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

I probably dont need to mention this works fine on localhost:/我可能不需要提及这在本地主机上运行良好:/

The solution was quite simple. 解决方案非常简单。 By setting UseForwardedHeaders it now sends all the requests as HTTPS. 通过设置UseForwardedHeaders,它现在将所有请求作为HTTPS发送。

app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedProto
        });

Correlation failed. 关联失败。

is now fixed and i no longer need to have a http and https redirect uris. 现在已修复,我不再需要http和https重定向uris。

ASP.NET core documentation says if the forwarded headers are not working add this middleware ASP.NET 核心文档说,如果转发的标头不起作用,请添加此中间件

app.Use((context, next) =>
{
    context.Request.Scheme = "https";
    return next(context);
});

Refer to the Scenarios and User cases section of - https://learn.microsoft.com/en-us/as.net/core/host-and-deploy/proxy-load-balancer?view=as.netcore-6.0请参阅场景和用户案例部分 - https://learn.microsoft.com/en-us/as.net/core/host-and-deploy/proxy-load-balancer?view=as.netcore-6.0

only add this code to your web.config file and of course change.com with your website , anyone enter the URL in the browser direct Redirect URI from HTTP to HTTPS. 只需将此代码添加到您的web.config文件中,当然还要与您的网站一起添加到change.com中,任何人在浏览器中输入URL即可直接将URI从HTTP重定向到HTTPS。

<system.webServer>
    <rewrite>
      <rules>
        <rule name="IP Hit" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="http://www.exemple.com" />
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://www.exemple.com/{R:1}" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
    <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true" />
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365:00:00" />
    </staticContent>
 <system.webServer>

Ubuntu 18, Nginx, .NetCore 3.1 it works like: Ubuntu 18、Nginx、.NetCore 3.1 它的工作方式如下:

app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.All
            });
 

/etc/nginx/nginx.conf

fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;

/etc/nginx/sites-enabled/default or your web config file /etc/nginx/sites-enabled/default或您的网络配置文件

location / {

# under your configuration
    proxy_set_header X-Forwarded-Proto $scheme;
}

Then it started to redirect to https, and without nginx config i got error 503.然后它开始重定向到 https,没有 nginx 配置我得到错误 503。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM