C# OIDC登录失败,出现';关联失败';-';未找到cookie';当饼干出现时
我正在使用IdentityServer 4,通过外部登录提供商(Microsoft)为我的web应用程序提供身份验证和自动授权 当我在本地运行IdentityServer和我的web应用程序时,这很好。 但是,当我将Identityserver项目发布到Azure时,它就不再工作了 当我将本地运行的web应用程序连接到已发布的IdentityServer时,从Microsoft登录页返回后,web应用程序失败,错误为“关联失败”。未知位置' web应用程序的输出显示:C# OIDC登录失败,出现';关联失败';-';未找到cookie';当饼干出现时,c#,asp.net-core,identityserver4,C#,Asp.net Core,Identityserver4,我正在使用IdentityServer 4,通过外部登录提供商(Microsoft)为我的web应用程序提供身份验证和自动授权 当我在本地运行IdentityServer和我的web应用程序时,这很好。 但是,当我将Identityserver项目发布到Azure时,它就不再工作了 当我将本地运行的web应用程序连接到已发布的IdentityServer时,从Microsoft登录页返回后,web应用程序失败,错误为“关联失败”。未知位置' web应用程序的输出显示: Microsoft.Asp
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.xxxxxxxxxxxx”的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?}");
});
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
服务
.AddTransient();
services.AddAuthentication(选项=>
{
options.DefaultScheme=“Cookies”;
options.DefaultChallengeScheme=“oidc”;
})
.AddCookie()
.AddOpenIdConnect(“oidc”,选项=>
{
options.signnscheme=“Cookies”;
options.Authority=Configuration.GetSection(“IdentityServer”).GetValue(“AuthorityUrl”);
//options.RequireHttpsMetadata=true;
options.ClientId=“mvc”;
options.ClientSecret=“secret”;
options.ResponseType=“代码id\U令牌”;
options.SaveTokens=true;
options.GetClaimsFromUserInfoEndpoint=true;
选项。范围。添加(“api1”);
options.Scope.Add(“脱机访问”);
});
services.AddLocalization(options=>options.ResourcesPath=“Resources”);
配置(选项=>
{
var supportedCultures=new[]
{
新文化资讯(“nl nl”),
新文化信息(“en-US”)
};
options.DefaultRequestCulture=新的RequestCulture(“nl nl”、“en US”);
options.SupportedCultures=SupportedCultures;
options.supportedCultures=supportedCultures;
});
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.后缀)
.AddDataAnnotationsLocalization();
services.AddMvc(配置=>
{
var policy=new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()文件
.Build();
config.Filters.Add(新的授权过滤器(策略));
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“区域”,
模板:“{area:exists}/{controller}/{action}/{id?}”);
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
}
问题在于IdentityServer仍在使用AddDeveloperSigningCredential
它在本地运行良好,但在Azure中不起作用。
通过添加certicate和此代码,它可以完美地工作:
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}");
}
我已通过添加以下代码解决了此问题
options.Events = new OpenIdConnectEvents
{
OnMessageReceived = OnMessageReceived,
OnRemoteFailure = context => {
context.Response.Redirect("/");
context.HandleResponse();
return Task.FromResult(0);
}
};
还需要帮助吗?谢谢。这是IdentityServer中的一个问题。我必须添加一个加密证书。这个解决方案是有点黑客这正是我要找的。我不想让用户知道关于登录过程的固有错误(不利于积极的用户体验)。我只希望他被抛出到主页面(现在-我将在稍后添加一个重定向到错误页面)。