I want to authenticate users with JWT tokens in Asp.Net Core Web App (not WebAPI). How can I store JWT token, post it in each Http request's header and how to read stored info from cookie in controller action?
Here is my Login method in Auth controller:
[HttpPost]
[Route("LoginStudent")]
public async Task<IActionResult> PostLoginStudent(StudentLoginDto loginDto)
{
if (!ModelState.IsValid)
{
return RedirectToAction(
actionName: "GetLoginStudent",
routeValues: new { error = "Invalid login credentials." }
);
}
// Result is instance of a class which contains
// - content (StudentReturnDto) of response (from Repository),
// - message (from Repository),
// - bool IsSucces indicates whether operation is succes.
var result = await _repo.LoginStudent(loginDto);
if (result.IsSuccess)
{
// User must be Authorized to acces this Action method.
return RedirectToAction("GetProfile");
}
// If it fails return back to login page.
return RedirectToAction(
"GetLoginStudent",
routeValues: new { error = result.Message }
);
}
[HttpGet]
[Authorize]
public IActionResult GetProfile()
{
// Reading user id from token
return View();
}
In startup class I configured authentication like this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidateAudience = true,
ValidIssuer = _config["Jwt:Issuer"],
ValidAudience = _config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_config["Jwt:Key"])
)
};
});