In program.cs I have the following
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
var key = builder.Configuration["Jwt:Key"];
var keyBytes = Encoding.ASCII.GetBytes(key);
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
//define which claim requires to check
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
//,ValidateIssuerSigningKey = true,
////store the value in appsettings.json
//ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Issuer"]
};
});
...
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
I have an AuthenticationManager which I pass inject into my auth controller with the following method:
public string Authenticate(UserCredential user)
{
var key = _configuration.GetValue<string>("Jwt:Key");
var keyBytes = Encoding.UTF8.GetBytes(key);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.UserName),
new Claim("AdminID", user.AdminID.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(keyBytes),
SecurityAlgorithms.HmacSha256Signature),
Issuer = _configuration["Jwt:Issuer"],
Audience = _configuration["Jwt:Issuer"]
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
Finally in the AuthController I have the follwing code, user lookup omitted for brevity
var token = _jwtTokenManager.Authenticate(userCredential);
var cookieOptions = new CookieOptions();
cookieOptions.Expires = DateTimeOffset.UtcNow.AddDays(7);
cookieOptions.Domain = Request.Host.Value;
cookieOptions.Path = "/";
Response.Cookies.Append("jwt", token, cookieOptions);
return Ok(new { token = token });
The login page doesn’t actually do much, I’m sending the request off via ajax as follows:
<script type="text/javascript">
function btnLogin_click() {
var data = $("#loginForm").serialize();
$.ajax({
type: 'POST',
url: '/Auth/Authenticate',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function (result) {
alert('Successfully received Data ');
console.log(result);
},
error: function () {
alert('Failed to receive the Data');
console.log('Failed ');
}
})
}
</script>
I feel like I’m almost there… I’m running into a few issues:
I’m not receiving the cookie on the front end, when I try to navigate to a page I’m still getting the unauthorized page redirection (401)…
I feel like one step I need to take is to intercept requests on the front end in order to add the bearer token to any requests. Not sure if this is the way to go for .net 8 MVC, was definitely the way to go with angular.
End result I need the login process to provide authentication which can be used on both ajax requests as well as asp postbacks.
Kind of feeling like saving this token to a cookie using javascript methodology then intercepting requests to the server to append the bearer token may be the quick and dirty of it.
Unless somebody knows a way through this hell