I am trying to request a token to the Here API with Rest service java in order to obtain OAuth 2.0 Token Credentials. I am blocked in the request level and constantly having the same error but according to the documentation I don't do anything wrong.
Here is the necessary code in REST Java to make the request.
The below code i tried.
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class here {
private static final String HMAC_SHA256 = "HmacSHA256";
private static final String ENC = "UTF-8";
private static Base64 base64 = new Base64();
private static String key = "MyKeyID"; // here.access.key.id from credential file
private static String secret = "MySecretKey" //here.access.key.secret
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
long value = (System.currentTimeMillis() / 1000);
int unique = (int) (Math.random() * 100000000);
// These params should ordered in key
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("grant_type", "client_credentials"));
qparams.add(new BasicNameValuePair("oauth_consumer_key", "MY_KEY_ID"));
qparams.add(new BasicNameValuePair("oauth_nonce", ""
+ unique));
qparams.add(new BasicNameValuePair("oauth_signature_method",
"HMAC-SHA256"));
qparams.add(new BasicNameValuePair("oauth_timestamp", ""
+ value));
qparams.add(new BasicNameValuePair("oauth_version", "1.0"));
System.err.println("query param->>>");
// creating authentication signature
String signature = getSignature(URLEncoder.encode(
"https://account.api.here.com/oauth2/token", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
// comibining the params
String authHeader = "OAuth oauth_consumer_key=MY_KEY,"
+"oauth_nonce="+unique+","
+"oauth_signature="+signature+","
+"oauth_signature_method=HMAC-SHA256,"
+"oauth_timestamp="+value+","
+"oauth_version=1.0";
HttpPost httpPost = new HttpPost("https://account.api.here.com/oauth2/token");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
String grant_type = "client_credentials";
StringEntity input = new StringEntity("grant_type=" + grant_type);
httpPost.setEntity(input);
// output the response content.
System.out.println("Token and Token Secrect:");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int len;
byte[] tmp = new byte[2048];
try {
while ((len = instream.read(tmp)) != -1) {
System.out.println(new String(tmp, 0, len, ENC));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static String getSignature(String url, String params) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
StringBuilder base = new StringBuilder();
base.append("POST&");
base.append(url);
base.append("&");
base.append(params);
System.out.println("Stirng for oauth_signature generation:" + base);
// yea, don't ask me why, it is needed to append a "&" to the end of
// secret key.
byte[] keyBytes = (secret + "&").getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA256);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(key);
// encode it, base64 it, change it to string and return.
return new String(base64.encode(mac.doFinal(base.toString().getBytes(
ENC))), ENC).trim();
}}
And this is the error that I keep getting :
{"errorId":"ERROR-27b88f02-5d76-40ea-81d5-de6e70cf8464","httpStatus":401,"errorCode":401205,"message":"Unsupported signature method in the header. Require HMAC-SHA256","error":"invalid_request","error_description":"errorCode: '401205'. Unsupported signature method in the header. Require HMAC-SHA256"}
According to the documentation, https://developer.here.com/documentation/authentication/dev_guide/topics/using-aaa-javasdk-or-3rd-party-libraries.html
I develop the code based on the above api documentation but iam not getting the result.
Does anyone know how to fix this issue?
I tried this code
HttpClient httpClient = HttpClientBuilder.create().build();
String headers = "grant_type=client_credentials"+"&oauth_consumer_key=mykey"+"&oauth_nonce=uniquevalue"+"&oauth_signature_method=HMAC-SHA256"+"&oauth_timestamp=timestamp"+"&oauth_version=1.0";
String combine = "POST"+"\n&"+URLEncoder.encode("https://account.api.here.com/oauth2/token", StandardCharsets.UTF_8.toString())+"\n&"+URLEncoder.encode(headers, StandardCharsets.UTF_8.toString());
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(("mysecretkey &").getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String signature = Base64.encodeBase64String(sha256_HMAC.doFinal(combine.getBytes()));
String authHeader = "OAuth "
+ "oauth_consumer_key=\"X1E2a0ElfkaHx7aezqN5Hg-1234\","
+"oauth_nonce=\"uniquevalue\","
+"oauth_signature=\""+signature+"\","
+"oauth_signature_method=\"HMAC-SHA256\","
+"oauth_timestamp=\"timestamp\","
+"oauth_version=\"1.0\"";
HttpPost httpPost = new HttpPost("https://account.api.here.com/oauth2/token");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.addHeader("Host", "account.api.here.com");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
StringEntity input = new StringEntity("grant_type=" + "client_credentials");
httpPost.setEntity(input);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
Its showing one more error like errorCode: '401202'. Invalid Client Authorization header, expecting signed request format. Please give some suggestion how to request a toke ?
Can you try to modify your code as-
// creating authentication signature
String signature = getSignature(URLEncoder.encode(
"https://account.api.here.com/oauth2/token", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
// comibining the params
String authHeader = "OAuth oauth_consumer_key=MY_KEY,"
+"oauth_nonce="+unique+","
+"oauth_signature="+URLEncoder.encode(signature,"UTF-8")+","
+"oauth_signature_method=HMAC-SHA256,"
+"oauth_timestamp="+value+","
+"oauth_version=1.0";
I tried your solution and got the same error. There is some problem with the generated signature. I found this official Here Java SDK, which has classes to generate signature and Authorization Header.
https://github.com/heremaps/here-aaa-java-sdk/blob/acf6c7a982070f0b311c1741ce4887938b60df5b/here-oauth-client/src/main/java/com/here/account/auth/SignatureCalculator.java#L101
Hope this helps !
Related
I am using OAuth authenication in Jira to test some methods in jira using JIRA Rest Java Client. I have got the access token using OAuth authenication that I need to pass on Jira URL. Here is all what I have got to get access token.
Token is 38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Token secret is cnDSL8oJyuoaQdRcFDwgHzLppSshQn9b
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Access token is : 015CeJiH8cpI5R3OKpNco158kApq8YwV
Now I am passing that access token to Jira URL but I am getting an empty array. Please let me know where I am doing wrong or what changes do I need to incorporate into my code to make this thing work. Here is my code.
public void getAllIssueTypesUsingOAuth(JiraCQCredential jcqcred) {
System.out.println("Inside getAllIssuetypeAssociatedToProject for JiraAdapterImpl");
//String username = jcqcred.getUserName();
//String password = jcqcred.getPassword();
String jiraURL = jcqcred.getJiraUrl();
if (!jiraURL.endsWith("/")) {
jiraURL = jiraURL + "/";
}
try {
String accessToken = JiraAdapterImpl.getAccessToken(); // This method is giving me access token
URL url = new URL(jiraURL + "rest/api/2" + "/" + "issuetype?access_token=" + accessToken);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String issueTypes = sb.toString();
System.out.println("Issuetype associated to project are\n" + issueTypes);
JSONArray jsonArray = new JSONArray(issueTypes);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String issueNames = (String) jsonObject.get("name");
System.out.println(issueNames);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Its giving me an empty array like []
Hi After searching the little bit I finally managed to a find the solution to the above problem. After getting the access token just pass that access token to the makeAuthenticatedRequest(url, accessToken) method that will give you the resultant data which you want to retrive. Here url is the url which you want to hit to get the resultant data.
private AtlassianOAuthClient getJiraOAuthClient() {
final String baseURI = "http://bmh1060149:8080";
final String consumerKey = "hardcoded-consumer";
final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWHM5iNswoNYzrNS2k6ZYkDnZxUlbrPDELETbz/n3YgBHGUlyrXi2PBjAgMBAAECggEAAtMctqq6meRofuQbEa4Uq5cv0uuQeZLV086VPMNX6k2nXYYODYl36T2mmNndMC5khvBYpn6Ykk/5yjBmlB2nQOMZPLFPwMZVdJ2Nhm+naJLZC0o7fje49PrN2mFsdoZeI+LHVLIrgoILpLdBAz/zTiW+RvLvMnXQU4wdp4eO6i8J/Jwh0AY8rWsAGkk1mdZDwklPZZiwR3z+DDsDwPxFs8z6cE5rWJd2c/fhAQrHwOXyrQPsGyLHTOqS3BkjtEZrKRUlfdgV76VlThwrE5pAWuO0GPyfK/XCklwcNS1a5XxCOq3uUogWRhCsqUX6pYfAVS6xzX56MGDndQVlp7U5uQKBgQDyTDwhsNTWlmr++FyYrc6liSF9NEMBNDubrfLJH1kaOp590bE8fu3BG0UlkVcueUr05e33Kx1DMSFW72lR4dht1jruWsbFp6LlT3SUtyW2kcSet3fC8gySs2r6NncsZ2XFPoxTkalKpQ1atGoBe3XIKeT8RDZtgoLztQy7/7yANQKBgQDQvSHEKS5SttoFFf4YkUh2QmNX5m7XaDlTLB/3xjnlz8NWOweK1aVysb4t2Tct/SR4ZZ/qZDBlaaj4X9h9nlxxIMoXEyX6Ilc4tyCWBXxn6HFMSa/Rrq662Vzz228cPvW2XGOQWdj7IqwKO9cXgJkI5W84YtMtYrTPLDSjhfpxNwKBgGVCoPq/iSOpN0wZhbE1KiCaP8mwlrQhHSxBtS6CkF1a1DPm97g9n6VNfUdnB1Vf0YipsxrSBOe416MaaRyUUzwMBRLqExo1pelJnIIuTG+RWeeu6zkoqUKCAxpQuttu1uRo8IJYZLTSZ9NZhNfbveyKPa2D4G9B1PJ+3rSO+ztlAoGAZNRHQEMILkpHLBfAgsuC7iUJacdUmVauAiAZXQ1yoDDo0Xl4HjcvUSTMkccQIXXbLREh2w4EVqhgR4G8yIk7bCYDmHvWZ2o5KZtD8VO7EVI1kD0z4Zx4qKcggGbp2AINnMYqDetopX7NDbB0KNUklyiEvf72tUCtyDk5QBgSrqcCgYEAnlg3ByRd/qTFz/darZi9ehT68Cq0CS7/B9YvfnF7YKTAv6J2Hd/i9jGKcc27x6IMi0vf7zrqCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";
AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");
return jiraoAuthClient;
}
Here is the code to get Access Token
private String getAccessToken() {
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
String token = requestToken.token;
String tokenSecret = requestToken.secret;
System.out.println("Token is " + requestToken.token);
System.out.println("Token secret is " + requestToken.secret);
System.out.println("Retrieved request token. go to " + authorizeUrl);
String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, "");
System.out.println("Access token is : " + accessToken);
return accessToken;
}
This is the method you call to retrieve the data.
public void getAllCommentOfIssueUsingOAuth() {
logger.info("Inside getAllCommentOfIssue for JiraAdapterImpl");
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
String accessToken = getAccessToken();
String url = "your Jira URL";
String responseAsString = jiraoAuthClient.makeAuthenticatedRequest(url, accessToken);
System.out.println(responseAsString);
}
This will give you the resultant JSON data or XML data in resultantString.
I use this code to access weather data from yahoo and everything just work fine.
Somehow this stops working getting a "Bad request" from yahoo...
"Please provide valid credentials. OAuth oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR", realm="yahooapis.com"
"
I try to understood what happed and i think that has to do with the oAuth from yahoo but i don't know how to use it and the documentation from yahoo sucks...
code below..
mForcastTown.Add(MainForm.ExtraFE_IdHttp.Get('http://weather.yahooapis.com/forecastrss?w='+ mAdd_Town[mTonwNum].mWoeID +'&u='+ mAdd_Town[mTonwNum].mDegree);
Thank you...
UPDATE...
I found this below and when run in the browser i get the xml i need but when i run it to the
IdHttp.get('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid=55903793%20and%20u=%27c%27&format=xml')
i get unknown version found...
What is this...
Thank you...
I had the same problem for Java, maybe this will direct you to something.
In this link there is a sample java code:
// Copyright 2019 Oath Inc. Licensed under the terms of the zLib license see https://opensource.org/licenses/Zlib for terms.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Random;
import java.util.Collections;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.URI;
/**
*
* <pre>
* % java --version
* % java 11.0.1 2018-10-16 LTS
*
* % javac WeatherYdnJava.java && java -ea WeatherYdnJava
* </pre>
*
*/
public class WeatherYdnJava {
public static void main(String[] args) throws Exception {
final String appId = "test-app-id";
final String consumerKey = "your-consumer-key";
final String consumerSecret = "your-consumer-secret";
final String url = "https://weather-ydn-yql.media.yahoo.com/forecastrss";
long timestamp = new Date().getTime() / 1000;
byte[] nonce = new byte[32];
Random rand = new Random();
rand.nextBytes(nonce);
String oauthNonce = new String(nonce).replaceAll("\\W", "");
List<String> parameters = new ArrayList<>();
parameters.add("oauth_consumer_key=" + consumerKey);
parameters.add("oauth_nonce=" + oauthNonce);
parameters.add("oauth_signature_method=HMAC-SHA1");
parameters.add("oauth_timestamp=" + timestamp);
parameters.add("oauth_version=1.0");
// Make sure value is encoded
parameters.add("location=" + URLEncoder.encode("sunnyvale,ca", "UTF-8"));
parameters.add("format=json");
Collections.sort(parameters);
StringBuffer parametersList = new StringBuffer();
for (int i = 0; i < parameters.size(); i++) {
parametersList.append(((i > 0) ? "&" : "") + parameters.get(i));
}
String signatureString = "GET&" +
URLEncoder.encode(url, "UTF-8") + "&" +
URLEncoder.encode(parametersList.toString(), "UTF-8");
String signature = null;
try {
SecretKeySpec signingKey = new SecretKeySpec((consumerSecret + "&").getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHMAC = mac.doFinal(signatureString.getBytes());
Encoder encoder = Base64.getEncoder();
signature = encoder.encodeToString(rawHMAC);
} catch (Exception e) {
System.err.println("Unable to append signature");
System.exit(0);
}
String authorizationLine = "OAuth " +
"oauth_consumer_key=\"" + consumerKey + "\", " +
"oauth_nonce=\"" + oauthNonce + "\", " +
"oauth_timestamp=\"" + timestamp + "\", " +
"oauth_signature_method=\"HMAC-SHA1\", " +
"oauth_signature=\"" + signature + "\", " +
"oauth_version=\"1.0\"";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url + "?location=sunnyvale,ca&format=json"))
.header("Authorization", authorizationLine)
.header("X-Yahoo-App-Id", appId)
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.body());
}
}
The problem with this code is where the oauthNonce generated with random bytes. Here, the error is caused by the unrecognized chars. Because for any random byte there can be any char that your system doesn't recognize and can't process because it converts it into a string.
I replace the whole part with this:
String oauthNonce = RandomStringUtils.random(10, true, true);
It worked like a charm. I currently don't have any errors now and able to get the response. I hope this helps.
I am having trouble calling Yahoo Gemini API to access Yahoo Gemini Advertising from my C# console (desktop) application.
Here are steps I used:
Create an installed application on https://developer.yahoo.com/apps/create/. This gave me both {Client ID} and {Client Secret}.
https://api.login.yahoo.com/oauth2/request_auth?client_id={Client ID} &redirect_uri=oob&response_type=code&language=en-us. This will take me to the yahoo login screen where I sign in. Press the Agree button and the next screen shows the seven-letter authorization code (say nzbcns9). I write down this authorization code.
Then I use the following code to try to get the access token:
class Program
{
static void Main(string[] args)
{
string clientId = {Client ID};
string secret = {Client Secret};
var request = WebRequest.Create(#"https://api.login.yahoo.com/oauth2/get_token");
request.Method = "POST";
SetBasicAuthHeader(request, clientId, secret);
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
request.ContentType = "application/x-www-form-urlencoded";
var response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
}
static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
}
Then I get
Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse().
What did I do wrong?
I also try to post the same message using Fiddler, I get
{"error":"invalid_request"}
I tried your code and what worked for me was to put the line request.ContentType = "application/x-www-form-urlencoded"; BEFORE Stream dataStream = request.GetRequestStream();
So this worked:
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
Neither of these worked for me, but it did work once I changed the SetBasicAuthHeader to use ISO-8859-1 encoding:
static void SetBasicAuthHeader( WebRequest request, String userName, String userPassword )
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String( Encoding.GetEncoding( "ISO-8859-1" ).GetBytes( authInfo ) );
request.Headers[ "Authorization" ] = "Basic " + authInfo;
}
I am new to flickr API.Some where i get the code to create the signature for getting request token.but i cant able to create it for the access token.Always says that the signature is invalid.
i am using the code for creating signature is
private static String getreqSignature(String url, String params)
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException {
StringBuilder base = new StringBuilder();
base.append("GET&");
base.append(url);
base.append("&");
base.append(params);
System.out.println("Stirng for oauth_signature generation:" + base);
// yea, don't ask me why, it is needed to append a "&" to the end of
// secret key.
byte[] keyBytes = (ApplicationContext.getFLICKR_API_SECRET() + "&")
.getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
System.out.println(new String(base64.encode(mac.doFinal(base.toString()
.getBytes(ENC))), ENC));
// encode it, base64 it, change it to string and return.
return new String(base64.encode(mac.doFinal(base.toString().getBytes(
ENC))), ENC).trim();
}
My query parameters are
qparams.add(new BasicNameValuePair("oauth_consumer_key","******"));
qparams.add(new BasicNameValuePair("oauth_nonce", ""+ (int) (Math.random() * 100000000)));
qparams.add(new BasicNameValuePair("oauth_signature_method","HMAC-SHA1"));
qparams.add(new BasicNameValuePair("oauth_timestamp", ""+ (System.currentTimeMillis() / 1000)));
qparams.add(new BasicNameValuePair("oauth_version", "1.0"));
// generate the oauth_signature
String signature = getreqSignature(URLEncoder.encode(
"http://www.flickr.com/services/oauth/request_token", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
// qparams.add(new BasicNameValuePair("oauth_verifier", verifier));
qparams.add(new BasicNameValuePair("oauth_signature", signature));
URI uri = URIUtils.createURI("http", "www.flickr.com", -1,
"/services/oauth/request_token",
URLEncodedUtils.format(qparams, ENC), null);
How to create signature to get access token.What to change in the above code.
finally i used Scribe library to get my details.Its working fine.
I am trying to generate a JWT in Apex on Force.com but keep getting a 400 "error" : "invalid_grant". I've tried numerous variations, but just can't get a valid response. My clientEmailAddress is correct (eg ###developer.gserviceaccount.com). I extracted the value of my Private Key using openSSL. I wrote a method to base64URL encode based on other posts on the board. Any help would be greatly appreciated.
public static String base64URLencode(Blob input){
String output = encodingUtil.base64Encode(input);
output = output.replace('+', '-');
output = output.replace('/', '_');
while ( output.endsWith('=')){
output = output.subString(0,output.length()-1);
}
return output;
}
public static void generateJWT(){
Long rightNow = (dateTime.now().getTime()/1000)+1;
JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
gen.writeStringField('iss',clientEmailAddress);
gen.writeStringField('scope','https:\\/\\/www.googleapis.com\\/auth\\/prediction');
gen.writeStringField('aud','https:\\/\\/accounts.google.com\\/o\\/oauth2\\/token');
gen.writeNumberField('exp',rightNow+300);
gen.writeNumberField('iat',rightNow);
String claimSet = gen.getAsString().trim();
String header = '{"alg":"RS256","typ":"JWT"}';
String signatureInput = base64URLencode(blob.valueOf(header))+'.'+base64URLencode(blob.valueOf(claimSet));
Blob signature = crypto.sign('RSA', blob.valueOf(signatureInput), encodingUtil.base64decode(privatekey));
String jwt = signatureInput+'.'+base64URLencode(signature);
http h = new http();
httpRequest req = new httpRequest();
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setMethod('POST');
req.setBody('grant_type='+encodingUtil.urlEncode('urn:ietf:params:oauth:grant-type:jwt-bearer','UTF-8')+'&assertion='+encodingUtil.urlEncode(jwt,'UTF-8'));
req.setEndpoint('https://accounts.google.com/o/oauth2/token');
httpResponse res = h.send(req);
}
I think the method name is Base64encode but not base64urlencode