Search code examples
c#asp.net-core-mvc.net-6.0

issue in role based authorization in c#


i am trying to implement authentication and authorization in c# project.

authentication is working fine.

while trying to achieve role based authorization like this->

[System.Web.Http.Authorize(Roles = UserRoles.Admin)]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
public class StudentsController : ControllerBase

.
.
.

i am able to access this controller even with a User role.

i have used this inside my HttpGet method

var isAdmin = User.IsInRole(UserRoles.Admin);

this returns false.

what could be the issue?

if you need any other code, please let me know i can add it.

i have followed this tutorial https://www.c-sharpcorner.com/article/jwt-authentication-and-authorization-in-net-6-0-with-identity-framework/

i am working with .net 6.0


Solution

  • Seems like I was using wrong import for Authorize (System.Web.Http.Authorize attribute is for WebForms).

    After using import from Microsoft.AspNetCore.Authorization issue was fixed.