.NET 6.0 - JWT Authentication with Refresh Tokens Tutorial with Example API
Documentation at https://jasonwatmore.com/post/2022/01/24/net-6-jwt-authentication-with-refresh-tokens-tutorial-with-example-api
.NET 6.0 - JWT Authentication with Refresh Tokens Tutorial with Example API
License: MIT License
.NET 6.0 - JWT Authentication with Refresh Tokens Tutorial with Example API
Documentation at https://jasonwatmore.com/post/2022/01/24/net-6-jwt-authentication-with-refresh-tokens-tutorial-with-example-api
Thanks for the great explanation on JWT. This sample project/blog post is by far the best explanation of the subject. Thanks for not making a "To-Do" List. I'm implementing my solution based on your example (makes for great documentation).
Now to the matter at hand: I discovered that the refresh token string value is getting the last two characters lopped off when it's saved within a cookie.
private void SetRefreshTokenCookie(string token)
{
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.UtcNow.AddDays(7)
};
Response.Cookies.Append("refreshToken", token, cookieOptions);
}
In Postman we see this in the cookie:
but, all of the refresh tokens seem to have == appended at the end of the string, like
Do you have an explanation why Response.Cookies.Append() drops ==?
Thanks,
The RefreshToken entity does not have a reference to the User entity in order to complete the User.RefreshTokens join.
Is the assumption that EntityFramework will create the join table automatically? If so, perhaps a mapping reference in the DbContext would be appropriate?
// token is a cryptographically strong random sequence of values
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
// ensure token is unique by checking against db
var tokenIsUnique = !_context.Users.Any(u => u.RefreshTokens.Any(t => t.Token == token));
Would it be faster to check a token existence unrelated to the Users table? Like _context.RefreshTokens.Any(t => t.Token == token)
Very nice and neat example, thanks!
The only thing I want to notice is that normally refresh happens every hour (in this example 15 minutes). There's no need to generate a new token on each refresh as there will be just too many of them.
Maybe better to update existing token with some fields like Updated
and UpdatedByIp
? Initially set together with Created
and CreatedByIp
. Because if the request is valid it is still ok to reuse the same record.
UserService.GetUserByRefreshToken(string token) returns a null list for the user's refresh tokens. Code is missing an Include in order to pick up the child table data:
private async Task<User> GetUserByRefreshToken(string token)
{
var user = await _context.Users
**.Include(p => p.RefreshTokens)**
.SingleOrDefaultAsync(u => u.RefreshTokens.Any(t => t.Token == token)) ??
throw new AppException("Invalid token");
return user;
}
At the moment the API can only be used to test authentication for an existing hardcoded user. Having an extra endpoint to enable registration of new users will make this API a more complete JWT testbed for future projects.
Hi,
why are you using AllowAnonymous for the /users/refresh-token ?
Shouldn't updating a token happen in an already authenticated session? and in theory, I should only be able to update the token relating to my session.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.