Google JWT Invalid Signature from Salesforce - salesforce

I am trying to authenticate via a service account from Salesforce.com to Google's DFP. I had the integration working under a previous user/credential pair, but am required to update to a new user.
I created the project/user/key pair in the Google Developer Console and added the new service account to the network in DFP. I then changed the "iss" value to be the new user's email and the private key to be the new private key from the keypair.
I am now receiving an 'Invalid Signature' error.
In SFDC, I am using Crypto.sign method with RSA-SHA256.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_crypto.htm#apex_System_Crypto_sign
I have validated the key format to be PKCS#8 with header and new line characters removed per the documentation (I went so far as to decode the ASN.1 format and inspect the nodes for conformity).
Have I missed a step in the connection between the user and the correct credential? Is there a way for me to validate the signature that I am producing locally to see where I am going wrong? The only difference I have seen is that the old private key was shorter than the current private key.
Below is the code I am using to generate the JWT (again, this code functioned properly with a different username and credential key).
JWTHeader head = new JWTHeader();
head.alg = 'RS256';
head.typ = 'JWT';
JWTClaimSet claim = new JWTClaimSet();
claim.iss = '<username>#*.iam.gserviceaccount.com';
claim.scope = 'https://www.googleapis.com/auth/dfp';
claim.aud = 'https://accounts.google.com/o/oauth2/token';
claim.iat = DateTime.now().getTime() / 1000;
claim.exp = claim.iat + 3600;
System.debug(JSON.serialize(head));
System.debug(JSON.serialize(claim));
String key = '<privatekey>’;
String base = EncodingUtil.urlEncode(EncodingUtil.base64Encode(Blob.valueOf(JSON.serialize(head))), 'UTF-8') + '.' + EncodingUtil.urlEncode(EncodingUtil.base64Encode(Blob.valueOf(JSON.serialize(claim))), 'UTF-8');
String sig = EncodingUtil.urlEncode(EncodingUtil.base64Encode(Crypto.sign('RSA-SHA256', Blob.valueOf(base), EncodingUtil.base64Decode(key))), 'UTF-8');
String body = base + '.' + sig;
System.debug(body);
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://accounts.google.com/o/oauth2/token');
req.setBody('grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=' + body);
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setMethod('POST');
HttpResponse resp = http.send(req);

Days later I found another solution that solved the issue. The problem was the base64urlsafe encoding. This encoding is not natively done in SFDC and perscribes the removal of trailing padding characters from the base64 string. Luckily, my original username encoded with no padding characters in the claim set. With the new username, the padding characters are present and must be removed before signing.
It all comes down to just a few characters.

Related

Use HMAC with OData Connected Service

So we want to use a webapi that is build in ASP.net and uses OData as protocol. I did some homework and saw that Microsoft has a very good documenten OData Connected Service. The only thing I can't find is that the webapi we want to use has a HMAC for security. I cannot find an example where the OData Connected Service is used with HMAC. Could someone explain if and how HMAC is possible with the OData Connected Service?
Probably the answer depends on the specific implementation of the HMAC on the server side.
If server receives all the data included in the request along with the Authorization header and extracts the values (APP Id, Signature, Nonce and Request Time stamp) from the Authorization header, then client should:
Build a string by combining all the data that will be sent, this string contains the following parameters (APP Id, HTTP method, request URI, request time stamp, nonce, and Base 64 string representation of the request pay load).
The signature will be sent in the Authorization header using a custom scheme such as ”amx”. The data in the Authorization header will contain the APP Id, request time stamp, and nonce separated by colon ‘:’. The format for the Authorization header will be like: [Authorization: amx APPId:Signature:Nonce:Timestamp].
Client send the request as usual along with the generated data in the Authorization header (just use client hooks or httpclient).
Example (after generating client code):
private string APPId = "65d3a4f0-0239-404c-8394-21b94ff50604";
private string APIKey = "WLUEWeL3so2hdHhHM5ZYnvzsOUBzSGH4+T3EgrQ91KI=";
public async Task<IEnumerable<string>> TestODataHMAC()
{
// add there your OData Uri
var container = new DefaultContainer(new Uri("https://services.odata.org/V4/(S(qc322lduoxrqt13nhydbdcvx))/TripPinServiceRW/"));
container.Configurations.RequestPipeline.OnMessageCreating = (args) =>
{
var request = new HttpWebRequestMessage(args);
// Get the Request URI
string requestUri = HttpUtility.UrlEncode(request.Url.AbsoluteUri.ToLower());
// Calculate UNIX time
var epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
var timeSpan = DateTime.UtcNow - epochStart;
var requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();
// Create the random nonce for each request
var nonce = Guid.NewGuid().ToString();
// Creating the raw signature string by combinging
// APPId, request Http Method, request Uri, request TimeStamp, nonce
var signatureRawData = string.Format("{0}{1}{2}{3}{4}", APPId, request.Method, requestUri, requestTimeStamp, nonce);
// Converting the APIKey into byte array
var secretKeyByteArray = Convert.FromBase64String(APIKey);
// Converting the signatureRawData into byte array
var signature = Encoding.UTF8.GetBytes(signatureRawData);
// Generate the hmac signature and set it in the Authorization header
using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray))
{
var signatureBytes = hmac.ComputeHash(signature);
var requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
//Setting the values in the Authorization header using custom scheme (hmacauth)
request.SetHeader("Authorization", string.Format("hmacauth {0}:{1}:{2}:{3}", APPId, requestSignatureBase64String, nonce, requestTimeStamp));
}
return request;
};
// add there your OData method call
var nquery = container.People.Where(p => p.Gender == PersonGender.Female).Take(10) as DataServiceQuery<Person>;
var response = await nquery?.ExecuteAsync();
return (response as QueryOperationResponse<Person>).Select(p => p.FirstName).ToArray();
}

How to send Twilio SMS via Web Service in Salesforce Apex

I want to send SMS from Twilio noticed they have libraries built for Java, .Net, Node, etc. so that we can use them if we are upto those technologies.
But I want to do the same from Salesforce Apex and trying to figure out how to build the Http parameters to make the authorization.
I tried to map with cURL example given in Twilio documentation and can't find header keys for Auth token.
Below is my current code and looking for how to set the authentication params.
req.setEndpoint(baseURL + '/2010-04-01/Accounts/account_sid/Messages.json');
req.setMethod('POST');
req.setHeader('to', EncodingUtil.urlEncode('+to_number', 'UTF-8'));
req.setHeader('from', EncodingUtil.urlEncode('+from_number', 'UTF-8'));
Http ht = new Http();
HttpResponse res = ht.send(req);
Updated request :
Blob headerValue = Blob.valueOf('my-twilio-account-sid:my-twilio-auth-token');
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String body = EncodingUtil.urlEncode('From=+from_number&To=+to_number&Body=Sample text from twilio', 'UTF-8');
req.setBody(body);
Http ht = new Http();
HttpResponse res = ht.send(req);
Response saying
Bad Request : A 'From' phone number is required.
The phone numbers don't go in the headers.
For the headers you will need
Content-Type: "application/x-www-form-urlencoded"
then you will need another header for authorization
Authorization: auth-string
where auth-string is a combination of the string Basic followed by a space followed by a base64 encoding of twilio-account-sid:twilio-auth-token (replace with your Twilio credentials joined by the colon) so the header will look something like
Authorization: "Basic ABCiDEdmFGHmIJKjLMN2OPQwR2S3TUVzABliCDE3FGc1HIo2JKL2MjNwOPcxQRSwTUc1Vzc0XmYhZAB3CDElFGH1Jw=="
The body of the POST request should contain key, value pairs of To, From and Body, something like
"From=" + twilio-phone-number + "&To=" + to-number + "&Body=" + message-body (replace with string values for phone numbers and message).
I hope this helps.

Unity/Android ServerAuthCode has no idToken on Backend

I have an unity app and use the google-play-games plugin with google *.aar versions 9.4.0. I lately changed my Backend (Google App Engine) from php to java. My problem is the following: in php the serverauthcode is used to get the users data (in JWT format) - it was working fine. So I changed to a Java servlet and I am failing since 2 days to get a valid idtoken. I am able to recieve the server auth code from my app and a valid token response is made by GoogleAuthorizationCodeTokenRequest (see code snippet). Unfortunately it does not contain any idtoken content but a valid auth_token. So I can not get the user id to identifiy the user. When I call tokenResponse.parseIdToken(); it is failing with a NullPointerException.
servlet code (authCode is the serverAuthCode I send from the play-games-plugin inside Unity to my GAE):
// (Receive authCode via HTTPS POST)
// Set path to the Web application client_secret_*.json file you downloaded from the
// Google Developers Console: https://console.developers.google.com/apis/credentials?project=_
// You can also find your Web application client ID and client secret from the
// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
// object.
String CLIENT_SECRET_FILE = "/mypath/client_secret.json";
// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
clientSecrets.getDetails().getTokenUri(),
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode,
REDIRECT_URI) // Specify the same redirect URI that you use with your web
// app. If you don't have a web version of your app, you can
// specify an empty string.
.execute();
String accessToken = tokenResponse.getAccessToken();
// Get profile info from ID token -> HERE IT THROWS AN EXCEPTION.
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
String userId = payload.getSubject(); // Use this value as a key to identify a user.
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
the token response looks like (its invalid now):
{
"access_token" : "ya29.CjA8A7O96w-vX4OCSPm-GMEPGVIEuRTeOxKy_75z6fbYVSXsdi9Ot3NmxlE-j_t-BI",
"expires_in" : 3596,
"token_type" : "Bearer"
}
In my PHP GAE I always had a idToken inside this constuct which contained my encrypted data. But it is missing now?! So I asssume I do somthing differently in Java or I made a mistake creating the new OAuth 2.0 Client on the google console.
I checked the accessToken manually via:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.CjA8A7O96w-vX4OCSPm-GMEPGVIEu-RTeOxKy_75z6fbYVSXsdi9Ot3NmxlE-j_t-BI
{
"issued_to": "48168146---------.apps.googleusercontent.com",
"audience": "48168146---------.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/games_lite",
"expires_in": 879,
"access_type": "offline"
}
Is there something I do not see? Help is very much appreciated...
I found a root cause discussion inside the unity plugin "play-games-services" on github:
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1293
and
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1309
It seems that google switching their authentication flow. In the given links they are talking about adding the email scope inside the plugin to get the idtoken again. I'll try that in the next days and share my experience.
Here is a good explaination about what happens:
http://android-developers.blogspot.de/2016/01/play-games-permissions-are-changing-in.html
If you do what paulsalameh said here (Link to Github) it will work again:
paulsalameh: Sure. After you import the unitypackage, download NativeClient.cs and
PlayGamesClientConfig.cs from my commits (#1295 & #1296), and replace
them in the correct locations.
Afte that "unity play-services-plugin" code update you will be able to add AddOauthScope("email") to PlayGamesClientConfiguration, which allows your server to get the idtoken with the serverAuthCode again...
Code snippet from Unity:
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("email")
.AddOauthScope("profile")
.Build();
Now I am back in business:
{
"access_token" : "ya29.Ci8..7kBR-eBdPw1-P7Pe8QUC7e_Zv7qxCHA",
"expires_in" : 3600,
"id_token" : "eyJhbGciOi......I1NiE0v6kqw",
"refresh_token" : "1/HlSZOo......dQV1y4E",
"token_type" : "Bearer"
}

logging into d2l lms using valence

I want to authenticate and get a specific course org unit id using valence and java. I have a application id and user key for the application I got from the d2l keytool. I am also using d2l's java client library for authenticating. i.e. com.d2lvalence.idkeyauth.*;
I am getting a http 403 error on the last line of code.
Can someone see what I doing wrong?
URL url = null;
URLConnection connection = null;
String host = "ucbdev.desire2learn.com";
int port = 443;
String appID = "from d2l";
String appKey = "from d2l";
String userId = "";
String userKey = "";
AuthenticationSecurityFactory factory = new AuthenticationSecurityFactory();
// appID and appKey are from d2l
ID2LAppContext appContext = factory.createSecurityContext(appID, appKey);
URI resultUri=new URI("?x_a=fromd2l&x_b=fromd2l");
ID2LUserContext userContext=appContext.createUserContext(resultUri, host, port, true);
if (userContext == null){
System.out.println("USERCONTEXT is NULL");
}
System.out.println("USERCONTEXT HOST NAME IS :"+userContext.getHostName());
userId = userContext.getUserId();
userKey = userContext.getUserKey();
System.out.println("userID is "+userId);
System.out.println("userKey is "+userKey);
URI newUri = userContext.createAuthenticatedUri("/d2l/api/lp/1.0/orgstructure/", "GET");
String res = newUri.toString();
System.out.println("authenticated uri usercontext s "+res);
connection = newUri.toURL().openConnection();
//cast the connection to a HttpURLConnection so we can examin the status code
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
StringBuilder sb=new StringBuilder();
BufferedReader in = null;
//if the status code is success then the body is read from the input stream
if(httpConnection.getResponseCode()==200) {
in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
//otherwise the body is read from the output stream
} else {
System.out.println("Error: " + httpConnection.getResponseCode() + ""); //error 403 here
// in = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
}
You do not seem to be clear on how the authentication works for the Valence Learning Framework API.
The AppId/AppKey pair you get back from D2L's KeyTool is the keypair that you'll use to prove that your API call comes from your app (i.e. you pass the AppId in the x_a parameter on a normal call, and you use the AppKey to generate a signature that you then pass in the x_c parameter on the call). But each normal API call also requires user tokens to prove the is being made on behalf of a known user:
All our SDKs work in the same general way:
First you create an application context object that's built using your AppID/Key keypair.
Then, you create an "URL for authentication": this URL will be a call to the special "get user tokens" API call (here the x_a parameter is your AppId, and the x_b parameter is the signature).
You direct the user's browser to go to this URL for authentication, and it's x_target query parameter specifies the callback URL where the LMS should send the user ID/Key pair after it successfully determines who the user is.
Once you have this User ID/Key pair, in subsequent normal API calls, you will pass the User ID in the x_b parameter (as you're passing the App Id in the x_a) and you will use the User Key to make a signature that you will pass in the x_d parameter.
Please follow along the authentication conceptual topic in the docs carefully, as it will show you all the steps involved in the process of your app getting back a UserID/Key pair so you can then use it to make API calls.

Convert a clientsecret into a private key

I'm working with Google Cloud Storage in AppEngine and I'm attempting to use a POST form to upload a file to GCS. The problem I'm having is with the steps needed to sign the policy document. I can easily fetch the client_secret, which is a String from the client_secrets.json that the API Console gave me. however, in order to create a signature, I need to convert that string into a PrivateKey object. Here's what my code looks like:
//create the policy document and encode it
String policyDocument = ... //omitted for brevity
String encodedPolicy = Base64.encodeString(policyDocument);
//sign using SHA256 with RSA
String secretKey = ... //I fetch this from client_secrets.json
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(secretKey); //THIS IS THE PROBLEM!
sig.update(encodedPolicy.getBytes("UTF-8"));
String signature = new String(Base64.encode(sig.sign()));
//put the values in the request attributes so we can fetch them from a JSP
req.setAttribute("policy", encodedPolicy);
req.setAttribute("signature", signature);
As noted above, my problem is in the line
sig.initSign(secretKey); //THIS IS THE PROBLEM!
secretKey is a String. Signature.initSign() expects a PrivateKey, or one of its descendant objects. How do I convert the string in the client_secrets.json into a PrivateKey (or derived) object that I can pass Signature.initSign?
Any help would be greatly appreciated. Thanks
OK, here's where I am right now. I tried the suggestions below, and all of the documentation is urging me to use the client_secret in the client_secrets.json file downloaded from the Google API console, not the service account. And besides, I'm trying to construct an example of a user's upload, not a service account.
I found the following code on another page:
public static String signPolicyDocument(String policyDocument, String secret) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
byte[] secretBytes = secret.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(secretBytes, "HmacSHA256");
mac.init(signingKey);
byte[] signedSecretBytes = mac.doFinal(policyDocument.getBytes());
return new String(Base64.encode(signedSecretBytes));
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
And it gets me all the way through the process...until I submit the resulting form. Then I get the following response:
The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.
What signing method is it looking for?
Here's what I think you need to do:
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
sig.initSign(privateKey);
The keyBytes variable should contain a byte[] array with your service account key file in it.
The final answer to this problem is like the conclusion of Wargames. As WOPR said, "A strange game...the only way to win is not to play." Avoid signing and policy document and all that crap and use the blobstore.
(See this: https://developers.google.com/appengine/docs/java/blobstore/overview#using-blobstore-with-gcs)
It's very easy to implement; when you create your temporary blobstore upload URL like so:
//open the blobstore service and create the upload url
BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
String uploadUrl = bs.createUploadUrl("/display",
UploadOptions.Builder.withGoogleStorageBucketName(bucket));
The downside to this approach is the object name will be a string of characters you don't recognize. You can open the blobstore viewer and see your object by file name in the blobstore, but in GCS its object name will be gobbledygook. (A hash, maybe? A randomly assigned ID)?
To upload a file to GCS from Appengine you can use the blobstore Api. Follow the steps described in Using Blobstore with GCS. The advantage is that you don't have to worry about keys and the code is much simpler.

Resources