net.core/asp.net identity/openid connect 中的关联失败 [英] Correlation failed in net.core / asp.net identity / openid connect

查看:34
本文介绍了net.core/asp.net identity/openid connect 中的关联失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Azure AD 用户登录时收到此错误(我能够在之后获得用户的声明),我使用 OpenIdConnect 的组合,以及 net.core 2.0 上的 asp.net Identity 核心

<块引用>处理请求时发生未处理的异常.例外:关联失败.Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

跟踪:

<块引用>例外:关联失败.Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)System.Runtime.CompilerServices.TaskAwaiter.GetResult()Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext()System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

这是我的 Startup.cs:

使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Threading.Tasks;使用 BPT.PC.IdentityServer.Data;使用 BPT.PC.IdentityServer.IdentityStore;使用 BPT.PC.IdentityServer.Models;使用 Microsoft.AspNetCore.Authentication;使用 Microsoft.AspNetCore.Authentication.Cookies;使用 Microsoft.AspNetCore.Authentication.OpenIdConnect;使用 Microsoft.AspNetCore.Builder;使用 Microsoft.AspNetCore.Hosting;使用 Microsoft.AspNetCore.Identity;使用 Microsoft.EntityFrameworkCore;使用 Microsoft.Extensions.Configuration;使用 Microsoft.Extensions.DependencyInjection;命名空间 BPT.PC.IdentityServer.Web{公开课启动{公共启动(IConfiguration配置){配置=配置;}公共 IConfiguration 配置 { 获取;}//这个方法被运行时调用.使用此方法向容器添加服务.public void ConfigureServices(IServiceCollection 服务){services.AddIdentity<用户,角色>().AddUserStore().AddRoleStore().AddDefaultTokenProviders();services.AddMemoryCache();services.AddDistributedMemoryCache();services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));服务.AddMvc();services.AddAuthentication(auth =>{auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;}).AddCookie().AddOpenIdConnect("AzureAD", opts =>{Configuration.GetSection("OpenIdConnect").Bind(opts);opts.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);opts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;opts.CorrelationCookie = 新的 Microsoft.AspNetCore.Http.CookieBuilder{HttpOnly = 假,SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None,SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.None,到期时间 = TimeSpan.FromMinutes(10)};opts.Events = new OpenIdConnectEvents(){OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,OnRemoteFailure = OnRemoteFailure,OnAuthorizationCodeReceived = OnAuthorizationCodeReceived};//opts.Events = 新的 OpenIdConnectEvents//{//OnAuthorizationCodeReceived = ctx =>//{//返回 Task.CompletedTask;//}//};});//services.ConfigureApplicationCookie(options =>//{////Cookie 设置//options.Cookie.HttpOnly = true;//options.ExpireTimeSpan = TimeSpan.FromMinutes(30);//options.SlidingExpiration = true;//});}私人任务 OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext arg){返回 Task.FromResult(0);}私有任务 OnRemoteFailure(RemoteFailureContext arg){返回 Task.FromResult(0);}私有任务 OnRedirectToIdentityProvider(RedirectContext arg){返回 Task.FromResult(0);}//这个方法被运行时调用.使用此方法配置 HTTP 请求管道.公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment 环境){如果 (env.IsDevelopment()){app.UseBrowserLink();app.UseDeveloperExceptionPage();}别的{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseAuthentication();app.UseMvc(routes =>{路线.MapRoute(名称:默认",模板:{controller=Account}/{action=Login}/{id?}");});}}}

我的 appsettings.json:

<代码>{记录":{包括范围":假,日志级别":{默认":警告"}},连接字符串":{"IdentityServerDb": "Server=localhost;Database=IdentityServer;Trusted_Connection=True;MultipleActiveResultSets=true"},OpenIdConnect":{"ClientId": "xxxxx","权威": "https://login.microsoftonline.com/xxxxx/","PostLogoutRedirectUri": "/Account/SignoutOidc","CallbackPath": "/Account/SigninOidc","UseTokenLifetime": 真,RequireHttpsMetadata":假,//"ResponseType": "code id_token","ClientSecret": "xxx",资源":https://graph.microsoft.com/"}}

和实现:

[HttpGet]公共 IActionResult CorpLogin(){var authProperties = _signInManager.ConfigureExternalAuthenticationProperties("AzureAD",Url.Action("SigninOidc", "Account", null, Request.Scheme));返回挑战(authProperties,AzureAD");}[HttpPost]public IActionResult SigninOidc([FromForm]object data){//这永远不会运行返回确定();}

解决方案

我终于找到了解决方案,我会在这里发布以防有人遇到类似的问题.

看起来主要问题是我的重定向 URI 与 CallBackPath 相同:

<块引用>

"CallbackPath": "/Account/SigninOidc"

var authProperties = _signInManager.ConfigureExternalAuthenticationProperties("AzureAD",Url.Action("SigninOidc", "Account", null, Request.Scheme));

好吧,这是我更正的 Startup.cs:

使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Threading.Tasks;使用 BPT.PC.IdentityServer.Data;使用 BPT.PC.IdentityServer.IdentityStore;使用 BPT.PC.IdentityServer.Models;使用 BPT.PC.IdentityServer.Web.Models;使用 Microsoft.AspNetCore.Authentication;使用 Microsoft.AspNetCore.Authentication.Cookies;使用 Microsoft.AspNetCore.Authentication.OpenIdConnect;使用 Microsoft.AspNetCore.Builder;使用 Microsoft.AspNetCore.Hosting;使用 Microsoft.AspNetCore.Http;使用 Microsoft.AspNetCore.Identity;使用 Microsoft.EntityFrameworkCore;使用 Microsoft.Extensions.Configuration;使用 Microsoft.Extensions.DependencyInjection;使用 Microsoft.IdentityModel.Protocols.OpenIdConnect;命名空间 BPT.PC.IdentityServer.Web{公开课启动{公共启动(IConfiguration配置){配置=配置;}公共 IConfiguration 配置 { 获取;}//这个方法被运行时调用.使用此方法向容器添加服务.public void ConfigureServices(IServiceCollection 服务){services.AddIdentity<用户,角色>().AddUserStore().AddRoleStore().AddDefaultTokenProviders();services.AddMemoryCache();services.AddDistributedMemoryCache();services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));服务.AddMvc();服务.AddAuthentication(auth =>{auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;}).AddCookie().AddOpenIdConnect("AzureAD", "AzureAD", options =>{Configuration.GetSection("AzureAD").Bind(options);;options.ResponseType = OpenIdConnectResponseType.CodeIdToken;options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.RequireHttpsMetadata = false;options.SaveTokens = true;});services.AddSingleton(Configuration.GetSection("OpenIdConnectProviderConfiguration").Get());}//这个方法被运行时调用.使用此方法配置 HTTP 请求管道.公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment 环境){如果 (env.IsDevelopment()){app.UseBrowserLink();app.UseDeveloperExceptionPage();}别的{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseAuthentication();app.UseMvc(routes =>{路线.MapRoute(名称:默认",模板:{controller=Account}/{action=Login}/{id?}");});}}}

最后的实现:

[HttpGet]公共 IActionResult CorpLogin(){var authProperties = _signInManager.ConfigureExternalAuthenticationProperties("AzureAD",Url.Action("LoggingIn", "Account", null, Request.Scheme));返回挑战(authProperties,AzureAD");}

appsettings.json 是一样的.

I getting this error when a Azure AD user login (I able to get the user´s claims after), im using a combination of OpenIdConnect, with asp.net Identity core over net.core 2.0

An unhandled exception occurred while processing the request. Exception: Correlation failed. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

The trace:

Exception: Correlation failed. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.GetResult() Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

Here is my Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BPT.PC.IdentityServer.Data;
using BPT.PC.IdentityServer.IdentityStore;
using BPT.PC.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace BPT.PC.IdentityServer.Web
{
    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.AddIdentity<User, Role>()
                .AddUserStore<UserStore>()
                .AddRoleStore<RoleStore>()
                .AddDefaultTokenProviders();

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddDbContext<IdentityServerDb>(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));

            services.AddMvc();
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect("AzureAD", opts =>
            {
                Configuration.GetSection("OpenIdConnect").Bind(opts);
                opts.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);
                opts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                opts.CorrelationCookie = new Microsoft.AspNetCore.Http.CookieBuilder
                {
                    HttpOnly = false,
                    SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None,
                    SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.None,
                    Expiration = TimeSpan.FromMinutes(10)
                };

                opts.Events = new OpenIdConnectEvents()
                {
                    OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    OnRemoteFailure = OnRemoteFailure,
                    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived
                };
                //opts.Events = new OpenIdConnectEvents
                //{
                //    OnAuthorizationCodeReceived = ctx =>
                //    {
                //        return Task.CompletedTask;
                //    }
                //};
            });

            //services.ConfigureApplicationCookie(options =>
            //{
            //    // Cookie settings
            //    options.Cookie.HttpOnly = true;
            //    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            //    options.SlidingExpiration = true;
            //});
        }

        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRemoteFailure(RemoteFailureContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRedirectToIdentityProvider(RedirectContext arg)
        {
            return Task.FromResult(0);
        }

        // 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.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

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

My appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "ConnectionStrings": {
    "IdentityServerDb": "Server=localhost;Database=IdentityServer;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

  "OpenIdConnect": {
    "ClientId": "xxxxx",
    "Authority": "https://login.microsoftonline.com/xxxxx/",
    "PostLogoutRedirectUri": "/Account/SignoutOidc",
    "CallbackPath": "/Account/SigninOidc",
    "UseTokenLifetime": true,
    "RequireHttpsMetadata": false,
    //"ResponseType": "code id_token",
    "ClientSecret": "xxx",
    "Resource": "https://graph.microsoft.com/"
  }
}

And the implementation:

[HttpGet]
public IActionResult CorpLogin()
{
  var authProperties = _signInManager
                .ConfigureExternalAuthenticationProperties("AzureAD",
     Url.Action("SigninOidc", "Account", null, Request.Scheme));

   return Challenge(authProperties, "AzureAD");
}

[HttpPost]
public IActionResult SigninOidc([FromForm]object data)
{
//this never runs
   return Ok();
}

解决方案

I've finally found the solution, I´ll post here just in case somebody have a similar problem.

Looks like the principal problem was that my redirect URI was the same that the CallBackPath:

"CallbackPath": "/Account/SigninOidc"

var authProperties = _signInManager .ConfigureExternalAuthenticationProperties("AzureAD", Url.Action("SigninOidc", "Account", null, Request.Scheme));

Well, here is my corrected Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BPT.PC.IdentityServer.Data;
using BPT.PC.IdentityServer.IdentityStore;
using BPT.PC.IdentityServer.Models;
using BPT.PC.IdentityServer.Web.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace BPT.PC.IdentityServer.Web
{
    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.AddIdentity<User, Role>()
                .AddUserStore<UserStore>()
                .AddRoleStore<RoleStore>()
                .AddDefaultTokenProviders();

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddDbContext<IdentityServerDb>
                (options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));

            services
                .AddMvc();
            services
                .AddAuthentication(auth =>
                {
                    auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie()
                .AddOpenIdConnect("AzureAD", "AzureAD", options =>
                {
                    Configuration.GetSection("AzureAD").Bind(options); ;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);
                    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.RequireHttpsMetadata = false;
                    options.SaveTokens = true;
                });

            services.AddSingleton(Configuration.GetSection("OpenIdConnectProviderConfiguration").Get<OpenIdConnectProviderConfiguration>());

        }
        // 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.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

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

And the finally implementation:

[HttpGet]
public IActionResult CorpLogin()
    {
        var authProperties = _signInManager
            .ConfigureExternalAuthenticationProperties("AzureAD",
            Url.Action("LoggingIn", "Account", null, Request.Scheme));

        return Challenge(authProperties, "AzureAD");
    }

The appsettings.json is the same.

这篇关于net.core/asp.net identity/openid connect 中的关联失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆