OIDC登录失败,并显示“关联失败”-存在cookie时出现“找不到cookie”

时间:2018-12-30 18:05:54

标签: asp.net-core identityserver4

我正在使用IdentityServer 4通过外部登录提供程序(Microsoft)为我的Web应用程序提供身份验证和自动保护。

当我在本地运行IdentityServer和Web应用程序时,此方法工作正常。 但是,当我将Identityserver项目发布到Azure时,它不再起作用。

当我将本地运行的Web应用程序连接到已发布的IdentityServer时,从Microsoft登录页面返回后,Web应用程序将失败,并显示错误“关联失败。未知位置”。

Web应用程序的输出显示:

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler: 
Warning: '.AspNetCore.Correlation.oidc.xxxxxxxxxxxxxxxxxxx' cookie not found.

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler: 
Information: Error from RemoteAuthentication: Correlation failed..

但是,当我检查浏览器时,确实存在一个名称为“ .AspNetCore.Correlation.oidc.xxxxxxxxxxxxxxxxxxx”的Cookie。.

这是Web应用程序中的startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services
            .AddTransient<ApiService>();



        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie()
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = "Cookies";

            options.Authority = Configuration.GetSection("IdentityServer").GetValue<string>("AuthorityUrl"); 
            //options.RequireHttpsMetadata = true;

            options.ClientId = "mvc";
            options.ClientSecret = "secret";
            options.ResponseType = "code id_token";

            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;

            options.Scope.Add("api1");
            options.Scope.Add("offline_access");
        });

        services.AddLocalization(options => options.ResourcesPath = "Resources");
        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("nl-NL"),
                new CultureInfo("en-US")
            };
            options.DefaultRequestCulture = new RequestCulture("nl-NL", "en-US");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
        });

        services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

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

        app.UseMvc(routes =>
        {
            routes.MapRoute(
               name: "areas",
               template: "{area:exists}/{controller}/{action}/{id?}");

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

2 个答案:

答案 0 :(得分:0)

问题是IdentityServer仍在使用AddDeveloperSigningCredential

可以在本地正常运行,但不能在Azure中运行。 通过添加证书和此代码,它可以完美地工作:

X509Certificate2 cert = null;
using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
    certStore.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certCollection = certStore.Certificates.Find(
        X509FindType.FindByThumbprint,
        // Replace below with your cert's thumbprint
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        false);
    // Get the first cert with the thumbprint
    if (certCollection.Count > 0)
    {
        cert = certCollection[0];
        Log.Logger.Information($"Successfully loaded cert from registry: {cert.Thumbprint}");
    }
}

// Fallback to local file for development
if (cert == null)
{
    cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "example.pfx"), "exportpassword");
    Log.Logger.Information($"Falling back to cert from file. Successfully loaded: {cert.Thumbprint}");
}

答案 1 :(得分:0)

我通过添加以下代码解决了这个问题

 options.Events = new OpenIdConnectEvents
                {
                    OnMessageReceived = OnMessageReceived,
                     OnRemoteFailure = context => {
                         context.Response.Redirect("/");
                         context.HandleResponse();

                         return Task.FromResult(0);
                     }

                };