I have been trying to get JWT Authentication working and it is not entirely clear how this needs to be done, and what the best ways are to do this in ASP.NET Core 3.1.
I was using Cookie based authentication which I assume is tied to the session id, which is tied to the running server instance. If I want to use multiple servers with different IP addresses and ports, I assume that cookies would no longer work and therefor require something else that can be validated across systems.
I have been following various web examples but it is not clear what to do beyond the point where I have a JWT Token once the user has been "Authenticated" - Logged In. Once users are logged in they can access any part of the system via: html links (the menu).
How do I pass the tokens around with all subsequent requests?
Do I redirect the user to a Welcome page after the user has been authenticated and store the token in the browser sessionStore or localStorage or Cookie? What is the best way to deal with this.
options.success = function (obj) {
sessionStorage.setItem("token", obj.token);
sessionStorage.setItem("userName",$("#userName").val());
}
HTTP HEADERS
Would the Authorization HTTP Header variable work and would this be sent around in all subsequent requests by the browser, acting as the HTTP client. How long does this HTTP header last, is it lost once the TCP socket is closed? How do I set this HTTP Header Variable in ASP.NET Core 3.1? Would the server then use this Header to validate the token, and also pass it on again for use in subsequent requests?
Currently I have this, which returns the token in the body once the user is authenticated:
var claims = await GetClaims(user);
var token = GenerateSecurityToken(claims);
return Ok(new { Token = token })
AJAX CALLS
I have several forms and several AJAX calls, how do implement this as a manual approach seems rather tedious.
Is there a way to get the JWT token from a hidden form variable similar to the AntiForgery token
@Html.AntiForgeryToken()as used in all my Ajax calls?
jQuery using the hidden form variable:
request = $.ajax({
async: true,
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
WHAT DO I ADD FOR JWT ?
data: JSON.stringify(data)
}).done(function() {
completion();
}).fail(function() {
// fail
});
HTML FORMS
I have Razor Pages and have some forms which then POST back to the controllers. How do I include the token?
CONTROLLERS
Is there anything else that needs to be performed when using JWT besides what I have in my Startup.cs? I know I need to deal with Token refreshes but I will leave for a seperate question.
LINKS FROM THE MENU - HTTP GET
I could manipulated the menu / links presented to the user, by adding the token to the end of the URL, but how should this be done?