向 .NET 应用程序添加多个身份验证方案

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

目前我们使用 Auth0 作为会计师的身份验证机制。我们想为管理员用户添加 .Net Identity。

下面是我的代码

// Accountants
configurationbuilder.Services.AddAuth0WebAppAuthentication("AccountantScheme", options =>{    options.Domain = builder.Configuration["Auth0:Domain"]; 
options.ClientId = builder.Configuration["Auth0:ClientId"];    options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];    options.Scope = "openid profile email";
options.OpenIdConnectEvents = new OpenIdConnectEvents    {        OnAccessDenied = context =>        {            context.Response.Redirect("/");            context.HandleResponse();            return Task.FromResult(0);        }    }; 
options.CookieAuthenticationScheme = "AccountantCookies"; }).WithAccessToken(options =>{    options.Audience = builder.Configuration["Auth0:ManagementAudience"];    options.UseRefreshTokens = true;});

builder.Services.Configure<CookieAuthenticationOptions>("AccountantCookies", options =>{    options.LoginPath = "/AccountantPortal/Authentication/LogIn/Login";    options.LogoutPath = "/AccountantPortal/Authentication/LogOut/Logout";});

builder.Services.AddDbContext<DataContext>(opts => opts.UseNpgsql(builder.Configuration["Database:ConnectionString"]));

//Admins
builder.Services.AddIdentity<IdentityUser, IdentityRole>()    .AddEntityFrameworkStores<DataContext>()    .AddDefaultTokenProviders();

// Configure custom Identity cookie settings for Admins
builder.Services.ConfigureApplicationCookie(options =>{    options.Cookie.Name = "AdminIdentityCookies";    options.LoginPath = "/AdminPortal/Account/Login";    options.LogoutPath = "/AdminPortal/Account/Logout";    options.AccessDeniedPath = "/AdminPortal/Account/AccessDenied";});

当我从 Auth0 登录时,它使用默认的身份方案 我的应用程序正在使用 .net 8

c# .net authentication auth0 .net-8.0
1个回答
0
投票

您可以通过设置授权策略来设置所需的角色和身份验证方案。

更多详情,可以参考以下代码:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AccountantPolicy", policy =>
    {
        policy.AddAuthenticationSchemes("AccountantScheme");
        policy.RequireAuthenticatedUser();
    });

    options.AddPolicy("AdminPolicy", policy =>
    {
        policy.AddAuthenticationSchemes("Identity.Application");
        policy.RequireRole("Admin");
    });
});

然后你可以如下使用它:

[Authorize(Policy = "AdminPolicy")]
public class EmployeeController : Controller


[Authorize(Policy = "AccountantPolicy")]
public class EmployeeController : Controller
© www.soinside.com 2019 - 2024. All rights reserved.