gpt4 book ai didi

asp.net-core - ASP.NET Core 5.0 基于角色的授权

转载 作者:行者123 更新时间:2023-12-04 13:10:08 24 4
gpt4 key购买 nike

我无法定义我的 Admin、Company、Agency 角色,因为

services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

没有工作或没有定义,它给我一个错误

Error   CS1061  'IServiceCollection' does not contain a definition for 'AddDefaultIdentity' and no accessible extension method 'AddDefaultIdentity' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

这是我的 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddControllersWithViews();
services.AddDbContext<TradeTurkDBContext>();
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<TradeTurkDBContext>();

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
...
});
services.AddMvc(config =>
{
...
});
}

这是我使用的库

using BL.TradeTurk;
using DAL.TradeTurk;
using Entities.TradeTurk;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

谁能告诉我我遗漏了哪一部分?

我查看了 Microsoft 源代码中的 AddRoles 部分,我的代码和他们的源代码没有什么不同。

Here是 Microsoft 来源,一直到页面。

最佳答案

我认为问题在于管道中身份验证和授权的顺序,身份验证应始终放在授权之前。在 Configure 方法中更改您的中间件顺序,如下所示:-

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Home/Error");

app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Account}/{action=Login}/{id?}");
});
}

关于asp.net-core - ASP.NET Core 5.0 基于角色的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66295081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com