Get Refresh Tokens (2024)

To get a refresh token, you must include the offline_access scope when you initiate an authentication request through the /authorize endpoint. Be sure to initiate Offline Access in your API. For more information, read API Settings.

For example, if you are using the Authorization Code Flow, the authentication request would look like the following:

https://{yourDomain}/authorize? audience={API_AUDIENCE}& scope=offline_access& response_type=code& client_id={yourClientId}& redirect_uri={https://yourApp/callback}& state={OPAQUE_VALUE}

Was this helpful?

/

The refresh token is stored in session. Then, when a session needs to be refreshed (for example, a preconfigured timeframe has passed or the user tries to perform a sensitive operation), the app uses the refresh token on the backend to obtain a new ID token, using the /oauth/token endpoint with grant_type=refresh_token.

Once the user authenticates successfully, the application will be redirected to the redirect_uri, with a code as part of the URL: {https://yourApp/callback}?code=BPPLN3Z4qCTvSNOy. You can exchange this code with an access token using the /oauth/token endpoint.

  • cURL
  • C#
  • Go
  • Java
  • Node.JS
  • Obj-C
  • ...
    • PHP
    • Python
    • Ruby
    • Swift
curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code={yourAuthorizationCode}' \ --data 'redirect_uri={https://yourApp/callback}'

Was this helpful?

/

var client = new RestClient("https://{yourDomain}/oauth/token");var request = new RestRequest(Method.POST);request.AddHeader("content-type", "application/x-www-form-urlencoded");request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody);IRestResponse response = client.Execute(request);

Was this helpful?

/

package mainimport ("fmt""strings""net/http""io/ioutil")func main() {url := "https://{yourDomain}/oauth/token"payload := strings.NewReader("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}")req, _ := http.NewRequest("POST", url, payload)req.Header.Add("content-type", "application/x-www-form-urlencoded")res, _ := http.DefaultClient.Do(req)defer res.Body.Close()body, _ := ioutil.ReadAll(res.Body)fmt.Println(res)fmt.Println(string(body))}

Was this helpful?

/

HttpResponse<String> response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") .asString();

Was this helpful?

/

var axios = require("axios").default;var options = { method: 'POST', url: 'https://{yourDomain}/oauth/token', headers: {'content-type': 'application/x-www-form-urlencoded'}, data: new URLSearchParams({ grant_type: 'authorization_code', client_id: '{yourClientId}', client_secret: '{yourClientSecret}', code: '{yourAuthorizationCode}', redirect_uri: '{https://yourApp/callback}' })};axios.request(options).then(function (response) { console.log(response.data);}).catch(function (error) { console.error(error);});

Was this helpful?

/

#import <Foundation/Foundation.h>NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" };NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=authorization_code" dataUsingEncoding:NSUTF8StringEncoding]];[postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]];[postData appendData:[@"&client_secret={yourClientSecret}" dataUsingEncoding:NSUTF8StringEncoding]];[postData appendData:[@"&code={yourAuthorizationCode}" dataUsingEncoding:NSUTF8StringEncoding]];[postData appendData:[@"&redirect_uri={https://yourApp/callback}" dataUsingEncoding:NSUTF8StringEncoding]];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/oauth/token"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"POST"];[request setAllHTTPHeaderFields:headers];[request setHTTPBody:postData];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];

Was this helpful?

/

$curl = curl_init();curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", CURLOPT_HTTPHEADER => [ "content-type: application/x-www-form-urlencoded" ],]);$response = curl_exec($curl);$err = curl_error($curl);curl_close($curl);if ($err) { echo "cURL Error #:" . $err;} else { echo $response;}

Was this helpful?

/

import http.clientconn = http.client.HTTPSConnection("")payload = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}"headers = { 'content-type': "application/x-www-form-urlencoded" }conn.request("POST", "/{yourDomain}/oauth/token", payload, headers)res = conn.getresponse()data = res.read()print(data.decode("utf-8"))

Was this helpful?

/

require 'uri'require 'net/http'require 'openssl'url = URI("https://{yourDomain}/oauth/token")http = Net::HTTP.new(url.host, url.port)http.use_ssl = truehttp.verify_mode = OpenSSL::SSL::VERIFY_NONErequest = Net::HTTP::Post.new(url)request["content-type"] = 'application/x-www-form-urlencoded'request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}"response = http.request(request)puts response.read_body

Was this helpful?

/

import Foundationlet headers = ["content-type": "application/x-www-form-urlencoded"]let postData = NSMutableData(data: "grant_type=authorization_code".data(using: String.Encoding.utf8)!)postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!)postData.append("&client_secret={yourClientSecret}".data(using: String.Encoding.utf8)!)postData.append("&code={yourAuthorizationCode}".data(using: String.Encoding.utf8)!)postData.append("&redirect_uri={https://yourApp/callback}".data(using: String.Encoding.utf8)!)let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/oauth/token")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "POST"request.allHTTPHeaderFields = headersrequest.httpBody = postData as Datalet session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()

Was this helpful?

/

The response should contain an access token and a refresh token.

{ "access_token": "eyJz93a...k4laUWw", "refresh_token": "GEbRxBN...edjnXbL", "token_type": "Bearer" }

Was this helpful?

/

If you are requesting a Refresh Token for a mobile app using the corresponding Native Client (which is public), then you don't need to send the client_secret in the request since it's only required for confidential applications.

Refresh Tokens must be stored securely by an application since they allow a user to remain authenticated essentially forever.

For more information on how to implement this using the Authorization Code Flow, refer to our tutorial, Call API Using the Authorization Code Flow. For other grants, see Authentication and Authorization Flows.

Learn more

Get Refresh Tokens (2024)

FAQs

What is the best practice for refresh token? ›

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.

How to pass a refresh token? ›

Use a refresh token

To refresh your access token and an ID token, you send a token request with a grant_type of refresh_token . Be sure to include the openid scope when you want to refresh the ID token. If the refresh token is valid, then you get back a new access token, a new ID token, and the refresh token.

Are refresh tokens worth it? ›

The main purpose of using a refresh token is to considerably shorten the life of an access token. The refresh token can then later be used to authenticate the user as and when required by the application without running into problems such as cookies being blocked, etc.

What are the security issues with refresh tokens? ›

4.1 Security risks when using refresh tokens

A compromised refresh token can lead to an attacker gaining access to user data over a longer period of time. Token theft: Refresh tokens can be stolen through various attack vectors, including cross-site scripting (XSS) or other web application vulnerabilities.

What is refresh token rotation strategy? ›

Refresh token rotation is the practice of updating an access_token on behalf of the user, without requiring interaction (ie.: re-authenticating). access_token s are usually issued for a limited time. After they expire, the service verifying them will ignore the value, rendering the access_token useless.

Where should I keep 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.

What if a refresh token is stolen? ›

If a refresh token is stolen, we can place this token on our blacklist to prevent it from generating any new access tokens, similar to how one might remove a session. This method isn't perfect — the attacker can still use the access token until it expires.

What is the lifespan of refresh token? ›

Refresh tokens have a longer lifetime than access tokens. The default lifetime for the refresh tokens is 24 hours for single page apps and 90 days for all other scenarios. Refresh tokens replace themselves with a fresh token upon every use.

How to decode a refresh token? ›

@bsrour You don't “decode” a refresh token. Refresh tokens are just strings. You use refresh tokens to extend the lifetime of an OAuth access token. If either the access token or refresh token have expired, then the user will need to authorise your application again.

Is JWT obsolete? ›

The JWT app type will be completely deprecated as of June 2023. New and current users have 12 months to migrate their JWT based solutions to the Server-to-Server OAuth app type.

What is the logic behind refresh token? ›

Refresh token allow users to log in and stay connected without providing their passwords for long periods. Further, they add a layer of security for sensitive data, improving the user experience. Refresh tokens can last from a few days to a few months.

Should refresh token be hashed? ›

Hashing refresh tokens before storing (or retrieving) is recommended both to prevent a compromise of this database from leaking valid tokens and to prevent string comparison timing attacks; assuming the refresh tokens are cryptographically secure random strings (as they should be!), a single unsalted round of a fast ...

Can refresh tokens be revoked? ›

You can revoke refresh tokens in case they become compromised.

Should I store refresh token in browser? ›

Finally, when using refresh tokens, make sure to store them in their own cookies. There is no need to send them with every API request, so ensure that this is not the case. Refresh tokens must only be added when refreshing expired access tokens.

What is the best practice for refresh token expiration? ›

Here are some best practices to follow:
  • Secure storage: Refresh tokens should be stored securely and never exposed to the client side to prevent unauthorized use.
  • Rotation policy: Implementing a token rotation policy where a new refresh token is issued with every access token refresh can reduce the risk of token theft.
Nov 9, 2023

What is the recommended refresh token length? ›

@Sandesh Patil Refresh tokens are nearly 500 characters long. We recommend that your application stack be made to handle tokens of at least 1000 characters to accommodate future expansion plans. This applies to access tokens as well as refresh tokens.

What is the recommended approach for refreshing JWT tokens? ›

Using refresh tokens is our recommended approach when your frontend is not a website (mobile, api only, etc). Making a request with a refresh token looks just like making a request with an access token. Here is an example using HTTPie.

Where should I store refresh tokens on the server side? ›

Server-side Token Storage

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. This is also known as the backend for frontend (BFF) proxy.

Should I send refresh token to client? ›

A refresh token is only sent to an authorization server and is therefore more secure. This didn't make much sense to me. It's a frequent response, yet why it's more secure to send it to an authorization server than to a resource server is never explained.

Top Articles
What Are The Best Seats At Madison Square Garden?
Convert $1 per hour to Yearly salary | Talent.com
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Kimberely Baumbach CPA

Last Updated:

Views: 6434

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Kimberely Baumbach CPA

Birthday: 1996-01-14

Address: 8381 Boyce Course, Imeldachester, ND 74681

Phone: +3571286597580

Job: Product Banking Analyst

Hobby: Cosplaying, Inline skating, Amateur radio, Baton twirling, Mountaineering, Flying, Archery

Introduction: My name is Kimberely Baumbach CPA, I am a gorgeous, bright, charming, encouraging, zealous, lively, good person who loves writing and wants to share my knowledge and understanding with you.