0

I am using JWT token to validate user in my ASP.NET Core Web API. I try to validate user in CustomAuthorizationFilter. Here, I set the user information and after filter is finished its job, the app goes to Related Controller Endpoint, in this endpoint I would like to access the User Information which is just set in the CustomAuthorizationFilter. But it's not possible it returns null. How to achive that?

Thanks in advance

inside of the CustomAuthorizationFilter;

var authService = (IAuthService)context.HttpContext.RequestServices.GetService(typeof(IAuthService));

                    var userInfo = _unitOfWork.Persons.GetPersonWithEMail(userMailAddress.ToString());
                    if (userInfo != null)
                    {
                        authService.SetCurrentUser(userInfo.Data, userPermissionList.Data);
                        var model = authService.GetCurrentUser().PersonPermissions.FirstOrDefault(s => s.PermissionController == path);
                        if(model == null)
                        {
                            context.Result = new JsonResult(new UnAuthorizedResult<object>()
                            {
                                ErrorMessage = "You are not authorized for " + path,
                                HasError = true,
                                ErrorCode = "401"
                            });
                        }
                       
                    }

Here is the controller Constructor,

 public UserRolesController(IUnitOfWork _unitOfWork, IAuthService _authService)
    {
        unitOfWork = _unitOfWork;
        authService = _authService;
    }

Here is the endpoint located in the same controller;

 [HttpGet("get-user-permissons")]
    public async Task<ApiResult<PersonelDTO>> GetUserPermissions()
    {
        var result = new ApiResult<PersonelDTO>();
        try
        {
                
            result.Data = authService.GetCurrentUser();/*returns NULL*/
            return result;
        }
veli
  • 155
  • 10
  • Where did you define `get-user-permissons` roles? You could have look [`more example here in this thread`](https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core). You have to set [`Authorize attribute`](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/simple?view=aspnetcore-6.0#authorize-attribute-and-razor-pages) at this way which has been shown here. – Md Farid Uddin Kiron Apr 12 '22 at 07:49

0 Answers0