Gup*_*R4c 7 c# asp.net-identity asp.net-core
我在使用ASP.NET Core 2.1站点时遇到了一个奇怪的问题。登录并在30分钟后刷新时,总是会抛出此异常:
InvalidOperationException:没有为方案“ Identity.External”注册任何注销身份验证处理程序。注册的注销方案为:Identity.Application。您是否忘记了调用AddAuthentication()。AddCookies(“ Identity.External”,...)?
没Identity.External注册是正确的,但我也不想注册。为什么它一直尝试退出?这是我注册我的cookie的方法:
services.AddAuthentication(
o => {
o.DefaultScheme = IdentityConstants.ApplicationScheme;
}).AddCookie(IdentityConstants.ApplicationScheme,
o => {
o.Events = new CookieAuthenticationEvents {
OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
};
});
services.ConfigureApplicationCookie(
o => {
o.Cookie.Expiration = TimeSpan.FromHours(2);
o.Cookie.HttpOnly = true;
o.Cookie.SameSite = SameSiteMode.Strict;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.AccessDeniedPath = "/admin";
o.LoginPath = "/admin";
o.LogoutPath = "/admin/sign-out";
o.SlidingExpiration = true;
});
Run Code Online (Sandbox Code Playgroud)
有人可以为我指出正确的解决方法吗?
更新
这是@Edward在注释中要求的完整代码和使用过程。为了简洁起见,我省略了一些部分。
Startup.cs
public sealed class Startup {
public void ConfigureServices(
IServiceCollection services) {
// ...
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddApplicationIdentity();
services.AddScoped<ApplicationSignInManager>();
services.Configure<IdentityOptions>(
o => {
o.Password.RequiredLength = 8;
o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
o.Lockout.MaxFailedAccessAttempts = 5;
});
services.ConfigureApplicationCookie(
o => {
o.Cookie.Name = IdentityConstants.ApplicationScheme;
o.Cookie.Expiration = TimeSpan.FromHours(2);
o.Cookie.HttpOnly = true;
o.Cookie.SameSite = SameSiteMode.Strict;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.AccessDeniedPath = "/admin";
o.LoginPath = "/admin";
o.LogoutPath = "/admin/sign-out";
o.SlidingExpiration = true;
});
// ...
}
public void Configure(
IApplicationBuilder app) {
// ...
app.UseAuthentication();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
ServiceCollectionExtensions.cs
public static class ServiceCollectionExtensions {
public static IdentityBuilder AddApplicationIdentity(
this IServiceCollection services) {
services.AddAuthentication(
o => {
o.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
o.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
o.DefaultForbidScheme = IdentityConstants.ApplicationScheme;
o.DefaultSignInScheme = IdentityConstants.ApplicationScheme;
o.DefaultSignOutScheme = IdentityConstants.ApplicationScheme;
}).AddCookie(IdentityConstants.ApplicationScheme,
o => {
o.Events = new CookieAuthenticationEvents {
OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
};
});
services.TryAddScoped<SignInManager<User>, ApplicationSignInManager>();
services.TryAddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
services.TryAddScoped<IdentityErrorDescriber>();
services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<User>>();
services.TryAddScoped<IUserClaimsPrincipalFactory<User>, UserClaimsPrincipalFactory<User>>();
services.TryAddScoped<UserManager<User>>();
services.TryAddScoped<IUserStore<User>, ApplicationUserStore>();
return new IdentityBuilder(typeof(User), services);
}
}
Run Code Online (Sandbox Code Playgroud)
DefaultController.cs
[Area("Admin")]
public sealed class DefaultController :
AdminControllerBase {
[HttpPost, AllowAnonymous]
public async Task<IActionResult> SignIn(
SignIn.Command command) {
var result = await Mediator.Send(command);
if (result.Succeeded) {
return RedirectToAction("Dashboard", new {
area = "Admin"
});
}
return RedirectToAction("SignIn", new {
area = "Admin"
});
}
[HttpGet, ActionName("sign-out")]
public async Task<IActionResult> SignOut() {
await Mediator.Send(new SignOut.Command());
return RedirectToAction("SignIn", new {
area = "Admin"
});
}
}
Run Code Online (Sandbox Code Playgroud)
SignIn.cs
public sealed class SignIn {
public sealed class Command :
IRequest<SignInResult> {
public string Password { get; set; }
public string Username { get; set; }
}
public sealed class CommandHandler :
HandlerBase<Command, SignInResult> {
private ApplicationSignInManager SignInManager { get; }
public CommandHandler(
DbContext context,
ApplicationSignInManager signInManager)
: base(context) {
SignInManager = signInManager;
}
protected override SignInResult Handle(
Command command) {
var result = SignInManager.PasswordSignInAsync(command.Username, command.Password, true, false).Result;
return result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
SignOut.cs
public sealed class SignOut {
public sealed class Command :
IRequest {
}
public sealed class CommandHandler :
HandlerBase<Command> {
private ApplicationSignInManager SignInManager { get; }
public CommandHandler(
DbContext context,
ApplicationSignInManager signInManager)
: base(context) {
SignInManager = signInManager;
}
protected override async void Handle(
Command command) {
await SignInManager.SignOutAsync();
}
}
}
Run Code Online (Sandbox Code Playgroud)
从我如何配置身份到登录和注销,都有所有相关的代码。Identity.External当我从未提出要求时,我仍然不知道为什么会出现在图片中。
从技术上讲SignIn,SignOut可以删除和类,并将它们的功能合并到中DefaultController,但是我选择保留它们以保持应用程序结构一致。
首先,我会避免扩展 ServiceCollection 类。相反,我会调用 AddIdetityCore 方法。在此处检查源代码。
然后:
services.AddIdentityCore<ApplicationUser>()
.AddUserStore<UserStore>()
.AddDefaultTokenProviders()
.AddSignInManager<SignInManager<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)
其次,在 AddCookie 方法选项中设置 Events 属性。由于您没有为 ValidationInterval 属性设置一段时间,因此它将持续 30 分钟。这意味着一旦时间结束,将在服务器执行的下一个请求中验证用户的 SecurityStamp 属性。由于在您所做的描述中您没有说您是否更改了密码,我怀疑用户的 SecurityStamp 在 BD 中为空而其 Cookie 版本为空字符串,因此当 Identity 在两个版本之间进行验证时 (null = = "") 它将是假的,然后 Identity 将尝试关闭 Application Scheme、Extern one 和 TwoFactor 的会话。然后它会抛出异常,因为只有 ApplicationScheme 被注册:
public virtual async Task SignOutAsync()
{
await Context.SignOutAsync(IdentityConstants.ApplicationScheme);
await Context.SignOutAsync(IdentityConstants.ExternalScheme); //<- Problem and...
await Context.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme); //... another problem.
}
Run Code Online (Sandbox Code Playgroud)
解决方案是首先确保 SecurityStamp 不为空。然后你有两个选择:
或者
覆盖 SignInManager 类中的 SignOutAsync 方法。
public class SignInManager<TUser> : Microsoft.AspNetCore.Identity.SignInManager<TUser>
where TUser : class
{
public SignInManager(
UserManager<TUser> userManager,
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<TUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILogger<Microsoft.AspNetCore.Identity.SignInManager<TUser>> logger,
IAuthenticationSchemeProvider schemes)
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
{
}
public async override Task SignOutAsync()
{
await Context.SignOutAsync(IdentityConstants.ApplicationScheme); // <-
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
services.AddIdentityCore<ApplicationUser>()
.AddUserStore<UserStore>()
.AddDefaultTokenProviders()
.AddSignInManager<Services.Infrastructure.Identity.SignInManager<ApplicationUser>>() //<-
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1480 次 |
| 最近记录: |