C# AzureAD与asp.net核心-使用http时关联失败
我正在尝试在asp.net core 3.1 web应用程序中使用AzureAd实现用户身份验证 当应用程序在HTTPS协议上运行时,它工作正常。但当我尝试在不安全的HTTP上运行时,会出现错误C# AzureAD与asp.net核心-使用http时关联失败,c#,asp.net-core,azure-active-directory,C#,Asp.net Core,Azure Active Directory,我正在尝试在asp.net core 3.1 web应用程序中使用AzureAd实现用户身份验证 当应用程序在HTTPS协议上运行时,它工作正常。但当我尝试在不安全的HTTP上运行时,会出现错误 '.AspNetCore.Correlation.AzureADOpenID.4ts37wiZG7bAquJ4KQ6Z_eNtV8DGrkFyvZ6g63GEwq4' cookie not found. ---> System.Exception: Correlation failed. 有一个
'.AspNetCore.Correlation.AzureADOpenID.4ts37wiZG7bAquJ4KQ6Z_eNtV8DGrkFyvZ6g63GEwq4' cookie not found.
---> System.Exception: Correlation failed.
有一个最简单的例子:
Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using AzureAdTest.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace AzureAdTest
{
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.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services
.AddAuthentication()
.AddAzureAD(options =>
{
Configuration.Bind("AzureAd", options);
});
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme,
options =>
{
options.SignInScheme = IdentityConstants.ExternalScheme;
});
services.AddControllersWithViews();
services.AddSession(options =>
{
options.Cookie.IsEssential = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCookiePolicy();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Identity;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.EntityFrameworkCore;
使用AzureAdTest.数据;
使用Microsoft.AspNetCore.Authentication;
使用Microsoft.AspNetCore.Authentication.AzureAD.UI;
使用Microsoft.AspNetCore.Authentication.OpenIdConnect;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
名称空间AzureAdTest
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext发生这种情况有多种原因:
当应用程序回调路径中定义的重定向URL与identity server中定义的任何重定向URL不匹配时(在本例中为Azure AD中的应用程序注册)。请验证。另请注意
默认cookie策略正在覆盖OpenIdConnect cookie设置。在这种情况下,请删除、更新:放宽cookie策略以允许非安全。更新app.UseCookiePolicy()
中的在Startup.cs中配置方法,如下所示
app.UseCookiePolicy(新的CookiePolicyOptions{
Secure=CookieSecurePolicy.None,//如果处于调试模式
MinimumSameSitePolicy=SameSiteMode.未指定
});
未在您的节点上正确配置。虽然本地调试不需要它,但请注意已部署的环境,因为我在启动代码中没有看到这一点
我真的需要让它在http上工作,因为我们的一些开发人员不能使用https进行本地调试
对于本地调试,这是可以的。但请确保在部署的环境中使用https
另一方面(与此问题无关),可以使用来简化与Microsoft identity platform的身份验证和授权代码集成。重定向URL mathes,否则它无法与HTTP一起工作,并且在Azure端会产生不同的错误。删除app.UseCookiePolicy()
不起作用。未使用数据保护。此处无法使用Microsoft Identity Web身份验证库,因为它不支持外部登录提供商方案您的问题带有标签“azure active directory”,并且您还说“我正在尝试用AzureAd实现用户身份验证”在开始时。您可能应该更新问题以避免混淆。问题包括明显使用外部提供程序的代码和getexternallogininfosync
。在问题更新app.UseCookiePolicy
(第2点)中看不到应该更新的内容在我的回答中。请检查。这没有帮助,对不起,你能检查并确认在你的应用程序注册中注册的重定向URL是什么吗?我相信http
的URL没有注册。我已经注册了这两个URL,分别是http
和https
。问题中添加了屏幕,此错误发生在客户端,通常是表示未设置相关cookie,或者由于某些原因未发送相关cookie。如果可以找到cookie“丢失”的原因,则需要检查网络跟踪。
[AllowAnonymous]
public IActionResult AzureLogin(string returnUrl)
{
var redirectUrl = Url.Action("AzureResponse", "Home", new {returnUrl});
var properties =
_signInManager.ConfigureExternalAuthenticationProperties(AzureADDefaults.AuthenticationScheme, redirectUrl);
properties.AllowRefresh = true;
properties.IsPersistent = true;
return Challenge(properties, AzureADDefaults.AuthenticationScheme);
}
[AllowAnonymous]
public async Task<IActionResult> AzureResponse(string returnUrl = "/")
{
var info = await _signInManager.GetExternalLoginInfoAsync();
var email = info.Principal.Claims.First(x => x.Type == ClaimTypes.Email).Value;
var user = await _userManager.FindByEmailAsync(email);
if (user != null)
{
await _signInManager.SignInAsync(user, info.AuthenticationProperties);
return RedirectToAction("Private");
}
else
{
return Forbid();
}
}