Token Best Practices (2024)

Here are some basic considerations to keep in mind when using tokens:

  • Keep it secret. Keep it safe: The signing key should be treated like any other credential and revealed only to services that need it.

  • Do not add sensitive data to the payload: Tokens are signed to protect against manipulation and are easily decoded. Add the bare minimum number of claims to the payload for best performance and security.

  • Give tokens an expiration: Technically, once a token is signed, it is valid forever—unless the signing key is changed or expiration explicitly set. This could pose potential issues so have a strategy for expiring and/or revoking tokens.

  • Embrace HTTPS: Do not send tokens over non-HTTPS connections as those requests can be intercepted and tokens compromised.

  • Consider all of your authorization use cases: Adding a secondary token verification system that ensures tokens were generated from your server may be necessary to meet your requirements.

  • Store and reuse: Reduce unnecessary roundtrips that extend your application's attack surface, and optimize plan token limits (where applicable) by storing access tokens obtained from the authorization server. Rather than requesting a new token, use the stored token during future calls until it expires. How you store tokens will depend on the characteristics of your application: typical solutions include databases (for apps that need to perform API calls regardless of the presence of a session) and HTTP sessions (for apps that have an activity window limited to an interactive session). For an example of server-side storage and token reuse, see Token Storage.

Tokens vs. Cookies

Typically, single-page apps (such as React, Vue, and AngularJS + Node), native mobile apps (such as iOS and Android), and web APIs (written in Node, Ruby, ASP.NET, or a mix of those) benefit most from token-based authentication. Traditional, server-side web applications have traditionally used cookie-based authentication.

Token-based authentication is implemented by generating a token when the user authenticates and then setting that token in the Authorization header of each subsequent request to your API. You want that token to be something standard, like JSON web tokens since you will find libraries in most of the platforms and you don't want to do your own crypto.

With both approaches, you can get the same amount of information from the user. That's controlled by the scope parameter sent in the login request (either using the Lock, our JavaScript library or a plain link). The scope is a parameter of the .signin({scope: 'openid name email'}) method which ends up being part of the query string in the login request.

By default, we use scope=openid in token-based authentication to avoid having a huge token. You can control any standard OpenID Connect (OIDC) claims that you want to get in the token by adding them as scope values. For example, scope=openid name email family_name address phone_number. To learn more, see Standard Claims on openid.net.

You can mix token-based authentication with cookie-based authentication. Take into account that cookies will work just fine if the web app and the API are served from the same domain, so you might not need token based authentication. If you need to, we also return a JWT on the web app flow. Each of our SDKs will do it differently. If you want to call your APIs from JavaScript(instead of using the existing cookie), then you have to set the access tokens using Web Workers or JavaScript closures to handle token transmissions and storage. To learn more, read the Browser in-memory scenarios section of our Token Storage page.

You can only get a Refresh token if you are implementing the following flows:

  • Authorization Code Flow

  • Authorization Code Flow with Proof Key for Code Exchange (PKCE)

  • Resource Owner Password Flow

  • Device Authorization Flow

If you limit offline access to your API, a safeguard configured via the Allow Offline Access switch at Auth0 Dashboard > Applications > APIs > Settings, Auth0 will not return a Refresh Token for the API (even if you include the offline_access scope in your request).

Rules will run for the refresh token exchange. To execute special logic, you can look at the context.protocol property in your rule. If the value is oauth2-refresh-token, then the rule is running during the exchange.

When trying to get a refresh token, the audience parameter is not available on the Rules context object. If you receive an error when attempting to add the audience parameter, verify that you do not have it set on the token.

If you try to do a redirect with context.redirect, the authentication flow will return an error.

If you have added custom claims to your tokens using a rule, the custom claims will appear in new tokens issued when using a refresh token for as long as your rule is in place. Although new tokens do not automatically inherit custom claims, rules run during the refresh token flow, so the same code will be executed. This allows you to add or change custom claims in newly-issued tokens without forcing previously-authorized applications to obtain a new refresh token.

Refresh token limits

Auth0 limits the amount of active refresh tokens to 200 tokens per user per application. This limit only applies to active tokens. If the limit is reached and a new refresh token is created, the system revokes and deletes the oldest token for that user and application. Revoked tokens and expired tokens do not count against the limit.

Automated tests

Refresh tokens accumulate due to automated tests and are generally used for the test lifetime. To avoid a token stockpile subject to refresh token limits, you can use the Auth0 Management API to remove unnecessary refresh tokens.

  1. Create a user with Management API. You will use this user for testing.

  2. The response returns a user_id that you need to persist during tests to be used later.

  3. Once tests are complete, delete the user through Management API. When the test user is deleted, the associated artifacts are also removed, including refresh tokens.

For this use case, we don’t recommend using a static user ID. We do not recommended that you keep test users and artifacts, or cleaning the refresh tokens using the device credential endpoints as you could hit rate limits on the Management API. To learn more, read Management API Endpoint Rate Limits.

If you want to keep the test user for future testing:

  1. List the user’s refresh tokens using Management API's device credential endpoint. The endpoint will return a maximum of 1000 tokens without specific order regardless of accumulated tokens or the use of pagination.

  2. Delete those credentials using the DELETE method.

  3. If the user has more than 1k tokens, repeat listing and deleting tokens until no more tokens left for the user.

Configure Expiring Refresh Tokens

When users log into your application with Auth0, and when the offline_access is requested in the authorization request, a new refresh token is issued to the user. In the case users log out and in again with the same device, a new refresh token is issued. Depending on how your application stores and uses refresh tokens, the old refresh token from the first login might become obsolete, and your application will most likely use the new refresh tokens if both tokens are issued with the same audience. To learn more, read Token Storage.

To avoid accumulating obsolete refresh tokens, even though the refresh token limit removes the oldest token first, we recommend you configure refresh token expiration. Both rotating and non-rotating (or reusable) refresh tokens can be configured to expire with either idle or absolute expiry values. Both expiration values help remove tokens that are not in active use and avoid accumulating tokens for the user. To learn more, read Configure Refresh Token Expiration.

JWT validation

We strongly recommend that you use middleware or one of the existing open source third-party libraries to parse and validate JWTs. At JWT.io, you can find libraries for various platforms and languages, such as .NET, Python, Java, Ruby, Objective-C, Swift, and PHP.

Signing algorithms

The algorithm used to sign tokens issued for your application or API. A signature is part of a JWT and is used to verify that the sender of the token is who it says it is and to ensure that the message wasn't changed along the way. To learn more about JWTs, read JSON Web Tokens. To learn more about signatures, read JSON Web Token Structure.

You can select from the following signing algorithms:

  • RS256 (RSA Signature with SHA-256): An asymmetric algorithm, which means that there are two keys: one public key and one private key that must be kept secret. Auth0 has the private key used to generate the signature, and the consumer of the JWT retrieves a public key from the Metadata endpoints provided by Auth0 and uses it to validate the JWT signature.

  • HS256 (HMAC with SHA-256): A symmetric algorithm, which means that there is only one private key that must be kept secret, and it is shared between the two parties. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised. This private key (or secret) is created when you register your Application (Client Secret) or API (Signing Secret) and choose the HS256 signing algorithm.

The most secure practice, and our recommendation, is to use RS256 because:

  • With RS256, you are sure that only the holder of the private key (Auth0) can sign tokens, while anyone can check if the token is valid using the public key.

  • With RS256, you can request a token that is valid for multiple audiences.

  • With RS256, if the private key is compromised, you can implement key rotation without having to re-deploy your application or API with the new secret (which you would have to do if using HS256).

  • With HS256, if the secret key is compromised you would have to redeploy the API with the new secret.

Signing keys

It's good practice to assume that multiple signing keys could be present in your JWKS. This may seem unnecessary since the Auth0 JWKS endpoint typically contains a single signing key; however, multiple keys can be found in the JWKS when rotating signing certificates.

We recommend that you cache your signing keys to improve application performance and avoid running into rate limits, but you will want to make sure that if decoding a token fails, you invalidate the cache and retrieve new signing keys before trying only one more time.

Learn more

  • Tokens
  • Token Storage
Token Best Practices (2024)

FAQs

What is the best practice for storing tokens? ›



Storing tokens securely should be done on the backend (server-side) of your application, not on the frontend (client-side). A frontend application is more susceptible to potential security threats such as Cross-Site Scripting (XSS) attacks or unauthorized access if the client is compromised.

What is the best practice for refresh token expiration? ›

Best practice

Set the expiration time for refresh tokens in such a way that it is valid for a little longer period than the access tokens. For example, if you set 30 minutes for access token then set (at least) 24 hours for the refresh token.

What is the best way to store session tokens? ›

Browser in-memory scenarios

Auth0 recommends storing tokens in browser memory as the most secure option. Using Web Workers to handle the transmission and storage of tokens is the best way to protect the tokens, as Web Workers run in a separate global scope than the rest of the application.

What is the token method? ›

It enables users to verify their identity to websites, which then generates the unique encrypted authentication token. That token then provides users with access to protected pages and resources for a limited period of time without having to re-enter their username and password.

Where should I store my token? ›

We recommend storing tokens on the server, as this offers traditional web apps the maximum level of security. If this cannot be done, you should use encrypted session cookies so the client cannot read token values.

Is it good practice to store token in local storage? ›

XSS attack: storing JSON web tokens in LocalStorage makes them susceptible to a XSS attack. Lack of Encryption: LocalStorage does not provide built-in encryption, encrypted tokens make the stored data virtually inaccessible if an attacker gains access to the user's device.

What is the best way to store tokens in frontend? ›

There are three common options: local storage, session storage, and cookies. Each one has its pros and cons, but none of them is completely safe from attacks. Local storage and session storage are vulnerable to cross-site scripting (XSS) attacks, where malicious scripts can access and steal your tokens.

Should we store tokens in a database? ›

It is best to store the token in the 'users' table in the database. This is the most secure and efficient way to store the token. You can create a column in the 'users' table to store the token.

Where should I keep refresh token? ›

Store refresh tokens securely

For native applications connected to APIs, refresh tokens can be stored in long-term storage like relational and non-relational databases. Local storage and browser memory can be used to store refresh tokens for SPAs and browser-based applications.

What is a token strategy? ›

The token system is a strategy where the student receives a token after completing a specified academic task, or using an appropriate behavior.

What is token manipulation? ›

Access token manipulation is a technique often used to escalate privileges or permissions of a user. This attack type is listed under Privilege Escalation in the MITRE ATT&CK threat modelling framework.

What is token mechanism? ›

The token mechanism is similar to the token ring as a token needs to be in custody of a node for transmitting messages. Tokens are reclaimed, when messages either reach their destinations or are dropped. The proposed mechanism is useful for reducing the number of message drops in the network.

Should you store tokens in database? ›

The safest approach would be to maintain them in the database. However, the access tokens generated are short-lived (1h). If you use Custom UI extensions and basic scopes and want to have some stateless session, storing access tokens in secure cookies should be fine.

What is the best way to store access token and refresh token? ›

You can store the access token and refresh token in the server-side session. The application can use web sessions to communicate with the server. The token is then available for any requests originating from server-side code.

What is the best practice for JWT expiry time? ›

JWTs are self-contained, by-value tokens and it is very hard to revoke them, once issued and delivered to the recipient. Because of that, you should use as short an expiration time for your tokens as possible — minutes or hours at maximum. You should avoid giving your tokens expiration times in days or months.

Top Articles
CDs and DVDs - Torrance Recycles
'Bitcoin Is Going to Eat Gold': MicroStrategy’s Michael Saylor
Mountain Dew Bennington Pontoon
Phcs Medishare Provider Portal
Sam's Club Gas Price Hilliard
Displays settings on Mac
Costco in Hawthorne (14501 Hindry Ave)
83600 Block Of 11Th Street East Palmdale Ca
Hover Racer Drive Watchdocumentaries
REVIEW - Empire of Sin
How Many Cc's Is A 96 Cubic Inch Engine
Koop hier ‘verloren pakketten’, een nieuwe Italiaanse zaak en dit wil je ook even weten - indebuurt Utrecht
Gmail Psu
Chic Lash Boutique Highland Village
Bad Moms 123Movies
Sport-News heute – Schweiz & International | aktuell im Ticker
Abortion Bans Have Delayed Emergency Medical Care. In Georgia, Experts Say This Mother’s Death Was Preventable.
Inside the life of 17-year-old Charli D'Amelio, the most popular TikTok star in the world who now has her own TV show and clothing line
Transfer and Pay with Wells Fargo Online®
Vrachtwagens in Nederland kopen - gebruikt en nieuw - TrucksNL
Lawson Uhs
Moving Sales Craigslist
MLB power rankings: Red-hot Chicago Cubs power into September, NL wild-card race
Program Logistics and Property Manager - Baghdad, Iraq
Orange Pill 44 291
Spn 520211
Where to eat: the 50 best restaurants in Freiburg im Breisgau
Haunted Mansion Showtimes Near Epic Theatres Of West Volusia
Kirsten Hatfield Crime Junkie
Sound Of Freedom Showtimes Near Movie Tavern Brookfield Square
Great ATV Riding Tips for Beginners
Pacman Video Guatemala
Chelsea Hardie Leaked
Http://N14.Ultipro.com
Pnc Bank Routing Number Cincinnati
Petsmart Distribution Center Jobs
Plato's Closet Mansfield Ohio
Breckie Hill Fapello
Robot or human?
Collier Urgent Care Park Shore
ENDOCRINOLOGY-PSR in Lewes, DE for Beebe Healthcare
Htb Forums
Www Usps Com Passport Scheduler
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
888-822-3743
Is Ameriprise A Pyramid Scheme
Sound Of Freedom Showtimes Near Amc Mountainside 10
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
Oakley Rae (Social Media Star) – Bio, Net Worth, Career, Age, Height, And More
Keci News
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6261

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.