CJ *_*ten 16 c# 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..
Run Code Online (Sandbox Code Playgroud)
但是,当我检查浏览器时,确实存在一个名称为“.AspNetCore.Correlation.oidc.xxxxxxxxxxxxxxxxxxx”的 cookie。
这是网络应用程序中的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?}");
});
}
}
Run Code Online (Sandbox Code Playgroud)
Sco*_*eep 28
对我来说,Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler 正在记录此错误: '".AspNetCore.Correlation.OpenIdConnect.84ee_7zFbvb_w264b0SPRmS1OTKCeDhmzQ6awHoJ5gA"' cookie 未找到。
查看 Chrome 开发人员工具后,我可以看到浏览器删除了 Correlation cookie,因为 cookie 的 SameSite 属性设置为“None”,但未设置“Secure”属性。Chrome 不喜欢这样。
我在 Startup.Configure 方法中添加了以下语句。
*注意:必须在 app.UseAuthentication() 和 app.UseAuthorization() 之前添加。
app.UseCookiePolicy(new CookiePolicyOptions
{
Secure = CookieSecurePolicy.Always
});
Run Code Online (Sandbox Code Playgroud)
我通过添加以下代码解决了这个问题
options.Events = new OpenIdConnectEvents
{
OnMessageReceived = OnMessageReceived,
OnRemoteFailure = context => {
context.Response.Redirect("/");
context.HandleResponse();
return Task.FromResult(0);
}
};
Run Code Online (Sandbox Code Playgroud)
问题是 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}");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21141 次 |
| 最近记录: |