简体   繁体   English

.Net Core Identity 外部登录不起作用

[英].Net Core Identity External Login not working

I have a website that has external logins set up for google.我有一个为谷歌设置了外部登录的网站。 I have been successful in getting this to work in development, but when I moved to production it failed to work.我已经成功地让它在开发中工作,但是当我转向生产时,它却失败了。 When I click the button, instead of sending me to Google's account.google.com page, it just sends me to /Identity/Account/ExternalLogins with an error code of HTTP ERROR 400 .当我单击该按钮时,它没有将我发送到 Google 的 account.google.com 页面,而是将我发送到/Identity/Account/ExternalLogins ,错误代码为HTTP ERROR 400 The button is the same between production and environment.生产和环境之间的按钮是相同的。 Other than the email sending portion, everything is the same as it was generated during scaffolding.除了 email 发送部分之外,一切都与脚手架期间生成的相同。 My production environment uses Ubuntu and Nginx.我的生产环境使用Ubuntu和Nginx。 What could be causing this?这可能是什么原因造成的? I have been unable to recreate the issue outside of production.我无法在生产之外重现该问题。

btw, this is the default button:顺便说一句,这是默认按钮:

<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
    <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" 
          title="Log in using your @provider.DisplayName account">@provider.DisplayName
    </button>
</form>

My button is the default google log-in button altered, but it works in development, so I don't think that it matters:我的按钮是更改的默认谷歌登录按钮,但它在开发中有效,所以我认为这并不重要:

<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
    <div class="g-signin2" style="border:inherit;" data-onsuccess="onSuccess" data-gapiscan="true" data-onload="true">
        <div style="height:36px;width:120px;" class="abcRioButton abcRioButtonLightBlue">
            <button class="abcRioButtonContentWrapper" style="border:inherit; background-color:white !important"
                    type="submit" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">
                <img class="position-absolute" src="https://assets.stickpng.com/images/5847f9cbcef1014c0b5e48c8.png" style="left: 12px;height: 18px;bottom: 10px;">
                <span style="font-size:13px;line-height:34px;" class="abcRioButtonContents">
                    <span class="ml-3">Sign in</span>
                </span>
            </button>
        </div>
    </div>
</form>

Here are the relevant parts of my Startup.cs with some stuff removed from ConfigureServices() for brevity:以下是我的Startup.cs的相关部分,为简洁起见,从ConfigureServices()中删除了一些内容:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("UserDB"), MySqlOptions => MySqlOptions
                .ServerVersion(new Version(8, 0, 22), ServerType.MySql)));

            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI()
                .AddDefaultTokenProviders();
            services.Configure<IdentityOptions>(options =>
            {
                options.SignIn.RequireConfirmedAccount = true;
                options.User.RequireUniqueEmail = true;
                options.User.AllowedUserNameCharacters =
                        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 8;
            });


            services.AddAuthentication()
                .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection =
                    Configuration.GetSection("Authentication:Google");

                options.ClientId = googleAuthNSection["ClientId"];
                options.ClientSecret = googleAuthNSection["ClientSecret"];
            });

            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
            ConnectionString = Configuration["ConnectionStrings:DataDB"];

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {               
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHeadElementServerPrerendering();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

After some more investigation and setting logging to trace, I found the error of:经过更多调查并将日志记录设置为跟踪后,我发现了以下错误:

Connection id "0HM5SB235ONN8" bad request data: "Requests with 'Connection: Upgrade' cannot have content in the request body."连接 ID“0HM5SB235ONN8”错误请求数据:“带有‘连接:升级’的请求不能在请求正文中包含内容。”

I think is is because of my sites-enabled/default file that I had to configure this way according to the official Blazor deployment docs :我认为是因为我必须根据官方 Blazor 部署文档以这种方式配置sites-enabled/default文件:

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                proxy_pass http://localhost:5000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Connection $http_connection;
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

The issue was in my nginx file, I had incorrectly set it up for hosting.问题出在我的 nginx 文件中,我错误地将其设置为托管。 I changed it to the following and it worked:我将其更改为以下内容并且有效:

map $http_connection $connection_upgrade {
     "~*Upgrade" $http_connection;
    default keep-alive;
}

server {
    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html;
        server_name domain.us;


    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection $connection_upgrade;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

And then I changed my Startup.cs to include:然后我更改了我的Startup.cs以包括:

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();
                });
            }
//#################
 app.UseForwardedHeaders();
 app.UseCookiePolicy(new CookiePolicyOptions(){
    MinimumSameSitePolicy = SameSiteMode.Lax
 });
 app.UseCertificateForwarding();

暂无
暂无

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

相关问题 外部登录不工作身份服务器 4 asp.net 核心 - External login not working Identity server 4 asp.net core .Net Core 身份登录页面无法在 IIS 上运行托管应用程序 - .Net Core Identity Login Page is not working hosted application on IIS Asp.Net Core Web Api 和 ReactJS:使用没有身份的外部登录提供程序进行身份验证 - Asp.Net Core Web Api and ReactJS: authentication with external login provider without identity Asp.net core razor 页面、身份、外部登录返回错误关联失败 - Asp.net core razor pages,identity, external login returns error Correlation failed 了解 ASP.NET Core Identity 中的 oauth 外部登录认证流程 - Understanding oauth external login authentication flow in ASP.NET Core Identity 在 asp.NET 核心标识中使用外部登录和发送确认邮件的问题 - Problems with using external login and sending confirmation mail in asp.NET core identity 将 Asp.Net Core Identity 与外部登录提供程序一起使用时,无法识别用户角色和声明 - User roles and claim are not recognized when using Asp.Net Core Identity with External login provider 在ASP.NET Core 2.1中,将标识与外部登录提供程序一起使用时,ExternalLogin方法是否仅应为POST? - In ASP.NET Core 2.1, using identity with external login providers, should ExternalLogin method be POST only? 默认使用哪种授权类型 ASP.NET Core Identity Microsoft External account login? - Which grant type is used by default ASP.NET Core Identity Microsoft External account login? 登录后重定向到操作不起作用 ASP.NET 核心身份 (.Net 5) - Redirect To Action Not Working after login ASP.NET Core Identity (.Net 5)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM