Newer Version Available
JWTBearerTokenExchange Class
Namespace
Usage
Use the methods in this class to post a signed JWT bearer token to the OAuth token endpoint, in exchange for an access token.
To test HTTP callouts to the token endpoint, use the Auth.HttpCalloutMockUtil class.
Example
- Creates the JSON Claims Set.
- Specifies the scope of the request with additional claims.
- Creates the signed JWT.
- Specifies the token endpoint and POSTs to it.
- Gets the access token from the HTTP response.
1public class MyController{
2
3
4 public MyController() {
5 Auth.JWT jwt = new Auth.JWT();
6 jwt.setSub('user@salesforce.com');
7 jwt.setAud('https://login.salesforce.com');
8 jwt.setIss('3MVG99OxTyEMCQ3gNp2PjkqeZKxnmAiG1xV4oHh9AKL_rSK.BoSVPGZHQukXnVjzRgSuQqGn75NL7yfkQcyy7');
9
10 //Additional claims to set scope
11 Map<String, Object> claims = new Map<String, Object>();
12 claims.put('scope', 'scope name');
13
14 jwt.setAdditionalClaims(claims);
15
16 //Create the object that signs the JWT bearer token
17 Auth.JWS jws = new Auth.JWS(jwt, 'CertFromCertKeyManagement');
18
19 //Get the resulting JWS in case debugging is required
20 String token = jws.getCompactSerialization();
21
22 //Set the token endpoint that the JWT bearer token is posted to
23 String tokenEndpoint = 'https://login.salesforce.com/services/oauth2/token';
24
25 //POST the JWT bearer token
26 Auth.JWTBearerTokenExchange bearer = new Auth.JWTBearerTokenExchange(tokenEndpoint, jws);
27
28 //Get the access token
29 String accessToken = bearer.getAccessToken();
30
31 }
32}JWTBearerTokenExchange Constructors
The following are constructors for JWTBearerTokenExchange.
JWTBearerTokenExchange Methods
The following are methods for JWTBearerTokenExchange. All are instance methods.
getAccessToken()
Signature
public String getAccessToken()
Return Value
Type: String
Usage
This method extracts the access_token from the token response. If the token response issues the access token in a different parameter, the request fails.
If you want the full HTTP token response returned, use getHttpResponse instead.
getGrantType()
Signature
public String getGrantType()
Return Value
Type: String
getHttpResponse()
Signature
public System.HttpResponse getHttpResponse()
Return Value
Type: System.HttpResponse
Usage
You can get the access token from the full System.HttpResponse. If you want only the access_token from the token response, you can use getAccessToken instead.
setGrantType(grantType)
Signature
public void setGrantType(String grantType)
Parameters
- grantType
- Type: String
Return Value
Type: void
setJWS(jws)
setTokenEndpoint(tokenEndpoint)
Signature
public void setTokenEndpoint(String tokenEndpoint)
Parameters
- tokenEndpoint
- Type: String
Return Value
Type: void