Retrieving OAuth Verification Code via .NET HttpWebRequest - quickbooks

I'm attempting to replicate the OAuth steps normally done via the "Connect to QuickBooks" button using HttpWebRequest/HttpWebResponse.
It's easy at first grabbing the request token and generating the authorization link:
private const string oauthBaseUrl = "https://oauth.intuit.com/oauth/v1";
private const string urlRequestToken = "/get_request_token";
private const string urlAccessToken = "/get_access_token";
private const string verifyUrl = "https://appcenter.intuit.com";
private const string authorizeUrl = "https://appcenter.intuit.com/Connect/Begin";
...
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(ckSS),
ConsumerSecret = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(csSS),
SignatureMethod = SignatureMethod.HmacSha1
};
IOAuthSession session = new OAuthSession(consumerContext, oauthBaseUrl + urlRequestToken, authorizeUrl, oauthBaseUrl + urlAccessToken);
IToken requestToken = session.GetRequestToken();
string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);
Then I walk through grabbing the request verification code that is generated in the set-cookie string when requesting the site at the authorization link:
var requestAuth = (HttpWebRequest) WebRequest.Create(authorizationLink);
requestAuth.Method = "GET";
requestAuth.ContentType = "application/x-www-form-urlencoded";
requestAuth.Accept = "text/html, application/xhtml+xml, */*";
requestAuth.Headers.Add("Accept-Encoding", "gzip, deflate");
requestAuth.Headers.Add("Accept-Language", "en-us");
requestAuth.Host = "appcenter.intuit.com";
requestAuth.KeepAlive = true;
var responseAuth = (HttpWebResponse) requestAuth.GetResponse();
Stream answerAuth = responseAuth.GetResponseStream();
var _answerAuth = new StreamReader(answerAuth);
string htmlAuth = _answerAuth.ReadToEnd();
// Need to grab the request verification code embedded in the set-cookie string
string cookies = responseAuth.Headers.Get("Set-Cookie");
int idx = cookies.IndexOf("__RequestVerificationToken", StringComparison.Ordinal);
if (idx > 0)
{
int startIndex = cookies.IndexOf("=", idx, StringComparison.InvariantCultureIgnoreCase);
int endIndex = cookies.IndexOf(";", startIndex + 1, StringComparison.InvariantCultureIgnoreCase);
requestVerificationCode = cookies.Substring(startIndex + 1, endIndex - (startIndex + 1));
postDataString += requestVerificationCode;
}
As I understand it, the request verification code is needed in order to get the OAuth verification code that is returned in the postdata appended to the callback URL, which is in turn needed to get the access token.
This is where the difficulty begins. Using Fiddler2, I find that the login URL for generating the OAuth verification code is https://appcenter.intuit.com/Account/LogOnJson. But no matter how much I try to replicate the HTTP POST using HttpWebRequest, all I get in return is a 500 error. I'm wondering if anyone has a working example of this step? Is this even possible? I hope so, because the alternative of pulling up IE and walking through the same steps like a macro is too ugly.
Any help on this? Thanks!

You can download the dotnet sample app for understanding how the OAUTH flow works:
https://github.com/IntuitDeveloperRelations/IPP_Sample_Code
Set your app keys in web.config.

Related

How to use LIKE operator for msg_id or from_email or to_email in query for sendgrid email activity?

var queryParams = "msg_id LIKE'pBRuJA0OSqyRAHaT2sW8hg'";
var client = new RestClient("https://api.sendgrid.com/v3/messages?query=" + queryParams + "&limit=1");
var request = new RestRequest(Method.GET);
client.Timeout = -1;
request.AddHeader("x-query-id", "{{x-query-id}}");
request.AddHeader("x-cursor", "{{x-cursor}}");
request.AddHeader("authorization", "bearer " + ApiKey);
IRestResponse response = client.Execute(request);
var sendGridEmailDetails = JsonConvert.DeserializeObject<SendGridResponse>(response.Content);
Here I want to find out msg_id start with this value 'pBRuJA0OSqyRAHaT2sW8hg' and I code for this as above. I used LIKE operator here but it gives me empty response. How to use LIKE operator if we want to find out startwith or endwith values? Does anyone know how this could be done? Thanks for your help & time.
This might be an empty result because you are not url encoding the request. It looks like you are using RestSharp to make requests to the API here, so what you can try instead is:
var params = new {
query = "msg_id LIKE 'pBRuJA0OSqyRAHaT2sW8hg'",
limit = 1
}
var client = new RestClient("https://api.sendgrid.com/v3/messages");
var request = new RestRequest(Method.GET);
request.addObject(params);
client.Timeout = -1;
request.AddHeader("x-query-id", "{{x-query-id}}");
request.AddHeader("x-cursor", "{{x-cursor}}");
request.AddHeader("authorization", "bearer " + ApiKey);
IRestResponse response = client.Execute(request);
var sendGridEmailDetails = JsonConvert.DeserializeObject<SendGridResponse>(response.Content);
This way you create an object of the parameters you want to pass and let the request object handle encoding them.

passing access token to Jira using OAuth Authentication

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.

How to get access token from Dropbox Sync & Datastore xamarin component

I trying get an access token from Dropbox Sync & Datastore xamarin component in Xamarin iOS project.I have used dropnet to get the access token but I'm getting an http exception :( let me know where I'm doing wrong
private static void GetAccessToken()
{
try
{
const string DropboxSyncKey = "XXXXXXXX";
const string DropboxSyncSecret = "XXXXXX";
//this url is obtained fromDBAccountManager.SharedManager.HandleOpenURL(url);
string token = "db-XXXXXX://1/connect?oauth_token_secret=XXXXXXX&state=xXXXXXXX&uid=XXXXXX&oauth_token=xXXXXXXXX";
token = token.Substring(token.LastIndexOf("&") + 13);
string stoken = "db-XXXXXX://1/connect?oauth_token_secret=XXXXXXX&state=xXXXXXXX&uid=XXXXXX&oauth_token=xXXXXXXXX";
int indexof = stoken.IndexOf("?") + 20;
int lastindex = stoken.IndexOf("&") - indexof;
string secrettoken = stoken.Substring(indexof, lastindex);
var client = new DropNetClient(DropboxSyncKey, DropboxSyncSecret, token, secrettoken);
var accesskey = client.GetAccessToken();
Console.WriteLine(token);
Console.WriteLine(secrettoken);
Console.WriteLine(accesskey);
}
catch (Exception)
{
}
}

Force.com Apex Code to generate Google API oAuth 2.0 JWT

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

401 error calling REST service from mvc controller

I am trying to make a request to a REST method and recieve the data in XML but this all goes well but when i want to use credentials for a method, because for this method you need to give credentials.
https://handshake:16a144bc5f480692d5c8d926068d2db5#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=236750347X6d2ee7
But when i use this one in the browser it work but this is not working from my controller.
//
// GET: /Home/Succes
public ActionResult Succes(string orderId)
{
string token = PaymentCalls.Login();
ViewBag.Token = token;
string _URL = "https://handshake:" + token + "#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=" + orderId;
NetworkCredential cr = new NetworkCredential("handshake", token);
XDocument doc = XDocument.Load(_URL);
var output = from feed in doc.Descendants("data")
select new Status
{
amount = feed.Element("amount").Value,
consumerAccountNumber = feed.Element("consumerAccountNumber").Value,
consumerCity = feed.Element("consumerCity").Value,
consumerEmail = feed.Element("consumerEmail").Value,
consumerName = feed.Element("consumerName").Value,
consumerZipcode = feed.Element("consumerZipcode").Value,
countryCode = feed.Element("countrCode").Value,
entranceCode = feed.Element("entranceCode").Value,
ipAddress = feed.Element("ipAddress").Value,
orderId = feed.Element("orderId").Value,
statsAdded = feed.Element("statsAdded").Value,
paymentSessionId = feed.Element("paymentSessionId").Value,
result = feed.Element("result").Value,
statusAction = feed.Element("statusAction").Value
};
return View(output);
So when we call this controller we get an 401 error but using the same url in the browser works. So i dont know but how can i set to pass credentials or something?

Resources