OAuth2
The oauth2 core extension has replaced the webservicescommons/oauthauthorizationserver extension. It exposes the HTTP endpoint as an authorization server. It doesn't introduce any new significant functionalities.
Enabling and Configuring oauth2
<extension name="oauth2" />
By default, the web root is authorizationserver/ but you can change it using the oauth2.webroot=... property.
|
Property Name |
Description |
Type |
Default Value |
|---|---|---|---|
|
webservicescommons.required.channel |
Channel protocol for oauth/* endpoints |
http/https |
https |
|
oauthauthorizationserver.tokenServices.reuseRefreshToken |
Specifies if a new refresh token should be created during refreshing an access token |
boolean |
false |
|
oauth2.supportRefreshToken |
Enables the refresh token |
boolean |
true |
|
oauth2.refreshTokenValiditySeconds |
Refresh token time-to-live |
seconds |
2592000 (30 days) |
|
oauth2.cleanupAccessToken.maxRows |
Max rows fetched on cleaning up the obsolete access token table |
int |
100 |
|
oauth2.accessTokenValiditySeconds |
Access token time-to-live |
seconds |
43200 (12 hours) |
|
oauth2.optimize.accesstoken.save.enabled |
Optimizes the performance of the oauth2 extension by ensuring that the OAuthAccessTokenModel object isn't updated when the saveAccessToken method is called and there are no changes to the OAuth2Authentication object. |
boolean |
true |
|
oauth2.accesstoken.save.retry |
Ensures that the system retries to save access tokens in situations when an attempt to save such tokens ends with the ModelSavingException exception being thrown. Such situations are a result of duplicate access token IDs being created by two or more threads trying to create the same access token in HybrisOAuthTokenStore. |
boolean |
true |
|
oauth2.authorizationcode.stored.as.sha.signature |
Enables storing authorization codes as an SHA signature. |
boolean |
true |
|
oauth2.authorizationcode.length |
Allows you to configure the length of generated authorization codes. |
int |
30 |
|
oauthauthorizationserver.tokenServices.refreshWithLock |
Prevents the DuplicateKeyException exception caused by authenticationIdIdx index unique constraint violation. With selective thread locking implemented for HSQLDB and database row locking implemented for databases other than HSQLDB, refresh tokens cannot longer be consumed more than once by concurrent requests. For databases other than HSQLDB, the property also introduces database row locking for refresh tokens before refresh tokens are removed, which prevents potential deadlocks that could occur when access tokens are refreshed and refresh tokens are revoked at the same time. |
boolean |
true |
In the System/OAuth tab in Backoffice, you can manage OAuth clients and access tokens.
Deserialised Access Tokens after Spring Security Upgrade
Since all access tokens are serialized in the database, they are prone to deserialization when Spring Security is upgraded. Remove all your access tokens whenever Spring Security is upgraded.
For more information on upgraded libraries, see Additional Information.
Authorization Server
-
/oauth/authorize
-
/oauth/token
For details on usage and interfaces, see the RFC specification at https://tools.ietf.org/html/rfc6749#section-1.3.3
.
Response Encoding
Response content type might be in a JSON format, for example:
/oauth/token - proper credentials - json
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
{"access_token":"a084da1c-72af-4cf7-a461-986de3f3070f","token_type":"bearer","expires_in":34191,"scope":"read"}
or in XML, for example:
/oauth/token - proper credentials - xml
HTTP/1.1 200 OK Content-Type: application/xml;charset=UTF-8 <oauth><access_token>a084da1c-72af-4cf7-a461-986de3f3070f</access_token><expires_in>33966</expires_in></oauth>
The same applies to errors:
/oauth/token - bad credentials - json
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="hybris", error="invalid_client", error_description="Bad client credentials"
Content-Type: application/json;charset=UTF-8
{"error":"invalid_client","error_description":"Bad client credentials"}
/oauth/token - bad credentials - xml
HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic realm="hybris", error="invalid_client", error_description="Bad client credentials" Content-Type: application/xml;charset=UTF-8 <oauth><error_description>Bad client credentials</error_description><error>invalid_client</error></oauth>
Resource Server
There are two ways to validate a client token on custom web services. You can use the ywebservices template to generate a restful extension with a configuration that is already set up for integrating the resource server present in Platform.
You can also prepare your configuration manually:
Manual setup
<!-- load oauth2 definitions for resource server -->
<import resource="classpath*:oauth2-resource-spring.xml"/>
<!-- specify the filter change, the 'id' must be the same on web.xml filter -->
<bean id="oauth2SecurityFilterChain" class="de.hybris.platform.servicelayer.web.PlatformFilterChain">
<constructor-arg>
<list>
<ref bean="springSecurityFilterChain"/>
</list>
</constructor-arg>
</bean>
<!-- spring security. the pattern will be the one specific of your application -->
<http pattern="/rest/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false"/>
<intercept-url pattern="/rest/**" access="IS_AUTHENTICATED_FULLY" method="GET"/>
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"/>
<access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>
Preventing Brute Force Attacks
Using the oauth2.maxAuthenticationAttempts property, you can set the maximum number of failed client authentication attempts. If the max number of failed authentication attempts is reached, the oauth2 client is disabled. The property isn't enabled by default. You can set it in local.properties, as shown in the example:
oauth2.maxAuthenticationAttempts=10
The oauth2.maxAuthenticationAttempts property defines common configuration for all OAuth clients.
Once a client is disabled, it's not possible to access resources using an access token previously issued for this client. The client can also no longer be used in OAuth flows, which means that it's impossible to issue a new access token or refresh an existing one by using this client in the request.
For disabled clients, each subsequent authentication attempt results in a 401 HTTP error response similar to the following:
{"error":"unauthorized","error_description":"Authentication for clientId:'e2eTests' is disabled"}
You can re-enable disabled clients in the Clients tab under OAuth in Backoffice. Once your client is re-enabled, access tokens that are issued for this client can be used again if they haven't already expired.
Preventing Brute Force Attacks for Public Clients
The oauth2.maxAuthenticationAttempts configuration property is also applied for OAuth public clients. Public clients are not required to provide any password parameters in their authentication requests.
Once a public client is disabled, it's not possible to access resources using an access token previously issued for this client. The client can also no longer be used in OAuth flows, which means that it's impossible to issue a new access token or refresh an existing one by using this client in the request.
For information on prevention against user login brute force attacks, see User Account.
Disabling Client-side SSL Certificate Checks and Hostname Verification
If you want to switch to HTTPS for the token endpoint and other RESTful resources that our API offers, but still do not want to use an official server certificate, you need to disable the client-side checks. The following code shows you how this task can be accomplished.
The DummyHostnameVerifier disables hostname checks and simply verifies all hostnames:
package de.hybris.platform.ycommercewebservices.test.groovy.webservicetests;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class DummyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
The DummyTrustManager overrides all checks and trusts all clients, even if the certificate cannot be verified:
package de.hybris.platform.ycommercewebservices.test.groovy.webservicetests;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class DummyTrustManager implements X509TrustManager
{
@Override
public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) throws CertificateException
{
//TODO unimplemented
}
@Override
public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) throws CertificateException
{
//TODO unimplemented
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}
Before you can create <HTTPSUrlConnections>, you need to modify your SSL context to use instances of the above classes.
<Applying DummyHostnameVerifier and DummyTrustManager>
def trustManager = new DummyTrustManager()
def hostnameVerifier = new DummyHostnameVerifier();
def sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, [trustManager]as X509TrustManager[], new java.security.SecureRandom());
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
Roles
OAuth 2.0 defines the following roles:
-
Resource Owner: An entity that can grant access to a protected resource. When the resource owner is a person, then it is called: end-user.
-
Resource Server: The server that hosts the protected resources, capable of accepting and responding to protected resource requests using the access tokens.
-
Client: An application making protected resource requests on behalf of the resource owner and with its authorization. The term client does not imply any particular implementation characteristics (for example, whether the application runs on a server, desktop, or any other particular device).
-
Authorization Server: The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.
The authorization server is defined in the OAuth2 and the example resource server is configured in ycommercewebservices Extension and ywebservices Extension.
Flows
OAuth 2.0 comes with four flows. SAP Commerce supports all of them:
-
As the Resource Owner Password Flow holds a user's <username> and <password>, it is less secure and not for third-party applications.
-
The Authorization Code Flow is best to use if the web application can keep the< client_secret>.
-
The Implicit Flow does not need any authorization tokens. As such, it is easier but less secure. JavaScript running within a browser is less trusted, and the refresh tokens are not issued. This is suited for the client-side web applications that need temporary access.
-
The Client Credentials Flow gives the client access to the resources it owns.
Depending on your client application, you need to choose the appropriate flow. You also need to disable the other flows that you do not use.
Resource Owner Password Flow
This flow is somewhat similar to the basic authentication flow but it has a few benefits. It is typically used for trusted mobile applications, such as mobile Android or iOS applications. The flow includes sending the user's <username> and <password> to the token endpoint in exchange for an <access_token>. Replying with a refresh token is optional. The mobile <client> otherwise has to keep the username and password for long-lived access.
The flow needs a <username> and <password> for the <access_token>. However, keep in mind that the API provider provides access tokens combined with a< refresh_token>. The client therefore does not need to save the username and password, but it only has to pass this information on. The <access_token> and <refresh_token> need to be persisted locally, which is better than storing user credentials. The following diagram describes this flow.
Detailed description of the presented flow:
-
Step (A): The <client> receives the <username> and <password>. In this step, the user enters this information directly into the client application. Note that users must have a way to identify the application as being the official application they can trust.
-
Step (B): Next, the client application makes a request to the Authorization Server, for example the /oauth/token endpoint. There are two ways the <client_id> and <client_secret> can be sent along: either in a regular basic authentication request header, or as a part of the parameters passed in the request payload (that is, the request body). See the list of parameters to be passed:
-
<client_id> and <client_secret>: Either passed as parameters or as a basic authentication header. Basic authentication means that <client_id> and <client_secret> are treated as username and password, concatenated using a colon (:) and then <Base64> encoded. This value is then used as a part of the authorization request header, for example: Authorization: Basic <Base64-encoded username:password>
-
<username> and <password>: Credentials for the resource owner, the user's real credentials.
-
<grant_type>: Needs to be set to <password> for this flow.
-
-
Step (C): The authentication server returns the <access_token> with an optional <refersh_token>.
The following code sample describes this flow.
import com.google.appengine.api.urlfetch.*
import groovy.json.*
import java.net.URLEncoder
def client_id = 'mobile_android'
def client_secret = 'secret'
if (!params.username)
{
out << "No username given..."
return
}
if (!params.password)
{
out << "No password given..."
return
}
def username = URLEncoder.encode(params.username, 'UTF-8')
def password = URLEncoder.encode(params.password, 'UTF-8')
HTTPResponse res
URL tokenURL = "http://localhost:9001/authorization/oauth/token".toURL()
if (params.basic)
{
//direct exchange of username and password for access token
def headers = [Authorization:"Basic ${"${client_id}:${client_secret}".toString().bytes.encodeBase64().toString()}"]
res = tokenURL.post(deadline: 30, headers: headers, payload:"grant_type=password&username=${username}&password=${password}".getBytes())
}
else
{
//direct exchange of username and password for access token
res = tokenURL.post(deadline: 30, payload:"client_id=${client_id}&client_secret=${client_secret}&grant_type=password&username=${username}&password=${password}".getBytes())
}
out << res.text
The above code is written in Groovy and uses the Gaelyk Web Framework. This is, however, only for demonstration purposes. Typically, the code would not be a part of the server-side web application, but it serves as an example of how the single request against the authorization server is performed. First, <client_id> and <client_secret> need to be known for the code issuing the request. In this case, <username> and <password> are passed as parameters. In a real scenario, the credentials would be entered into a form through the application user interface.
Depending on the basic parameter, we either pass the username and password in a HTTP Post request as the authorization header or as a part of the parameters in the body of the request. The above code simply prints the response, which shall be a JSON-formatted document like in the example below.
{"access_token":"f2288c2b-1d08-4aac-a210-d62c0901f915","token_type":"bearer","refresh_token":"3f94522d-5a5a-4a22-bc85-f5f5a56920b4","expires_in":43199}
Using CURL For Resource Owner Password Flow
During the development phase, you may want to quickly try out a RESTful request. If you run this request against an OAuth 2.0 protected resource, you need an <access_token>. Unfortunately, OAuth 2.0, just like basic authentication, is not supported by the browser. The easiest option is to use cURL, the command-line utility for HTTP requests in combination with the resource owner password flow.
The token endpoint needs to be HTTPS in the production environment, but during the development phase the following example should work fine.
curl -X POST -d "client_id=mobile_android&client_secret=secret&grant_type=password&username=demo&password=1234" http://localhost:9001/authorizationserver/oauth/token
This will result in a JSON response with the <access_token>.
{
"access_token": "a503faf9-45b5-4fec-8334-337284a66ea4",
"token_type": "bearer",
"refresh_token": "486adfde-757b-4d37-81d7-446c2ec4bd91",
"expires_in": 43199
}
Next, if you want to access a protected resource, you have to pass the authorization header. The following code sample shows how to access the <current user> resource.
curl --header "Authorization: Bearer a503faf9-45b5-4fec-8334-337284a66ea4" http://localhost:9001/rest/v1/electronics/customers/current
The response is presented in the next sample below.
{
"uid": "demo",
"name": "demo",
"firstName": "Klaus",
"lastName": "Demokunde"
...
}
Authorization Code Flow Or Server-side Flow
The flow includes sending the client user by redirecting to the provider's login and authorization page. Next, it redirects back to the web application and passes an authorization code in the URL parameters. Then, it can be exchanged for <access_token> which needs to be passed in the HTTP request headers to obtain access to the user's data. With the <access_token> and information about its expiry, there is also a <refresh_token> issued. In the next step, a <refresh_token> can be exchanged against a new <access_token> for a long-lived access.
The following flow diagram describes this flow.
Detailed description of the presented flow:
-
Step (A): Redirect the user to the authorization server (typical endpoint should be /oauth/authorize). All communication should occur through HTTPS so that <client_id> contained in the URL is safe. The following parameters have to be included:
-
<response_type>: The value needs to be <code>, as we use the authorization code flow.
-
<client_id>: For SAP Commerce web services, the OAuth 2.0 client has to be manually set up in the Spring Security OAuth2 XML configuration.
-
<client_secret>: The <secret> for the <client_id>, and it needs to be on the server-side so that users cannot see it.
-
<redirect_uri>: Optional, but recommended. When a user is redirected to the authorization endpoint, this value needs to be passed, and it has to match the server configuration settings.
-
<scopes>: Used to allow different access levels.
-
<state>: Optional, but recommended. Used to overcome CSRF (cross-site request forgery) attacks.
The following code sample uses the described parameters.
import java.net.URLEncoder def client_id = 'mobile_android' def client_secret = 'secret' def redirect_uri = 'http://localhost:8080/oauth2_callback' def scopes = [ 'customer' ] def state = new Random(System.currentTimeMillis()).nextInt().toString() request.getSession(true).setAttribute('state', state) redirect "http://localhost:9001/authorizationserver/oauth/authorize?client_id=${client_id}&redirect_uri=${URLEncoder.encode(redirect_uri, 'UTF-8')}&response_type=code&scope=${URLEncoder.encode(scopes.join(' '), 'UTF-8')}&state=${URLEncoder.encode(state, 'UTF-8')}"
-
-
Step (B): The user authenticates himself and is granted authorization. This can be a two-step process: if the user is not logged in, then he has to log in first and then provide access to the <client>.
-
Step (C): The authorization server redirects back to the web application. The parameters passed in this redirect to the application are:
-
code: After the <grant_type> is set to <code>, the authorization code is accessible. Later, <code> is used to request the <access_token>.
-
state: The <state> specified in the first redirect to the authorization server. It should be checked with the session if the value is the same.
-
-
Step (D): The web application verifies the redirect and exchanges the authorization code for an access token. The following code snippet is an example of how it works.
import com.google.appengine.api.urlfetch.* import groovy.json.* import java.net.URLEncoder def client_id = 'mobile_android' def client_secret = 'secret' def redirect_uri = 'http://localhost:8080/oauth2_callback' if (!params.code) { out << "User denied access." return } if (!params.state) { out << "State parameter missing, somethign is wrong..." return } if (!session) { out << "No session, how weird!" return } if (params.state != session.state) { out << "State does not match! (${params.state} != ${session.state})" return } def code = params.code //exchange code for real oauth token URL tokenURL = "http://localhost:9001/authorizationserver/oauth/token".toURL() HTTPResponse res = tokenURL.post(deadline: 30, payload:"code=${code}&client_id=${client_id}&client_secret=${client_secret}&redirect_uri=${URLEncoder.encode(redirect_uri, 'UTF-8')}&grant_type=authorization_code".getBytes()) out << res.textThe above code first verifies that the <code> and <state> parameters are there and then checks whether the current state is equal to the session's state. Then the final request is made to obtain the <access_token>. The parameters passed into the URL are:
-
<code>: The obtained code.
-
<grant_type>: Tells the token endpoint we want the access token. This is now set to <authorization_code>.
-
<redirect_uri>: Used for consistency.
-
<client_id> and <client_secret>: Used for identifying the client application.
-
-
Step (E): Eventually, access token is passed on to the client. The output looks like in the following sample.
{"access_token":"865b3ecf-54d3-413c-951e-fae0b00c906f","token_type":"bearer","refresh_token":"addc590a-c79c-4e7e-a1a7-f98921765c20","expires_in":43192}
Implicit Flow Or Client-Side Flow
In the Implicit Flow (also called, Implicit Grant Flow), the required access token is sent back to the client application without the need of an authorization request token. This makes the flow easier, but also less secure. As the client application, which is typically JavaScript running within a browser, is less trusted, no refresh tokens for long-lived access are returned. You should use this flow for the client-side web applications (JavaScript clients) that need temporary access (for example, a few hours) to the user's data. Returning an access token to the JavaScript clients also means that your browser-based application needs to take special care. Take into account the XSS (Cross-Site Scripting) attacks that could leak the access token to other systems.
The following flow-diagram describes this flow.
Detailed description of the presented flow:
-
Step (A): The user information is sent to the authorization server. Following parameters are sent by URL:
-
<response_type>: Tells the authorization server to respond directly with an access token. It needs to be set to <token>.
-
<client_id>: Identifies which client is requesting access for a user.
-
<redirect_uri>: Strongly recommended and needs to match the settings for the <client_id>.
-
<scope>: Optional, but currently not required for the SAP Commerce OCC Web Services, as there is a single <customer> scope.
-
<state>: Optional, but recommended to mitigate XSS (Cross Site Scripting) attacks.
The following code sample uses the described parameters.
import java.net.URLEncoder def client_id = 'client-side' def redirect_uri = 'http://localhost:8080/oauth2_implicit_callback' def scopes = [ 'customer' ] def state = new Random(System.currentTimeMillis()).nextInt().toString() session.state = state redirect "http://localhost:9001/authorizationserver/oauth/authorize?client_id=${client_id}&redirect_uri=${URLEncoder.encode(redirect_uri, 'UTF-8')}&response_type=token&scope=${URLEncoder.encode(scopes.join(' '), 'UTF-8')}&state=${URLEncoder.encode(state, 'UTF-8')}"
-
-
Step (B): Now, the user may log in and then be presented an authorization screen where they are asked to grant access to the specified scope.
-
Step (C): The authorization server redirects back to the client web application. The <access_token> is part of this redirect URI, but in the <#hash> fragment of the URI. This makes it invisible for some server-side code, like the J2EE, which does not allow access to the hash fragment (as it is only intended for the client). At this point, nothing can be done for the redirection request, but as it hits the web application again at the <redirect_uri> you need to make sure the request will work.
For the purpose of a demo client application, a controller endpoint is used that forwards directly to the HTML page. The remaining logic (which is, getting access to the <access_token> and verifying the state parameter) all happens in JavaScript. In the demo application we chose to extract the state from the user's session for which we need to route the redirect request through the controller.
request.setAttribute('state', session.state) session.removeAttribute('state') forward '/WEB-INF/pages/oauth2_implicit_callback.gtpl' -
Step (D): Now, the user-agent (browser) follows the redirect and the client-side web application server responds with an HTML page that includes JavaScript to parse the hash fragment.
-
Step (E): The following sample shows the code of the returned HMTL page.
<!doctype html> <html> <head> <title>Oauth2 Implicit Callback Page</title> <head> <body> <div id="oauthParams" data-state=${request.getAttribute('state')}></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/js/oauth.js"></script> </body> </html>Elements to note:
-
state: The state that was into the user's session in the controller is extracted and passed on by the J2EE HttpServletRequest as an attribute. This state is passed on to a <data-*> field of the <oauthParams> HMTL <div> element. Later, it can be extracted and verified with the state arrived in the redirection URI.
-
scripts: In the sample, two script sources are included. One is the CDN-hosted jQuery, the second is our own oauth JavaScript.
-
-
<Step (F)>: Now, at the user-agent end, JavaScript will access the <#hash> fragment to extract the access token and compare the state value. The JavaScript resource looks like in the following sample.
$(document).ready(function(){ var oauthParams = {}, queryString = location.hash.substring(1), regex = /([OAuth 2.0 (PSI 2 Update)^&=]+)=([OAuth 2.0 (PSI 2 Update)^&]*)/g, m, html=' '; var state = $('#oauthParams').data('state'); while (m = regex.exec(queryString)) { oauthParams[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } console.log(oauthParams); for (pos in oauthParams) html += pos + '=' + oauthParams[pos] + ' '; if (oauthParams.state == state) html += 'State matches, use the access_token!'; else html += 'State does NOT match! Issue!'; $('#oauthParams').html(html); });The OAuth 2.0 parameters are part of the hash fragment, that is, the part of a URL after the <#> sign.
-
Step (G): Finally, the <access_token> is passed on to the client.
Client Credentials Flow
The purpose of this flow is giving the client access to the resources it owns. It identifies the client and the OCC Web Services using the client credentials flow to restrict access to various calls.
The flow to obtain a client credentials token is very simple: you need to pass the <client_id> and <client_secret> parameters to the token endpoint. Keep in mind that in the production environment the token endpoint needs to use HTTPS. The following cURL sample provides an example.
curl -X POST -d "client_id=mobile_android&client_secret=secret&grant_type=client_credentials" http://localhost:9001/authorizationserver/oauth/token
The authorization server responds with the access token if the credentials are valid.
{
"access_token": "b4dc1410-6b15-4a7c-bd22-1abea1f0fa3a",
"token_type": "bearer",
"expires_in": 42921
}
The token identifies, authenticates, and authorizes the client.
Refreshing an Expired Access Token
There is a need to refresh the issued <access_token>. Without refreshing these tokens, a <client> must remember user credentials, which is a less secure approach. Providing access tokens and refreshing the tokens means that the client only has to remember the tokens. The following code describes how to issue refresh tokens.
import com.google.appengine.api.urlfetch.*
import groovy.json.*
import java.net.URLEncoder
def client_id = 'mobile_android'
def client_secret = 'secret'
def redirect_uri = 'http://localhost:8080/oauth2_callback'
if (!params.token)
{
out << "No refresh token given..."
return
}
def token = params.token
//exchange code for real oauth token
URL tokenURL = "http://localhost:9001/authorizationserver/oauth/token".toURL()
HTTPResponse res = tokenURL.post(deadline: 30, payload:"refresh_token=${token}&client_id=${client_id}&client_secret=${client_secret}&redirect_uri=${URLEncoder.encode(redirect_uri, 'UTF-8')}&grant_type=refresh_token".getBytes())
out << res.text
It is a single request and response. In real life, the token endpoint would only be accessible by HTTPS. Parameters that must be sent to the /oauth/token endpoint to refresh a token are:
-
<client_id> and <client_secret>: As the refresh request is sent from a server, keep the <client_secret> really secret. Both parameters need to be sent along.
-
<redirect_uri>: Required, although not used here. The server responds with a JSON file with the token information directly. If you have a <redirect_uri> configured for the client, you need to pass this on for the refresh request.
-
<grant_type>: It needs to be <refresh_token>, indicating the exchange of a refresh token for a new <access_token> and also a refresh token for the next time.
-
<refresh_token>: For the client; the refresh token passed as the token request parameter and then into the refresh token request.
The server responds with a JSON response like in the following example.
{"access_token":"b70aeeb9-9095-4899-9480-2dbf432746ac","token_type":"bearer","refresh_token":"61f0d3fe-62bf-413f-8d6d-93a3bfe763b9","expires_in":43199,"scope":"customer"}