swaggerauthorization

AuthorizationFilterContext can not get content


I am using Microsoft.AspNetCore.Authentication.JwtBearer Microsoft.AspNetCore.Authentication.OpenIdConnect

I have written code:

    [Authorize]
    [ApiVersion("1.0")]
    [ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class UsersController : ControllerBase
    {

    }

and the Authorize class likes this:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuthorizeAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var user = (User)context.HttpContext.Items["User"];
            if (user == null)
            {
                context.Result = new JsonResult(new { message = "Unauthorized" })
                { StatusCode = StatusCodes.Status401Unauthorized };
            }
        }
    }

I use swagger to send request like this:

curl -X 'GET' \
  'https://localhost:7056/api/v1.0/TourLists' \
  -H 'accept: text/plain' \
  -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYmYiOjE2OTUwMjk4OTQsImV4cCI6MTY5NTExNjI5NCwiaWF0IjoxNjk1MDI5ODk0fQ.z_ak0QjRt3XFVWArvQOgeYALFyGyoJIXlfL5msKfT-Y'

the error is that: var user = (User)context.HttpContext.Items["User"]; user is null.

//user is null
var user = (User)context.HttpContext.Items["User"];

I do not know why user is null.

Could anyone tell me how to fix it?tthank you

I hope the user class get content then I will access successfully.


Solution

  • the answer is that the Secret key is empty lead to an empty user class.