Asp.net核心剃须刀页面,身份,外部登录返回错误关联失败

时间:2019-09-06 16:54:39

标签: asp.net-core oauth-2.0 asp.net-identity

我已经建立并正在运行一个网站,浏览日志时,我发现了以下错误。我发现了类似的问题,但是它们都使用了Odic而不是Identity。

我在本地进行了测试,并且出现了相同的问题。

我已经设置了https和www重定向,因此尝试禁用它们并仍然得到相同的结果。

我尝试移动app.UseAuthentication();周围也没有好处。

我启用了添加尾部斜杠选项,禁用了该选项没有效果...

我很困惑。

  

例外   System.Exception:处理远程登录时遇到错误。 ---> System.Exception:关联失败。 -内部异常堆栈跟踪的结尾--在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)在Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()在Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext上下文),Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)处于Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware。 httpContext),位于Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)

正如我读到的Odic问题所示,刷新页面将使过程继续进行。  我的ConfigureServices看起来像这样:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.Strict;
        });
        services.AddResponseCompression(options =>
        {
            options.Providers.Add<BrotliCompressionProvider>();
            options.Providers.Add<GzipCompressionProvider>();
            options.MimeTypes =
                ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "image/svg+xml" });
        });
        services.Configure<BrotliCompressionProviderOptions>(options =>
        {
            options.Level = CompressionLevel.Optimal;
        });
        services.Configure<GzipCompressionProviderOptions>(options =>
        {
            options.Level = CompressionLevel.Optimal;
        });
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("SqlConnectionString")));
        services.AddDbContext<LoggingDbContext>(options => {
            options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString"));
        });
        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.SignIn.RequireConfirmedEmail = true;
        })
            .AddDefaultUI()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddAuthentication()
                        .AddMicrosoftAccount(microsoftOptions =>
                        {
                            microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
                            microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
                        })
                        .AddGoogle(options =>
                        {
                            IConfigurationSection googleAuthNSection =
                                Configuration.GetSection("Authentication:Google");

                            options.ClientId = googleAuthNSection["ClientId"];
                            options.ClientSecret = googleAuthNSection["ClientSecret"];
                        })
                        .AddFacebook(facebookOptions => {
                            facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
                            facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                        });
        services.Configure<DataProtectionTokenProviderOptions>(options =>
        {
            options.TokenLifespan = TimeSpan.FromDays(7);
        });
        services.AddHsts(options =>
        {
            options.Preload = true;
            options.IncludeSubDomains = true;
            options.MaxAge = TimeSpan.FromDays(1);
        });

        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
            options.HttpsPort = 443;
        });
        services.AddSession();
        //services.AddResponseCaching();
        var adminPolicy = new AuthorizationPolicyBuilder()
                      .RequireAuthenticatedUser()
                      .RequireRole(Administrator)
                      .Build();
        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdmin", policy => {
                policy.RequireAuthenticatedUser();
                policy.RequireRole(Administrator);
            });
        });
        services.AddMvc().AddRazorPagesOptions(options =>
        {
            options.Conventions.AuthorizePage("/Users");
            options.Conventions.AuthorizePage("/ViewProfile");
            options.Conventions.AuthorizePage("/NewsFeed");
            options.Conventions.AuthorizePage("/PostEdit");
            options.Conventions.AuthorizePage("/PostDelete");
            options.Conventions.AuthorizePage("/Message");
            options.Conventions.AuthorizePage("/RelationshipManager");
            options.Conventions.AuthorizeAreaFolder("Administration", "/", "RequireAdmin");
            options.Conventions.AllowAnonymousToPage("/Index");
            options.Conventions.AllowAnonymousToPage("/Privacy");
            options.Conventions.AllowAnonymousToPage("/Terms");
            options.Conventions.AllowAnonymousToAreaPage("Horses", "/HorseBrowser/Index");
            options.Conventions.AuthorizeAreaPage("Horses", "/HorseBrowser/AddHorse");
            options.Conventions.AuthorizeAreaPage("Horses", "/HorseBrowser/EditHorse");
            options.Conventions.AuthorizeAreaPage("Horses", "/HorseBrowser/DeleteHorse");
            options.Conventions.AuthorizeAreaPage("Horses", "/MakeAnOffer");
            options.Conventions.AuthorizeAreaPage("Horses", "/Oops");

        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .AddJsonOptions(x => {
            x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            x.SerializerSettings.PreserveReferencesHandling =
                Newtonsoft.Json.PreserveReferencesHandling.Objects;
        }).AddFacebookWebHooks();
        services.Configure<RouteOptions>(options =>
        {
            options.AppendTrailingSlash = true;
        });
        services.AddSignalR().AddMessagePackProtocol();
        services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
        services.Configure<MailGunSettings>(Configuration.GetSection("MailGunSettings"));
        services.Configure<FacebookOptions>(Configuration.GetSection(nameof(FacebookOptions)));
        services.AddSingleton<IUploadSettings>(Configuration.GetSection("UploadSettings").Get<UploadSettings>());
        services.AddSingleton<IVapidKeys>(Configuration.GetSection("VapidKeys").Get<VapidKeys>());

        services.AddTransient<IEmailService, EmailService>();
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddHttpClient<CountriesService>();
        services.AddAngleSharp();
        services.AddSingleton<GenericPageScraper>();
        services.AddSingleton<IUserIdProvider, EmailBasedUserIdProvider>();
        services.AddScoped<IChatRepository, ChatRepository>();
        services.AddScoped<IPostRepository, PostRepository>();
        services.AddScoped<IHorseRepository, HorseRepository>();
        services.AddScoped<IDeviceRepository, DeviceRepository>();
        services.AddScoped<IWebPushRepository, WebPushRepository>();
        services.AddScoped<ILogsRepository, LogsRepository>();

    }

还有我的Congure:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //app.UseSerilogRequestLogging();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseAspNetCoreExceptionHandler();
            // 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.UseHttpsRedirection();
        var options = new RewriteOptions()
        .AddRedirectToHttpsPermanent()
        .AddRedirectToWwwPermanent();
        app.UseRewriter(options);

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();
        app.UseSignalR(hubs =>
        {
            hubs.MapHub<NagbookHub>("/hub");
            hubs.MapHub<PostHub>("/posthub");
        });
        app.UseSession();
        //app.UseResponseCaching();
        app.UseMvc();
    }

任何提供商(无论是Microsoft,Facebook还是Google)都有错误。

我正在使用进程内托管,并且在运行服务器2012R2的VPS内的IIS上托管。

我们对此提供了任何帮助。 在此先感谢:)

2 个答案:

答案 0 :(得分:0)

好,所以要掌心时间...

我要做的就是将cookie策略更改为:

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.Lax;
        });

真的很明显,并且总是在代码的顶部……很重要。

答案 1 :(得分:0)

尝试检查您的回调 url 并返回 url。我通过更改返回 url 修复了此错误。