Home > Blockchain >  How to pass Enum as string parameter to Authorize attribute?
How to pass Enum as string parameter to Authorize attribute?

Time:09-30

It's my first project to ASP.NET Core Authentication and Authorization and I get this error when I'm trying to pass Enum to [Authorize] attribute :

Error CS1503 Argument 1: cannot convert from 'BasicAuthAPI.Entities.Role' to 'string'

Here is my controller method which gives this error:

[Authorize(Role.Admin)]
[HttpGet]
public IActionResult GetAll()
{
     var users = _userService.GetAll();
     return Ok(users);
}

Role enum:

public enum Role
    {
        Admin,
        User
    }

User Entity:

public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Username { get; set; }
        public Role Role { get; set; }

        [JsonIgnore]
        public string PasswordHash { get; set; }
    }

And the _userService which I have mentioned in controller:

public class UserService : IUserService
    {
        private DataContext _context;
        private IJwtUtils _jwtUtils;
        private readonly AppSettings _appSettings;

        public UserService(
            DataContext context,
            IJwtUtils jwtUtils,
            IOptions<AppSettings> appSettings)
        {
            _context = context;
            _jwtUtils = jwtUtils;
            _appSettings = appSettings.Value;
        }


        public AuthenticateResponse Authenticate(AuthenticateRequest model)
        {
            var user = _context.Users.SingleOrDefault(x => x.Username == model.Username);

            // validate
            if (user == null || !BCryptNet.Verify(model.Password, user.PasswordHash))
                throw new AppException("Username or password is incorrect");

            // authentication successful so generate jwt token
            var jwtToken = _jwtUtils.GenerateJwtToken(user);

            return new AuthenticateResponse(user, jwtToken);
        }

        public IEnumerable<User> GetAll()
        {
            return _context.Users;
        }

        public User GetById(int id)
        {
            var user = _context.Users.Find(id);
            if (user == null) throw new KeyNotFoundException("User not found");
            return user;
        }
    }

How can I pass the Admin Role to [Authorize] attribute?

CodePudding user response:

Either use string constants

public static class Role
{
    public static string Admin = "Admin";
    public static string User = "User";
}

or you can use nameof

[Authorize(nameof(Role.Admin))]

CodePudding user response:

You can just call .ToString()

[Authorize(Role.Admin.ToString())]
[HttpGet]
public IActionResult GetAll()
{
     var users = _userService.GetAll();
     return Ok(users);
}

Looking at the answer from Alexander I have found the following SO post which highlights the difference between nameof and ToString: What is the difference between MyEnum.Item.ToString() and nameof(MyEnum.Item)?

  • Related