Hello all,
I currently have 2 separate projects, I have an API for the backend with CRUD and login functionality, I also set up Json Web Tokens on the backend for validation purposes.
I have a front end MVC project which I am using for my UI. On this front end I have my login page where a user logins in and the API sends back a JWT token.
private string GenerateToken(string user)
{
var secretKey = configuration.GetValue<string>("Tokens:Key");
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.UniqueName, user)
};
var jsonToken = new JwtSecurityToken(
signingCredentials: signingCredentials,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(5),
audience: this.configuration.GetValue<String>("Tokens:Audience"),
issuer: this.configuration.GetValue<String>("Tokens:Issuer")
);
return new JwtSecurityTokenHandler().WriteToken(jsonToken);
}
[AllowAnonymous]
[HttpPost("Authenticate")]
public async Task<IActionResult> Authenticate(LoginModel loginModel)
{
if (!string.IsNullOrWhiteSpace(loginModel.Username) && !string.IsNullOrWhiteSpace(loginModel.Password))
{
var result = await signInManager.PasswordSignInAsync(loginModel.Username, loginModel.Password, false, false);
if (result.Succeeded)
{
return Ok(GenerateToken(loginModel.Username));
}
return BadRequest("Login Fail");
}
return BadRequest();
}
[HttpPost]
public async Task<IActionResult> Login(LoginModel loginModel)
{
if (ModelState.IsValid)
{
var model = JsonConvert.SerializeObject(loginModel);
var client = apiClient.CreateClient();
HttpRequestMessage httpRequest = new HttpRequestMessage
{
Content = new StringContent(model, Encoding.UTF8, "application/json"),
RequestUri = new Uri($"https://localhost:5001/api/Account/Authenticate"),
Method = new HttpMethod("Post")
};
var response = await client.SendAsync(httpRequest);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Success","Home",null);
}
}
return View("Failure");
}
What I have tried:
Once I get this token I want the user to be able to access a secure page that only works with a valid login. I put [Authorize] on this new page, How do I do this in this circumstance? Do I have to add my same JWT properties to the front end and validate it there? Or do I create a validate method in the API and if successful then allow the user to go to the page. But with this way [Authorize] on front end wouldn’t work… I could add my JWT to a cookie on the front end but I don’t understand how to validate it on front end. The project wouldn’t have to talk back to my API to access the user portal page. Here is my code for my API and the front end. Both are C# projects.