Search code examples
entity-frameworkasp.net-coreauthorize-attributemagic-string

.net core authorize Roles do not use magic string


it's my code. but not work

[Authorize(Roles = nameof(SD.ROLE_ADMIN))]
    [HttpPost]
    public async Task<IActionResult> DeleteUserAsync([FromBody] ManagementUserRequestDTO requestDTO)
    {
        var responseDTO = await _accountRepository.DeleteUser(requestDTO);

        if (responseDTO.IsSucceeded)
            return Ok(responseDTO);

        return BadRequest(responseDTO);
    }

if change [Authorize(Roles = nameof(SD.ROLE_ADMIN))] to [Authorize(Roles = "admin")] it work correctly

SD.ROLE_Admin -----> public static string ROLE_ADMIN {get; set;} = "admin" at static class

how to fix it? thank you.


Solution

  • nameof(SD.ROLE_ADMIN) equals "ROLE_ADMIN" and your Role's name is "admin", it should be enough if you change to [Authorize(Roles = SD.ROLE_ADMIN)]

    And you need to change public static string ROLE_ADMIN {get; set;} = "admin" to public const string ROLE_ADMIN = "admin". It needs to be a constant expression.