C
C#3mo ago
Yasu

Why is my JWT token not getting authorized and not getting entering the [Authorize] method?

C#
[HttpPost]
public IActionResult Login(LogInAndSignUp user)
{
var logUser = context.LogInAndSignUps.Where(x => x.Email == user.Email && x.Password == user.Password).FirstOrDefault();
if (logUser != null)
{
// Generate JWT token
var token = GenerateJwtToken(logUser);

// Set the token in a cookie
var cookieOptions = new CookieOptions
{
HttpOnly = true, // Prevents JavaScript from accessing the cookie
Expires = DateTime.Now.AddMinutes(30) // Set expiration time for the token
};
Response.Cookies.Append("UserToken", token, cookieOptions);

// Redirect to the dashboard
return RedirectToAction("Dashboard");
}
else
{
ViewBag.Message = "Login Failed";
}
return View();
}

[Authorize]
public IActionResult Dashboard()
{
Console.WriteLine("Dashboard action called.");
var userEmail = HttpContext.Session.GetString("UserSession");
//var userEmail = User.FindFirstValue(JwtRegisteredClaimNames.Sub); // Extract email from token
if (userEmail != null)
{
var user = context.LogInAndSignUps.Where(x => x.Email == userEmail).FirstOrDefault();
if (user != null)
{
return View(user);
}
}
return RedirectToAction("Login");
}
C#
[HttpPost]
public IActionResult Login(LogInAndSignUp user)
{
var logUser = context.LogInAndSignUps.Where(x => x.Email == user.Email && x.Password == user.Password).FirstOrDefault();
if (logUser != null)
{
// Generate JWT token
var token = GenerateJwtToken(logUser);

// Set the token in a cookie
var cookieOptions = new CookieOptions
{
HttpOnly = true, // Prevents JavaScript from accessing the cookie
Expires = DateTime.Now.AddMinutes(30) // Set expiration time for the token
};
Response.Cookies.Append("UserToken", token, cookieOptions);

// Redirect to the dashboard
return RedirectToAction("Dashboard");
}
else
{
ViewBag.Message = "Login Failed";
}
return View();
}

[Authorize]
public IActionResult Dashboard()
{
Console.WriteLine("Dashboard action called.");
var userEmail = HttpContext.Session.GetString("UserSession");
//var userEmail = User.FindFirstValue(JwtRegisteredClaimNames.Sub); // Extract email from token
if (userEmail != null)
{
var user = context.LogInAndSignUps.Where(x => x.Email == userEmail).FirstOrDefault();
if (user != null)
{
return View(user);
}
}
return RedirectToAction("Login");
}
1 Reply
Yasu
YasuOP3mo ago
C#
private string GenerateJwtToken(LogInAndSignUp user)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSettings:Key"]!)); // Use your static key
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
issuer: _config["JwtSettings:Issuer"],
audience: _config["JwtSettings:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30), // Set token expiration time
signingCredentials: creds);

// Debug output to check the token
Console.WriteLine($"Generated Token: {new JwtSecurityTokenHandler().WriteToken(token)}");


return new JwtSecurityTokenHandler().WriteToken(token);
}
C#
private string GenerateJwtToken(LogInAndSignUp user)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSettings:Key"]!)); // Use your static key
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
issuer: _config["JwtSettings:Issuer"],
audience: _config["JwtSettings:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30), // Set token expiration time
signingCredentials: creds);

// Debug output to check the token
Console.WriteLine($"Generated Token: {new JwtSecurityTokenHandler().WriteToken(token)}");


return new JwtSecurityTokenHandler().WriteToken(token);
}
this is the GenerateJwtToken method used in login method btw
Want results from more Discord servers?
Add your server