[英]How to sign in ASP.NET Core Identity User, using OpenIdConnect Authentication?
I'm using ASP.NET Identity to authenticate my users and I want to be able to do this via Azure AD as well. 我正在使用ASP.NET Identity来验证我的用户,我也希望能够通过Azure AD进行身份验证。 All users will be in the DB beforehand, so all I need to do is sign them in and set their cookies, if the AzureAD login was successful. 所有用户都将事先位于数据库中,因此,如果AzureAD登录成功,那么我需要做的就是登录他们并设置其Cookie。 The problem is that when I implement the new external authentication and validate that they exist in my DB, they are not signed in. So after successful remote login, if in my controller I check for User.Identity.IsAuthenticated
it returns true
, but _signInManager.IsSignedIn(User)
, it returns false
. 问题是,当我实施新的外部身份验证并验证它们是否存在于数据库中时,它们没有登录。因此,在成功远程登录之后,如果在我的控制器中检查User.Identity.IsAuthenticated
它返回true
,但是_signInManager.IsSignedIn(User)
,它返回false
。 I have tried to follow the MS guidelines and documentation, but I assume there is something wrong with my config. 我试图遵循MS指南和文档,但是我认为我的配置有问题。
Here's the startup: 这是启动:
services.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddRouting(options =>
{
options.LowercaseQueryStrings = true;
options.LowercaseUrls = true;
});
services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("<my_db_connection_string_here>")));
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddUserManager<UserManager<ApplicationUser>>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
Configuration.GetSection("OpenIdConnect").Bind(options);
options.TokenValidationParameters.ValidateIssuer = false;
options.Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = async ctx =>
{
var request = ctx.HttpContext.Request;
var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);
var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
string userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
var authContext = new AuthenticationContext(ctx.Options.Authority);
var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource);
ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
}
};
});
var builder = services.AddIdentityCore<ApplicationUser>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddLogging(options =>
{
options.AddConfiguration(Configuration.GetSection("Logging"))
.AddConsole();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
IdentityModelEventSource.ShowPII = true;
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
And in my controller: 在我的控制器中:
[AllowAnonymous]
public IActionResult AzureLogin()
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction(nameof(HandleLogin)):
}
return Challenge(new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(HandleLogin))
});
}
[Authorize]
public async Task<IActionResult> HandleLogin()
{
var isAuth = User.Identity.IsAuthenticated; // true
var isSigned = _signInmanager.IsSignedIn(User); // false
return ....
}
You could try to set AutomaticAuthenticate
cookie to true
: 您可以尝试将AutomaticAuthenticate
cookie设置为true
:
services.Configure<IdentityOptions>(options => {
// other configs
options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
});
Here's how I managed to do it: Since I'm authorizing the user via ASP.NET Identity, I changed the default authentication method in the authentication options to options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
我设法做到这一点:因为我通过ASP.NET Identity授权用户,所以我将身份验证选项中的默认身份验证方法更改为options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
and in the OpenIdConnectOptions
OnAuthorizationCodeRecieved
event, I validate and sign in the Identity User via the SignInManager.SignInAsync()
method 在OpenIdConnectOptions
OnAuthorizationCodeRecieved
事件中,我通过SignInManager.SignInAsync()
方法验证并登录身份用户
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.