C#
C#

help

Root Question Message

MBARK
MBARK1/13/2023
✅ Why a valid JWT token not able to be accepted in an Authorized Action in ASP.NET Core 7

Hi friends I have the following controller:
[ApiController]
[Route("api/[controller]")]
public class StudentController : ControllerBase
{
    readonly AppDbContext _dbContext;
    readonly UserManager<IdentityUser> _userManager;
    readonly SignInManager<IdentityUser> _signInManager;

    public StudentController(AppDbContext context, UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
    {
        _dbContext = context;
        _userManager = userManager;
        _signInManager = signInManager;
    }

    [HttpPost]
    public async Task<IActionResult> Login([FromBody] LoginModel model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);
        if (!result.Succeeded)
        {
            return BadRequest();
        }

        var user = await _userManager.FindByNameAsync(model.UserName);
        var claims = new[]
        {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var token = new JwtSecurityToken(
            issuer: "https://localhost:7183",
            audience: "https://localhost:7183",
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(30),
            signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345")), SecurityAlgorithms.HmacSha256)
        );

        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token),
            expiration = DateTime.Now.AddMinutes(30),
            userName = user.UserName
        });
    }

    [Authorize]
    [HttpGet("students")]
    public IActionResult GetStudents()
    {
        var students = _dbContext.Students.ToList();
        return Ok(students);
    }
}
MBARK
MBARK1/13/2023
Idk why after getting a valid JWT and use it to get the Students I get 404 Not Found error,
The HTTP GETrequest I use :
GET https://localhost:7128/api/Student/students
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtYmFya3RpZXN0b0BvdXRsb29rLmNvbSIsImp0aSI6ImJiNDkwYTI5LWQ4MmMtNDQ5MC05NjcxLTY0MTkwMjE0YTg4YSIsImV4cCI6MTY3MzYyMzM1MCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NzEyOCIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcxMjgifQ.6QdQ0g3Ui2vRpvRUgBx7bnwW_Ckfruwzr-bvRfqh0EA

But when I remove the Authorize attribute I get the students list.
MBARK
MBARK1/13/2023
I hope please if someone has any solution, since I'm still a noob in using JWT
MBARK
MBARK1/13/2023
&566134678374055942 &566134721457946637
And sorry for ping guys
Nox
Nox1/13/2023
Don't be sorry that's what these roles are for, anyone who signs up for them wants to be pinged.
Nox
Nox1/13/2023
Are your jwt auth options correctin Startup.cs?
MBARK
MBARK1/13/2023
Yes I think, and the following is the registration :
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddIdentity<AppUser, IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "https://localhost:7128",
                ValidAudience = "https://localhost:7128",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yoursecretkey@123"))
            };
        });
Nox
Nox1/13/2023
Should the two SymmetricSecurityKeys be the same?
Thaumanovic
Thaumanovic1/13/2023
Yes
MBARK
MBARK1/13/2023
Yes
MBARK
MBARK1/13/2023
Omfg
MBARK
MBARK1/13/2023
Daaaaaaamn
MBARK
MBARK1/13/2023
:waaaaaaaaaahhhhhh:
MBARK
MBARK1/13/2023
Didn't notice the different keys
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy