being new to ASP NET I am using a React JS default app with ASP .NET in Visual Studio 2022.
I have setup the Identity with SQL Server and login etc works fine. I want to setup Role based Authorization.
I have a new controller that looks like this
[Authorize(Roles = "SuperAdmin")]
[Route("[controller]")]
[ApiController]
public class UsersController : Controller
{
private UserManager<ApplicationUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
public UsersController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
//public UsersController() { }
// GET: api/<UsersController>
[HttpGet]
public async Task<IEnumerable<ApplicationUser>> Get()
{
// ApplicationUser u = await _userManager.GetUserAsync(User);
The issue is that whenever I change [Authorize] without a role the react fetch works fine, but with the role it returns FORBIDDEN 403 error.
I have tried both claims as well as roles to be added
await userManager.CreateAsync(defaultUser, "#ond@BKD678!");
var claim = new Claim(ClaimTypes.Role, "SuperAdmin");
await userManager.AddToRoleAsync(defaultUser, UserRoles.SuperAdmin.ToString());
await userManager.AddClaimAsync(defaultUser, claim);
I have used the standard code that gets created when you create a new project
builder.Services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles() .AddEntityFrameworkStores();
builder.Services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
options.AccessDeniedPath = "/Forbidden/";
})
.AddIdentityServerJwt();
for reference my react fetch looks like the below
async populateUsersData()
{
const token = await authService.getAccessToken();
const response = await fetch('users', {
headers: !token ? {} : { 'Authorization': `Bearer ${token}` }
});
const data = await response.json();
this.setState({ userslist: data, loading: false });
}
Login, authentication etc works fine... but the fetch call always returns forbidden whenever try [Authorize(Roles = "SuperAdmin")] but works fine with I use [Authorize]. I want to use role based authentication...
Please help!! I have tried many things... what am I missing???
PS: the code shown is trying to just list the full set of registered users for a SuperAdmin user.