c# - 入口后面带有 Azure OAuth 的 ASP.NET Core MVC 进入无限登录循环

标签 c# asp.net-mvc oauth kubernetes-ingress

使用带有模板的简单 ASP.NET Core MVC:

来自 CLI:

dotnet new mvc --auth SingleOrg --client-id ***** --tenant-id 3**** --domain ***.onmicrosoft.com 

这将创建并搭建模板,一切在本地主机上都运行良好。

在入口后面构建和设置时,我在尝试登录时遇到无限循环。

这是我的入口 yaml:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  creationTimestamp: "2019-09-11T14:06:56Z"
  generation: 3
  name: secured-ingress
  namespace: default
  resourceVersion: "5022818"
  selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/secured-ingress
  uid: 69d948fa-d49d-11e9-ac98-3ab4552521b0
spec:
  rules:
  - host: authpr.westeurope.cloudapp.azure.com
    http:
      paths:
      - backend:
          serviceName: newad
          servicePort: 80
        path: /(.*)
  tls:
  - hosts:
    - authpr.westeurope.cloudapp.azure.com
    secretName: aks-authpr
status:
  loadBalancer:
    ingress:
    - {}

当点击上面的 URL 时,它会将我重定向到 Azure AD,然后无限地返回到登录状态。

代码中是否缺少任何内容?

我读了很多文章,似乎有很多问题。

我尝试实现: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-3.0&viewFallbackFrom=aspnetcore-2.0

startup.cs 文件进行了很多研究,但总是得到相同的行为。

无限循环。

当我查看调试日志时,我总是看到:

dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Execution plan of result filters (in the following order): Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.SaveTempDataFilter
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.

这是我当前的 startup.cs 文件:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddMvc(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                                        .RequireAuthenticatedUser()
                                        .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

if (string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED"), "true", StringComparison.OrdinalIgnoreCase))
{
    services.Configure<ForwardedHeadersOptions>(options =>
             {
                 options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | 
                                            ForwardedHeaders.XForwardedProto;
                 // Only loopback proxies are allowed by default.
                 // Clear that restriction because forwarders are enabled by  
                 // explicit configuration.
                 options.KnownNetworks.Clear();
                 options.KnownProxies.Clear();
             });
    }
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // app.UseHsts();
    }

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

    app.UseForwardedHeaders();
    // app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();

    // app.Use(async (context, next) =>
    //         {
    //              if (context.Request.IsHttps || context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps)
    //              {
    //                   await next();
    //              }
    //              else
    //              {
    //                   string queryString = context.Request.QueryString.HasValue ? context.Request.QueryString.Value : string.Empty;
    //                   var https = "https://" + context.Request.Host + context.Request.Path + queryString;
    //                   context.Response.Redirect(https);
    //              }
    //          });

app.UseMvc(routes =>
           {
                routes.MapRoute(name: "default",
                                template: "{controller=Home}/{action=Index}/{id?}");
           });
}

预期行为应该能够在身份验证成功后访问该 url, 可能是在startup.cs文件中缺少一些配置

最佳答案

我在以下人员的帮助下成功解决了该问题:https://github.com/kubernetes/ingress-nginx/issues/4675

第一个入口 yaml 应该是这样的:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
    nginx.ingress.kubernetes.io/proxy-buffering: "on"
    nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  creationTimestamp: 2019-09-11T14:06:56Z
  generation: 4
  name: secured-ingress
  namespace: default
  resourceVersion: "5177035"
  selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/secured-ingress
  uid: 69d948fa-d49d-11e9-ac98-3ab4552521b0
spec:
  rules:
  - host: authpr.westeurope.cloudapp.azure.com
    http:
      paths:
      - backend:
          serviceName: newad
          servicePort: 80
        path: /
  tls:
  - hosts:
    - authpr.westeurope.cloudapp.azure.com
    secretName: aks-authpr
status:
  loadBalancer:
    ingress:
    - {}

然后在startup.cs中 您需要在生成的内容之上设置以下内容:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //Outside dev, require HTTPS and use HSTS
                app.UseHttpsRedirection();
                app.UseHsts();
            }

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

            app.UseForwardedHeaders();
            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();
        }

关于c# - 入口后面带有 Azure OAuth 的 ASP.NET Core MVC 进入无限登录循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58357579/

相关文章:

具有多项授权的 Django OAuth 工具包

c# - 循环变量未被收集

c# - 如何从可能包含驱动器号和/或通配符的 args 构建目录列表

c# - 实现 OpenID : identifying users

c# - Jquery.Ajax 向 POST api 发送两个参数

javascript - 仅从网站限制 Controller 操作

Facebook 登录 OAuth 服务器 500 错误

c# - 在 C# 中使用游标进行字符计数

c# - asp.net mvc c#获取来自的页面的url

c# - 验证来自 Gmail 上下文小工具的签名请求