To give you some context:
I am trying to implement a Refresh/Access Token Authentication security to a simple Web API using ASPNET Core. Its going well so far.. It does work! Just not as expected.
To my understanding with this kind of setup the first thing that the app is supposed to check would be the JwtBearer within the Authentication. In this case the access token that will be send within the Header.
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JWT:Issuer"], // Ensure this matches your token's Issuer
ValidateAudience = false, // Assuming you're not validating audience, change if necessary
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"]!)),
ValidateLifetime = true, // Ensure lifetime validation is enabled
ClockSkew = TimeSpan.Zero // Optional: set this to zero to remove any time drift
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
// Check if the "auth_token" cookie is present and extract the token
if (context.Request.Cookies.ContainsKey("auth_token"))
{
context.Token = context.Request.Cookies["auth_token"];
}
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("Admin"));
options.AddPolicy("UserPolicy", policy => policy.RequireRole("User"));
});
Now the logic behind how the security within this app would work like is:
Every Request will be check for the header(Access Token) Which will have a short lifespan. Every few mins within the Client side (React) There will be a useEffect that will try to ReFetch said access token with the use of the next Endpoint:
[HttpGet]
public async Task<IActionResult> RefreshAccessToken()
{
// Access HttpContext from the ControllerBase class (no need to pass it as a parameter)
if (!HttpContext.Request.Cookies.ContainsKey("auth_token"))
return StatusCode(401, "Unauthorized");
var token = HttpContext.Request.Cookies["auth_token"];
// Decode the JWT to extract claims
var decodedClaims = _refreshTokenServices.DecodeJWT(token!);
if (decodedClaims == null)
return StatusCode(401, "Unauthorized");
// Retrieve the username claim from the decoded JWT
var usernameClaim = decodedClaims?.FindFirst(JwtRegisteredClaimNames.Sub);
// Check if the username claim exists
if (usernameClaim == null)
return StatusCode(401, "Unauthorized");
var username = usernameClaim.Value; // Use the 'Value' to get the actual username
// Find the user by username
var foundUser = await _userManager.FindByNameAsync(username);
// If user is not found, return unauthorized
if (foundUser == null)
return StatusCode(401, "Unauthorized");
// Create a new access token for the user
var accessToken = _accessTokenServices.CreateToken(foundUser);
// Return the new access token
return Ok(new { AccessToken = accessToken.Result });
}
Now I will also fill each API fetch call with a refreshAccessToken that will be called when the StatusCode would be 401. And it will just do nothing and return the Error if its 403. Meaning in case the Refetch fails or something all Api Calls from the frontend would be secure.
Now I have this side of the logic figured out. But thing is for some reason. This structure completely ignores the Bearer Token.
Doing some testing I noticed It only checks for the HttpOnly meaning the Refresh Token.
Since said Refresh token only has Username and Id Info. It is useless for the Role Based Access Control side of the Application. What I find weird is that if I completely delete the Refresh token meaning there is not a single HttpOnly Cookie only then will it bother to check for the Bearer Token.. Now I know this is probably due to a misuse or misconfiguration on my part but I legit have no idea how to proceed.
I am trying to use Attributes in order to handle my Protected routes like so:
[HttpGet]
[Route("admin-test")]
[Authorize(Roles = "Admin")]
public IActionResult Admin()
{
return Ok("Admin");
}
I have seen some guides and they say to do something like Request.Header and just straight up check the Header for the correct Token. But I really want to implement this functionality using Attributes as I believe they are cleaner looking but if the only way to implement Refresh/Access Authentication/Authorization is without it so be it.
Any guidance or advice into how to implement this functionality would be highly appreciated!
EDIT: In case necessary this is how I am sending back the Cookies:
[HttpPost]
[Route("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestDto loginModel)
{
if (!ModelState.IsValid) return BadRequest("Invalid Input Data");
var user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == loginModel.Username);
if (user == null) return BadRequest("Wrong Username or Password");
var passwordMatch = await _userManager.CheckPasswordAsync(user, loginModel.Password);
if (!passwordMatch) return BadRequest("Wrong Username or Password");
var refreshToken = _refreshToken.CreateToken(user);
Response.Cookies.Append("auth_token", refreshToken, new CookieOptions()
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = false, //For dev purposes
Expires = DateTime.Now.AddDays(7)
});
var accessToken = _accessToken.CreateToken(user);
return Ok(new { AcessToken = accessToken.Result });
}
}
And this is how the Tokens are being created:
public async Task<string> CreateToken(Usuario usuario)
{
var userRoles = await _userManager.GetRolesAsync(usuario);
var authClaims = new List<Claim>()
{
new Claim(JwtRegisteredClaimNames.Sub, usuario.UserName!),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
authClaims.AddRange(userRoles.Select(role => new Claim(ClaimTypes.Role, role)));
// Ensure the expiration time is UTC to avoid any timezone issues
var expiresAt = DateTime.UtcNow.AddMinutes(15);
var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(authClaims),
Expires = expiresAt, // Set expiration time
IssuedAt = DateTime.UtcNow, // Set the issue time
NotBefore = DateTime.UtcNow.AddSeconds(5), // Set the 'NotBefore' to a few seconds after issue time
SigningCredentials = creds,
Issuer = _config["JWT:Issuer"]
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
Only difference between the Access Token and the Refresh token is the duration and the Claims. Access Holds the userRoles whereas the Refresh Token only holds information about the user itself like the Username and its Id.
EDIT 2:
This is how I ended up switching up my Program.cs to handle the logic I wanted to achieve:
To have both Refresh/Access Token active in order to handle any protected Endpoint. I did this because of how I wanted to handle the Logout function.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var authorizationHeader = context.Request.Headers["Authorization"].ToString();
var httpOnlyCookie = context.Request.Cookies["auth_token"] ?? "";
if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(context.Request.Cookies["auth_token"]) && context.Request.Cookies.ContainsKey("auth_token"))
{
context.Token = authorizationHeader.Substring("Bearer ".Length).Trim();
}
else
{
context.Request.Headers["Authorization"] = "";
}
}
return Task.CompletedTask;
}
It checks both access and refresh token and only works if both Tokens have valid values.
Now I have this side of the logic figured out. But thing is for some reason. This structure completely ignores the Bearer Token.
You are correct. Please take a look at this https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/JwtBearer/src/JwtBearerHandler.cs#L74, it is the reason. I believe you can understand why it ignore Bearer Token in Authorization Header: the logic for loading token is skipped because you set token at OnMessageReceived
event.
Btw, I see your design is a little bit weird, why you set Refresh Token to auth_token
cookie, and OnMessageReceived
set token from auth_token
as refresh token to authenticate (instead of access token). Please clarify your purpose first.