0

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.

2 Answers 2

0

remember to add code like:

app.UseMiddleware<JwtMiddleware>();

that is perfect

    public class JwtMiddleware
{
    private readonly RequestDelegate _next;
    private readonly AuthSettings _authSettings;

    public JwtMiddleware(RequestDelegate next, IOptions<AuthSettings> appSettings)
    {
        _next = next;
        _authSettings = appSettings.Value;
    }

    public async Task Invoke(HttpContext context, IUserService userService)
    {
        var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

        if (token != null)
            AttachUserToContext(context, userService, token);

        await _next(context);
    }

    private void AttachUserToContext(HttpContext context, IUserService userService, string token)
    {
        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            byte[] key = Encoding.ASCII.GetBytes(_authSettings.Secret);
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero
            }, out var validatedToken);

            var jwtToken = (JwtSecurityToken)validatedToken;
            var userId = int.Parse(jwtToken.Claims.First(c => c.Type == "id").Value);

            context.Items["User"] = userService.GetById(userId);
        }
        catch
        {
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.