I have a doubt on API securing with identity server4
IdentityResource
Name | Claims |
---|---|
Roles | role |
APIResource
Name | Scopes |
---|---|
testapi | api1 |
APIScopes
Name | Claims |
---|---|
api1 | address |
In Startup.cs
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddJwtBearer("Bearer", opt =>
{
opt.Audience = "testapi";
opt.Authority = "https://localhost:5001";
opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateAudience = true
};
});
//Policy "Apiscope" created
services.AddAuthorization(opt =>
{
opt.AddPolicy("Apiscope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("Scope", "api1");
});
});
services.AddAuthorization(opt =>
{
opt.AddPolicy("AdminUsers", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole("admin");
});
});
In controller
[HttpPost]
[Authorize(Policy = "AdminUsers")]
public IActionResult GetAdminMessage()
{
return Ok("Hello Admin");
}
- Is it possible access identity scope in .Net Core API? if yes, How to do?
- To get the role value, do I need to add in APIScopes of "api1" userclaims as "address,role" or can do it by above Q1 ?
- In Policy "AdminUser", I am checking role by adding "api1" (APIScopes) userclaims as "address,role" but I could not access GetAdminMessage(). How to achieve this?