Yasu
Yasu
CC#
Created by Yasu on 10/18/2024 in #help
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");
}
2 replies
CC#
Created by Yasu on 10/9/2024 in #help
✅ can somebody help me learn about smtp so i can make a email message sender please
i am a beginner
6 replies