Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 为什么可以';我在API控制器中使用角色授权吗_Reactjs_Asp.net Core_Identityserver4_Asp.net Core Identity - Fatal编程技术网

Reactjs 为什么可以';我在API控制器中使用角色授权吗

Reactjs 为什么可以';我在API控制器中使用角色授权吗,reactjs,asp.net-core,identityserver4,asp.net-core-identity,Reactjs,Asp.net Core,Identityserver4,Asp.net Core Identity,我使用asp.net core中的react模板创建了一个react项目,该模板使用单个用户帐户。我环顾四周,发现我需要在启动文件中添加角色,并添加一个配置文件服务,这似乎已经奏效了一半 我可以在我的授权令牌中看到如下角色: “角色”:[ “管理员”, “簿记”], 但是,当我将[Authorize(Roles=“admin”)]标记添加到我的控制器时,请求现在被禁止,即使我可以看到我的令牌包含角色“admin” 我在这里错过了什么或做错了什么 这是配置文件服务: public类Profile

我使用asp.net core中的react模板创建了一个react项目,该模板使用单个用户帐户。我环顾四周,发现我需要在启动文件中添加角色,并添加一个配置文件服务,这似乎已经奏效了一半

我可以在我的授权令牌中看到如下角色:

“角色”:[
“管理员”,
“簿记”],
但是,当我将
[Authorize(Roles=“admin”)]
标记添加到我的控制器时,请求现在被禁止,即使我可以看到我的令牌包含角色“admin”

我在这里错过了什么或做错了什么

这是配置文件服务:

public类ProfileService:IProfileService
{
受保护的用户管理器mUserManager;
公共配置文件服务(UserManager UserManager)
{
mUserManager=userManager;
}
公共异步任务GetProfileDataAsync(ProfileDataRequestContext上下文)
{
ApplicationUser user=wait mUserManager.GetUserAsync(context.Subject);
IList roles=wait mUserManager.GetRolesAsync(用户);
IList roleClaims=新列表();
foreach(角色中的字符串角色)
{
roleClaims.Add(新索赔(JwtClaimTypes.Role,Role));
}
Add(新声明(JwtClaimTypes.Name,user.UserName));
context.IssuedClaims.AddRange(roleClaims);
}
公共任务IsActiveAsync(IsActiveContext上下文)
{
返回Task.CompletedTask;
}
}
这是我的启动文件:

公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“DefaultConnection”);
services.AddDefaultIdentity(options=>options.SignIn.RequireConfirmedAccount=true)
.AddRoles()
.AddRoleManager()
.AddEntityFrameworkStores();
services.AddIdentityServer()
.addapi授权();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddAuthorization(选项=>
{
options.AddPolicy(“RequireAdministratorRole”,
policy=>policy.RequireRole(“admin”);
});
services.AddTransient();
services.AddControllersWithViews()
.AddNewtonsoftJson(选项=>
options.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddRazorPages();
//在生产中,React文件将从此目录提供服务
services.AddSpaStaticFiles(配置=>
{
configuration.RootPath=“ClientApp/build”;
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller}/{action=Index}/{id?}”);
endpoints.MapRazorPages();
});
app.UseSpa(spa=>
{
spa.Options.SourcePath=“ClientApp”;
if(env.IsDevelopment())
{
用户eactdevelopmentserver(npmScript:“开始”);
}
});
}
}
我的API控制器的一个小版本:

[Authorize(Roles=“admin”)]
[路由(“api/[控制器]”)]
公共类SampleDataController:ControllerBase
{
私有只读应用程序dbContext_db;
公共SampleDataController(ApplicationDbContext数据库)
{
_db=db;
}   
[HttpGet(“[action]”)
公共IEnumerable GetOrderList()
{
return _db.Order.ToList();
}
}
还有我的取回方法

异步populateOrderList(){ const token=await authService.getAccessToken(); const response=wait fetch('api/SampleData/GetOrderList'{ 头:!令牌?{}:{'Authorization':`Bearer${token}`} }); const data=wait response.json(); this.setState({orderList:data}); } 正如您在我的启动文件中所看到的,我还尝试使用了一个策略,标记为
[Authorize(policy=“RequireAdministratorRole”)]
。当我只使用
[Authorize]

编辑:我的api控制器与我的identity server位于同一项目中


提前感谢您的帮助。

更改启动中角色的默认索赔类型,如下所示:

        services.Configure<IdentityOptions>(options =>
        {
            options.ClaimsIdentity.RoleClaimType = JwtClaimTypes.Role;
        });
services.Configure(选项=>
{
options.ClaimsIdentity.RoleClaimType=JwtClaimTypes.Role;
});

更改启动中角色的默认索赔类型,如下所示:

        services.Configure<IdentityOptions>(options =>
        {
            options.ClaimsIdentity.RoleClaimType = JwtClaimTypes.Role;
        });
services.Configure(选项=>
{
options.ClaimsIdentity.RoleClaimType=JwtClaimTypes.Role;
});

Hi@Mehrdad,谢谢你的帮助。遗憾的是,它仍然被禁止。请尝试[Authorize(LocalApi.PolicyName)]和[Authorize(Roles=“admin”)]切换