首页 > 解决方案 > 带有 OpenID Connect 的 ASP.Net Core 2.1:未找到相关状态属性错误

问题描述

我正在使用授权流使用 OpenID 连接 APS.Net Core 2.1 MVC 应用程序。运行以下配置时,我收到以下错误。我试图指定一个重定向 uri 并更改 addauthentication 中的字段,但没有成功。在下面找到我的 startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {

        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        //services.Configure<CookiePolicyOptions>(options =>
        //{
        //    options.CheckConsentNeeded = context => true;
        //    options.MinimumSameSitePolicy = SameSiteMode.None;
        //});

        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMemoryCache();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie("Cookies", options => {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.Headers["Location"] = "<host url>";
                return Task.CompletedTask;
            };

        })
        .AddOpenIdConnect("oicd", options =>
        {
            options.Scope.Add("openid");
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.ClientId = "<client id>";
            options.SignInScheme = "Cookies";
            options.CallbackPath = "/";
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Authority = "<authority url>";
            options.SaveTokens = true;
            options.RequireHttpsMetadata = false;
            options.Scope.Clear();
        });
    }

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


        //app.UseHttpsRedirection();

        app.UseAuthentication();
        app.UseStaticFiles();

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

        //app.UseCookiePolicy();

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

但是得到以下错误:

warn: 
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[14]
  .AspNetCore.Correlation. state property not found.
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
  An unhandled exception has occurred while executing the request.
 System.Exception: An error was encountered while handling the remote login. 
---> System.Exception: Correlation failed. 

标签: asp.net-core.net-coreauthorizationopenid-connect

解决方案


如果要动态更改重定向 url。您可以在 OIDC 中间件的 Notifications 属性中动态更改它——查看RedirectingToIdentityprovider回调和通知参数的 Protocol 属性:

options.Events.OnRedirectToIdentityProvider = async n =>
{

    n.ProtocolMessage.RedirectUri = "YourUrl";   
    await Task.FromResult(0);
};

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[14].AspNetCore.Correlation。未找到国家财产。

您是否在 DI 中有多个 OIDC 处理程序,并且您没有为每个处理程序设置唯一的回调路径?如果您使用的是 http url,也可以尝试使用 https 的 url。


推荐阅读