Common API Tasks🐈: Check if your access token has expired (2024)

Home

/

Common API Tasks

Inbar GazitSr. Manager, Developer Content

Summary

3 min read

See how to use the expires_in property of your Docusign access token to calculate when it expires.

Common API Tasks🐈: Check if your access token has expired (2)

Welcome to a wondrous new edition of the CAT🐈 (Common API Tasks) blog series. The CAT blogs provide all you need to complete small, specific, SDK-supported tasks using one of our APIs. You can find all articles in this series on the Docusign Developer Blog.

Today we’re going back to the basics: authentication. As we all know, you cannot make API calls to Docusign without obtaining an access token. That access token is required for any API call on any one of the Docusign APIs. However, it’s important to be aware that access tokens have a short lifespan. They expire quickly, which is why you never hardcode an access token into your code. You never rely on an access token that was obtained in the past. It may not work! So, how do you know if the access token you obtained is valid? More specifically, how do you know if it has already expired or not?

When you obtain an access token, the JSON that comes back when you make a request includes another property in addition to the token itself. It’s called expired_in and that is how long, in seconds, you have before the token expires. It’s important to note that, as the famous saying goes, time waits for no man (or woman) which means this value becomes obsolete within a second of obtaining the token. So the best way to handle this is to have the next line after you obtain the token (and this is true for both JWT Grant or Authorization Code Grant) perform a simple calculation that tells you when the token expires by adding the number of seconds to the value of Now() (each language has a similar method). That way you have the exact time when the token expires in your system, and when you use that token, you can have a simple check to see if this time has passed or not (again using the Now() function, method, or property). If the token has not yet expired, you can use it. If the token expires, you will have to obtain a new one.

One thing to consider is that this check and the API call you’ll make will take a few milliseconds, and to avoid a situation where the token had a few milliseconds left, you checked and the code says it has not expired, but by the time you made the call it did, it’s recommended that you give yourself an extra one second and not use a token that has less than one second before it expires—just in case.

OK, and now, here are the code snippets that do what I just described. I am not showing here how to obtain an access token. This has been documented exhaustively and discussed in detail on the Dev Center Authentication section. You can also use our Quickstart downloadable personalized code that helps you jumpstart your Docusign API integration by setting up the needed configuration and authentication code for you automatically.

C#

OAuth.OAuthToken tokenInfo;// Obtain the access token code not shown... DateTime tokenExpiresTime;tokenExpiresTime = DateTime.Now.AddSeconds(tokenInfo.expires_in ?? 0);tokenExpiresTime = tokenExpiresTime.AddSeconds(-1); // One second just in case// Your app’s code doing things ...if (DateTime.Now < tokenExpiresTime){ // Token is good - you can use it to make API calls}else{ // Token expired - obtain a new one}

Java

OAuthToken tokenInfo;// Obtain the access token code not shown... LocalDateTime tokenExpiresTime;tokenExpiresTime = LocalDateTime.now().plusSeconds(tokenInfo.expires_in);tokenExpiresTime = tokenExpiresTime.plusSeconds(-1); // One second just in case// Your app’s code doing things ...if (LocalDateTime.now() < tokenExpiresTime){ // Token is good - you can use it to make API calls}else{ // Token expired - obtain a new one}

Node.js

let tokenInfo;// Obtain the access token code not shown... let tokenExpiresTime = moment().add(tokenInfo.body.expires_in, 's');tokenExpiresTime = tokenExpiresTime.subtract(1, 's'); // One second just in case// Your app’s code doing things ...if (moment() < tokenExpiresTime){ // Token is good - you can use it to make API calls}else{ // Token expired - obtain a new one}

PHP

$token_info;# Obtain the access token code not shown... $token_expires_time = time()->add($token_info->getExpiresIn();$token_expires_time = $token_expires_time->add(-1); # One second just in case# Your app’s code doing things ...if (time() < $token_expires_time){ # Token is good - you can use it to make API calls}else{ # Token expired - obtain a new one}

Python

token_info# Obtain the access token code not shown... token_expires_time = datetime.now() + timedelta(seconds = token_info.expires_in)token_expires_time = token_expires_time + timedelta(seconds = -1); # One second just in case# Your app’s code doing things ...if datetime.now() < token_expires_time: # Token is good - you can use it to make API callselse: # Token expired - obtain a new one

Ruby

token_info# Obtain the access token code not shown... token_expires_time = Time.now() + token_info.expires_in.to_i.secondstoken_expires_time = token_expires_time - 1.seconds; # One second just in case# Your app’s code doing things ...if Time.now() < token_expires_time # Token is good - you can use it to make API callselse # Token expired - obtain a new oneend

That’s all, folks! I hope you found it useful. If you have any questions, comments, or suggestions for topics for future Common API Tasks posts, feel free to email me. Until next time…

Additional resources

Common API Tasks🐈: Check if your access token has expired (3)

Inbar Gazit

Sr. Manager, Developer Content

More posts from this author

Related posts

  • Common API Tasks

    Common API Tasks🐈: List all your Maestro workflows using the Maestro API
    Common API Tasks🐈: Check if your access token has expired (5)

    Inbar Gazit

  • Common API Tasks

    Common API Tasks🐈: Find a web form by name
    Common API Tasks🐈: Check if your access token has expired (7)

    Inbar Gazit

  • Common API Tasks

    Common API Tasks🐈: Apply an existing template if it matches your envelope's documents
    Common API Tasks🐈: Check if your access token has expired (9)

    Inbar Gazit

Common API Tasks

Common API Tasks🐈: List all your Maestro workflows using the Maestro API
Common API Tasks🐈: Check if your access token has expired (11)

Inbar Gazit

Common API Tasks

Common API Tasks🐈: Find a web form by name
Common API Tasks🐈: Check if your access token has expired (13)

Inbar Gazit

Common API Tasks

Common API Tasks🐈: Apply an existing template if it matches your envelope's documents
Common API Tasks🐈: Check if your access token has expired (15)

Inbar Gazit

Common API Tasks🐈: Check if your access token has expired (2024)

FAQs

How to know if an access token has expired? ›

More specifically, how do you know if it has already expired or not? When you obtain an access token, the JSON that comes back when you make a request includes another property in addition to the token itself. It's called expired_in and that is how long, in seconds, you have before the token expires.

How do I check my API token? ›

The easiest way to locate your API token for use in 3rd party integrations is as follows:
  1. Navigate to Settings > Integrations.
  2. Under Webhooks click on "Connect"
  3. The pop-up window for Webhooks opens. Your token will display in the API Token field.

What is API response for expired token? ›

If you attempt to use an expired token, you'll receive a "401 Unauthorized HTTP" response.

How do I fix an expired access token? ›

Once expired, you need to re-authenticate to obtain a new token. Doing this prevents the same token from being used for an extended period of time, thereby reducing the risk of misappropriation. You can also use refresh tokens to renew new access tokens.

How do I check my token validation? ›

You can validate your tokens locally by parsing the token, verifying the token signature, and validating the claims that are stored in the token. Parse the tokens. The JSON Web Token (JWT) is a standard way of securely passing information. It consists of three main parts: Header, Payload, and Signature.

How do I check my token expiry online? ›

To determine the expiration time of the current JWT token that was created for your Azure AD connector app, you can decode the token and check the value of the “exp” claim. There are various online JWT decoding tools available that you can use to decode the token, such as jwt.io or jwt-decode.com.

How to test API with access token? ›

This doc describes how to test user access tokens for your API connection, using Postman and Authorization code (with PKCE). You can use this process to request tokens for your own and third-party APIs, and to test custom scopes added to claims.

How does an API validate a token? ›

The mechanism to validate a token varies between applications, but for the most part, it comprises decoding the payload, parsing the properties, and performing further queries to validate credentials. This validation, in a standard API service, would occur before any request reaches an endpoint.

What is an API access token? ›

What is an Access Token? A credential that can be used by an application to access an API. Access Tokens can be either an opaque string or a JSON Web Token (JWT) . They inform the API that the bearer of the token has been authorized: to access a particular service or services.

How do you handle if token is expired? ›

In this article. When a token has expired or has been revoked, it can no longer be used to authenticate Git and API requests. It is not possible to restore an expired or revoked token, you or the application will need to create a new token.

Can API tokens expire? ›

API tokens are valid for 30 days. When a token has been inactive for more than 30 days, it is revoked and cannot be used again. Provide detailed steps to successfully implement the solution or workaround for the problem. Include step-by-step instructions whenever possible.

How do you refresh the access token API? ›

A refresh token is a special key that enables a client for an API or service to retrieve new access tokens without requiring the user to perform a complete login. In other words, an application can exchange a valid refresh token for a new access token.

How to check if refresh token expired? ›

Unfortunately, there is no option to find the expiration time for the refresh token, because it is depending on authorization server and the type of client application, and it is not communicated to the client. In the Microsoft identity platform, the default lifetime for refresh tokens is 90 days.

How do I renew my access token? ›

If your refresh token expires before you use it, you can regenerate a user access token and refresh token by sending users through the web application flow or device flow.

How do I fix invalid access token? ›

Common Mistakes
  1. The Account SID must be from your Live Credentials. Test Credentials are not supported in Access Tokens.
  2. Access Tokens are bound to the Account SID specified and cannot be shared across accounts or subaccounts.
  3. Access Token must be passed as a simple string, not a JSON object.

How do I know if my Salesforce access token is expired? ›

How to determine token expiration
  1. Use your access token until you receive a 401 HTTP status code, and only refresh it then.
  2. Use Salesforce's token introspection endpoint to determine when the token expires.
Jan 21, 2021

How long does an access token last? ›

Configure access token lifetime

Default value is 86,400 seconds (24 hours). Maximum value is 2,592,000 seconds (30 days).

How to check if a token is expired in Java? ›

For example, you can use the Java JWT (JSON Web Token) library to decode and verify the token, and then check its expiration time using the 'Expiration()' method. If the token has expired, you can redirect the user to a login page or generate a new token using the refresh token provided by the authentication server.

How do I know when to refresh my access token? ›

About refresh tokens

A user needs a new access token when they attempt to access a resource for the first time. The user also needs a new access token after the previously granted access token expires. A refresh token is a special token that is used to obtain more access tokens.

Top Articles
Top Crypto Influencers on Twitter: Your 2024 Follow List
Navigation System for Cars
Cintas Pay Bill
855-392-7812
Red Wing Care Guide | Fat Buddha Store
Https //Advanceautoparts.4Myrebate.com
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Chic Lash Boutique Highland Village
Ou Class Nav
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Sadie Proposal Ideas
Lowe's Garden Fence Roll
Robert Deshawn Swonger Net Worth
Finalize Teams Yahoo Fantasy Football
Diakimeko Leaks
Glover Park Community Garden
Wkow Weather Radar
Klsports Complex Belmont Photos
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Mta Bus Forums
Truvy Back Office Login
Miles City Montana Craigslist
Emuaid Max First Aid Ointment 2 Ounce Fake Review Analysis
Craigslist Scottsdale Arizona Cars
Ff14 Sage Stat Priority
Account Now Login In
The Rise of "t33n leaks": Understanding the Impact and Implications - The Digital Weekly
Boneyard Barbers
Average weekly earnings in Great Britain
Craigslist Central Il
Whas Golf Card
Chattanooga Booking Report
Craigslist In Myrtle Beach
Unity Webgl Player Drift Hunters
Ludvigsen Mortuary Fremont Nebraska
How are you feeling? Vocabulary & expressions to answer this common question!
Wlds Obits
How much does Painttool SAI costs?
Pink Runtz Strain, The Ultimate Guide
Yakini Q Sj Photos
Greatpeople.me Login Schedule
Rocket League Tracker: A useful tool for every player
Diario Las Americas Rentas Hialeah
Goosetown Communications Guilford Ct
Strange World Showtimes Near Century Federal Way
How to Get a Check Stub From Money Network
Mazda 3 Depreciation
Escape From Tarkov Supply Plans Therapist Quest Guide
Anthony Weary Obituary Erie Pa
How to Choose Where to Study Abroad
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5523

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.