C
C#2y ago
M B V R K

✅ 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);
}
}
[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);
}
}
7 Replies
M B V R K
M B V R KOP2y ago
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
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. I hope please if someone has any solution, since I'm still a noob in using JWT @AspNetCore @Web And sorry for ping guys
Nox
Nox2y ago
Don't be sorry that's what these roles are for, anyone who signs up for them wants to be pinged. Are your jwt auth options correctin Startup.cs?
M B V R K
M B V R KOP2y ago
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"))
};
});
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
Nox2y ago
Should the two SymmetricSecurityKeys be the same?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
M B V R K
M B V R KOP2y ago
waaaaaaaaaahhhhhh notice the different keys
Want results from more Discord servers?
Add your server