I want users to redirect to 2 different views after logging in depending on the role from the token:
- Customers: after logging in, the project will use: Views/Home/…cshtml, site.js, site.css, HomeController.cs
- Admins: after logging in, the project will use: Views/Admin/…cshtml, admin-dashboard.js, admin-dashboard.css, AdminController.cs (use [Authorize(Roles = “Admin”)])
Views’ structure
This is how I create token:
public IActionResult Login([FromBody] LoginModel model)
{
string role = "Customer";
if (model.Username == "administrator" && BCrypt.Net.BCrypt.Verify("adminpassword", customer.CustomerPassword))
{
role = "Admin";
}
var token = GenerateJwtToken(customer.CustomerUsername, role);
return Ok(new { token = token, role = role });
}
private string GenerateJwtToken(string username, string role)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, role)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
When fulfill the login form, it will save the token into the localStorage:
document.getElementById("loginForm").addEventListener("submit", async function (e) {
e.preventDefault();
const username = document.getElementById("signin-email").value;
const password = document.getElementById("signin-password").value;
try {
const response = await fetch('/api/login', {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
});
if (!response.ok) {
if (response.status === 401) {
alert("Tên đăng nhập hoặc mật khẩu không đúng.");
} else {
alert("Đăng nhập không thành công. Mã lỗi: " + response.status);
}
return;
}
const data = await response.json();
const token = data.token;
const role = data.role;
localStorage.setItem("jwt_token", token);
if (role === "Admin") {
window.location.href = "/Admin/Dashboard";
} else {
window.location.href = "/Home/Homepage";
}
} catch (error) {
console.error("Error during login:", error);
alert("Lỗi xảy ra trong quá trình đăng nhập. Vui lòng thử lại.");
}
});
But after successfully logging in as admin, it moves to /Admin/Dashboard and reset the localStorage => there is no token to get the role and the server response with the error 401.
Help me fix this and maybe give me the other way to redirect than using window.location.href.
3