Best practices for storing tokens (2024)

This topic discusses best practices and recommendations for securely storing CyberArk Identity OpenIDConnect (OIDC) tokens in your applications.

Token types

Three types of OIDC tokens are used with CyberArk Identity: access tokens, ID tokens, and optional refresh tokens.

Access and refresh tokens have two main use cases:

  • When a client application needs to call one or more CyberArk Identity APIs.

    In this use case, CyberArk Identity serves as both the OAuth 2.0 authorization server and resource server. The client acquires tokens from the authorization server, and then includes them in any API requests.

  • When a client application secures its APIs using CyberArk Identity tokens.

    In this use case, CyberArk Identity is the authorization server while the third-party API is the resource server.

For a more detailed description of each token, see:

  • Access tokens

  • ID tokens

  • Refresh tokens

Client types

Two types of clients are defined in the OAuth 2.0 specification: confidential and public clients. The distinction between clients stems from secret storage. Secrets allow registered clients to make authorized calls to an OAuth 2.0 authorization server.

  • Some clients, such as servers, can store these secrets without the risk of users exposing them. These are known as confidential clients.

  • Public clients, including native, mobile and browser-based applications, cannot securely store such secrets. These clients should use OAuth 2.0 flows that do not store registered secrets in the UI.

We recommend against storing IDtokens. If you must do so, ensure that you clear the tokens when users log out or delete accounts.

In contrast to traditional web apps, single-page applications (SPAs) require client-side API calls to process user interactions.

For SPAs that make APIcalls to one or more servers on a different domain, access tokens are necessary. You may also choose to use refresh tokens.

Recommended Flow: Authorization Code Flow with PKCE

SDK: CyberArk Identity JavaScript SDK

You should store and access tokens exclusively through the OS's secure storage mechanism. Use Keychain for iOSapps and KeyStore for Android apps.

Recommended Flow: Authorization Code Flow with PKCE

SDK: CyberArk Identity SDK for iOS / CyberArk Identity SDK for Android

For web applications rendered entirely server-side, there are no browser-based APIcalls needed to populate the user interface.

These types of apps are often known as traditional web apps. Traditional web apps still require access and refresh tokens. However, they do not need to be stored in the client because the back end performs the APIcalls.

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.

Recommended Flows: Authorization Code Flow (PKCE is recommended but optional)

Security risks

Keep two well-known vulnerabilities in mind when storing tokens: Cross Site Scripting (XSS) and Cross Site Request Forgery (CSRF) attacks.

  • XSSattacks enable attackers to inject malicious JavaScript into a browser so that important information, such as tokens, can be stolen.

  • CSRF attacks enable attackers to cause an authenticated user's browser to issue requests that modify the application state.

Traditional web app / SPAoptions

You can use the following storage options in both traditional web apps and single-page applications (SPAs):

  • Cookies

  • Local/session storage

Cookies

Cookies are one of the most established and time-tested methods of storing user information. However, you should take care to mitigate both XSSand CSRF attacks.

Advantages

  • Sent automatically with every request, enabling simple implementation for development teams

  • Persist across page reloads and browser restarts

Disadvantages

Cookies are vulnerable to both XSSand CSRFattacks. However, you can prevent these attacks in several ways:

  • Use httpOnly cookies to ensure that only the server can access cookie contents. This prevents XSSattacks from hijacking tokens stored in cookies.

  • Use an anti-CSRF protection mechanism, such as an X-CSRF-Token HTTPheader containing the cookie's value. Most web app frameworks provide built-in support for CSRFtoken verification.

  • In combination with CSRFtokens, set the SameSite attribute of cookies to either Lax or Strict to limit their inclusion in cross-site requests.

  • If your application uses cross-origin resource sharing (CORS)to allow cross-domain requests, ensure that request headers are properly set to further prevent CSRF attacks.

Local/session storage

Local storage enables you to save key-value pairs in a reserved section of browser memory. This section of memory follows a same-origin policy, preventing other domains from accessing its contents.

Your application's JavaScript can use the window.sessionStorage property to access it.

Differences between local and session storage

Local and session storage implement the same Storage JavaScript interface. However, keep in mind the following differences:

  • Local storage persists until a user clears their browser data, while session storage persists until a user closes their tab or window.

  • Local storage can be accessed across windows or tabs. Session storage is limited to a particular window or tab.

Advantages

  • Both storage options are immune to CSRF attacks.

Disadvantages

  • Local and session storage are vulnerable to XSS attacks. However, you can prevent this in two ways:

    • Implement refresh token rotation, which requires a new refresh token to be used each time an access token is requested.

    • Shorten the lifespan of refresh tokens to limit the potential impact of token theft.

  • Tokens stored in localStorage or sessionStorage must be explicitly included with requests using JavaScript.

SPA-onlyoptions

You can use the following storage options in SPAs:

  • Backend for frontend (BFF)

  • JavaScript Memory

  • Workers

Backend for frontend (BFF)

With SPAs, it is recommended to use the backend for frontend (BFF) pattern.

Other storage options expose SPAs to vulnerabilities, and though mitigations exist, they do not completely eliminate the threat of token theft.

With BFFs, you can offload token storage entirely to a backend client. This client can securely acquire and store tokens in order to proxy API requests on behalf of the user.

Best practices for storing tokens (1)

The following flow describes the role of the BFF:

  1. The user accesses an SPA in their browser.

  2. The user clicks a login button, causing the SPA to redirect to an endpoint on the BFF, such as /bff/login.

  3. The BFF initiates the standard OpenIDConnect (OIDC) authentication flow.

  4. After the user authenticates with the OIDC provider, the access, ID, and refresh tokens are stored in the BFF.

  5. The backend issues a first-party cookie to the SPA.It is configured as SameSite: 'Strict', httpOnly, and Secure.

    In effect, this cookie creates a sandbox between the SPA and backend for the duration of the user's session.

  6. To issue a request to a protected API, the SPAcalls the BFF with the desired endpoint and payload.

  7. The BFF appends the user's access token and proxies the request to the appropriate API.

  8. The APIresponse is forwarded to the SPA.

Advantages

  • Never stores the token in the browser; thus, eliminating the risk of client-side token theft

  • Widely considered the best practice for modern SPAs

Disadvantages

  • Requires additional infrastructure to host the BFF, which can increase cost and complexity

JavaScript memory

Advantages

JavaScript memory is accessible only by your web app's JavaScript, eliminating the possibility of XSSand CSRFattacks.

Disadvantages

Data stored in memory does not persist across page refreshes, so special care must be taken to ensure that users are not logged out. You can, however, solve this by storing refresh tokens in httpOnly cookies. The application can then use them to request new access tokens when the page is refreshed.

Workers

Workers allow you to run JavaScript code in the background without sharing any memory. This is useful for ensuring that sensitive information, such as tokens, cannot be accessed.

Advantages

Workers are inaccessible to other JavaScript, making them resistant to XSSand CSRFattacks.

Disadvantages

Workers are not supported by some older browsers, though this is becoming less of an issue.

Best practices for storing tokens (2024)

FAQs

What is the best way to store tokens? ›

Applications can use dedicated APIs, such as the Web Storage API or IndexedDB, to store tokens. Applications can also simply keep the token in memory or put them in cookies. Some storage mechanisms are persistent, and others are wiped after some period of time or when the page is closed or refreshed.

What is the best practice for storing refresh tokens? ›

User tokens include both refresh tokens and access tokens used by your application. Store tokens securely at rest and never transmit them in plain text. Use a secure storage system appropriate for your platform, such as Keystore on Android, Keychain Services on iOS and macOS, or Credential Locker on Windows.

Where is the best place to store session tokens? ›

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 a good practice to store token in LocalStorage? ›

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 safest way to store Altcoins? ›

A cold storage wallet is a type of wallet not connected to the internet. With these types of wallets, your crypto is safe from hackers, so these are ideal for storing large amounts of cryptocurrency.

What is the best way to store coins? ›

For high-value coins, use hard plastic holders. Professional coin grading services use sealed holders called slabs to protect authenticated and graded coins. Use acid-free cardboard and plastic holders free from polyvinyl chloride (PVC). Acid and PVC can ruin a coin's surface.

Is it safe to store refresh token? ›

Store refresh tokens securely

However, local storage does come with some downfalls, including opening yourself up for cross-site scripting attacks. To ensure a higher level of security, storing tokens in server-side storage allows you to encrypt data at rest.

How do you keep tokens safe? ›

Token Best Practices
  1. Keep it secret. ...
  2. Do not add sensitive data to the payload: Tokens are signed to protect against manipulation and are easily decoded. ...
  3. Give tokens an expiration: Technically, once a token is signed, it is valid forever—unless the signing key is changed or expiration explicitly set.

How to 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. When a user logs in, you can generate a token and store it in the 'users' table.

Is it safe to store token in session? ›

These can be stored server-side or in a session cookie. The cookie needs to be encrypted and have a maximum size of 4 KB. If the data to be stored is large, storing tokens in the session cookie is not a viable option.

Where do we store tokens in front end? ›

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.

How to store a JWT token securely? ›

To keep them secure, you should always store JWTs inside an HttpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading and writing) from JavaScript running in the browser.

What is the best way to store access 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.

How do I securely store API tokens? ›

Here are the essential steps to mitigate the risks of secret API keys exposure:
  1. Centralize API keys and tokens management: Centralizing token management enables secure storage, access, and rotation. ...
  2. Rotate API keys and tokens Regularly: Regularly rotating tokens mitigates the risk in case of compromise.
Mar 1, 2024

Why is localStorage not secure? ›

Data stored in localStorage is easily accessible through browser developer tools, making it vulnerable to cross-site scripting (XSS) attacks. Malicious scripts injected into a website can easily access and manipulate data stored in localStorage , compromising sensitive user information.

What is the safest way to store ERC20 tokens? ›

ERC20 tokens can also be stored in hardware wallets, keeping the funds and private keys away from the internet. Trezor and Ledger and popular options here. Both allow users to add custom ERC20 tokens, so all Ethereum-based cryptocurrencies are supported.

How do I protect my tokens? ›

Token Best Practices
  1. Keep it secret. ...
  2. Do not add sensitive data to the payload: Tokens are signed to protect against manipulation and are easily decoded. ...
  3. Give tokens an expiration: Technically, once a token is signed, it is valid forever—unless the signing key is changed or expiration explicitly set.

Where is the best place to store refresh tokens? ›

To ensure a higher level of security, storing tokens in server-side storage allows you to encrypt data at rest.

Is it safe to store tokens in cookies? ›

Stolen access tokens can result in significant damage, and XSS remains a primary concern for web applications. Therefore, avoid storing access tokens in places where they are accessible to client code. Instead, store access tokens in cookies.

Top Articles
How to Self-Publish a Book in 2024: Your Guide to Success
Lighthouse Park hike near West Vancouver | Vancouver Trails
Knoxville Tennessee White Pages
Is Sam's Club Plus worth it? What to know about the premium warehouse membership before you sign up
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Wizard Build Season 28
Readyset Ochsner.org
Apex Rank Leaderboard
Elden Ring Dex/Int Build
Atrium Shift Select
Skip The Games Norfolk Virginia
Oppenheimer & Co. Inc. Buys Shares of 798,472 AST SpaceMobile, Inc. (NASDAQ:ASTS)
Elizabethtown Mesothelioma Legal Question
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Sony E 18-200mm F3.5-6.3 OSS LE Review
Gino Jennings Live Stream Today
Munich residents spend the most online for food
Tamilrockers Movies 2023 Download
Katherine Croan Ewald
Diamond Piers Menards
The Ultimate Style Guide To Casual Dress Code For Women
Site : Storagealamogordo.com Easy Call
Is Windbound Multiplayer
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Integer Division Matlab
Sandals Travel Agent Login
Horn Rank
Ltg Speech Copy Paste
Random Bibleizer
Craigslist Fort Smith Ar Personals
The Clapping Song Lyrics by Belle Stars
Poe T4 Aisling
R/Sandiego
Kempsville Recreation Center Pool Schedule
Rogold Extension
Beaver Saddle Ark
Log in or sign up to view
A Man Called Otto Showtimes Near Amc Muncie 12
Powerspec G512
Saybyebugs At Walmart
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Miami Vice turns 40: A look back at the iconic series
Love Words Starting with P (With Definition)
Tlc Africa Deaths 2021
Youravon Com Mi Cuenta
Nope 123Movies Full
Kushfly Promo Code
Diario Las Americas Rentas Hialeah
Game Akin To Bingo Nyt
Marion City Wide Garage Sale 2023
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 6041

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.