System.InvalidOperationException:没有为该方案注册注销身份验证处理程序

问题描述 投票:0回答:1

我使用 Asp Identity 进行了简单的 api 设置,登录、创建和 2fa 路由工作正常,但是当我尝试调用注销时,我收到以下错误响应

System.InvalidOperationException:没有为方案“Identity.Application”注册注销身份验证处理程序。注册的注销方案是:Identity.Bearer。您是否忘记调用 AddAuthentication().AddCookie("Identity.Application",...)? 在 Microsoft.AspNetCore.Authentication.AuthenticationService.SignOutAsync(HttpContext 上下文、字符串方案、AuthenticationProperties 属性) 在 Microsoft.AspNetCore.Identity.SignInManager`1.SignOutAsync() 在程序中。<>c.<<$>b__0_2>d.MoveNext()

我的program.cs 文件,这里是否缺少任何配置更改?

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql("Server=localhost;Database=PartnerPortal;Port=5432;User Id=postgres;Password=Password@1;Ssl Mode=Prefer;"));

builder.Services.AddIdentityCore<AgentPortalUser>()
                .AddEntityFrameworkStores<AppDbContext>()
                .AddApiEndpoints() ;

builder.Services.Configure<IdentityOptions>(options =>
{
    options.SignIn.RequireConfirmedEmail = true;
});

builder.Services.AddTransient<IEmailSender, EmailSender>();

builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
builder.Services.AddAuthorizationBuilder();
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapGroup("/account").MapIdentityApi<AgentPortalUser>();
app.MapGroup("/account").MapPost("/logout", async (SignInManager<AgentPortalUser> signInManager,
    [FromBody] object empty) =>
{
    if (empty != null)
    {
        await signInManager.SignOutAsync();
        return Results.Ok();
    }
    return Results.Unauthorized();
})
.WithOpenApi()
.RequireAuthorization();

app.MapGet("/test", (ClaimsPrincipal user) => $"Hello {user.Identity.Name}").RequireAuthorization();
app.MapControllers();
app.Run();


public class AgentPortalUser : IdentityUser;


class AppDbContext : IdentityDbContext<AgentPortalUser>
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}
c# asp.net-core asp.net-identity
1个回答
0
投票

在您的代码中,您使用了

AddIdentityCore<AgentPortalUser>() 
,它不会自动注册
Identity.Application
方案,因此您可以在AddAuthentication()之后添加
.AddCookie(IdentityConstants.ApplicationScheme)
,下面是一个示例供您参考:

builder.Services.AddAuthentication(IdentityConstants.ApplicationScheme)
    .AddCookie(IdentityConstants.ApplicationScheme)
    .AddBearerToken(IdentityConstants.BearerScheme);

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.