Microsoft OAuth does not return refresh_token - javascript

33I issued the following request to Microsoft to get the AuthCode,
public ActionResult ConnectMicrosoft()
{
var ClientId = "xxxxxxxxx";
// var ClientSecret = "xxxxxxxxxxxxxxx";
var RedirectUri = "http://www.domain.com:50952/Settings/MicrosoftAuthCallback";
var MsUrl = String.Format("https://login.live.com/oauth20_authorize.srf?client_id={0}&scope=wl.basic&response_type=code&redirect_uri={1}", ClientId, RedirectUri);
return Redirect(MsUrl);
}
and this during the callback,
public ActionResult MicrosoftAuthCallback(string code)
{
string result = null;
var ClientId = "xxxxxxxxxxxx";
var ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxx";
var RedirectUri = "http://www.domain.com:50952/Settings/MicrosoftAuthCallback";
var FinalUri = String.Format("https://login.live.com/oauth20_token.srf?client_id={0}&client_secret={1}&code={2}&grant_type=authorization_code&redirect_uri={3}", ClientId, ClientSecret, code, RedirectUri);
HttpWebRequest _Request = HttpWebRequest.Create(FinalUri) as HttpWebRequest;
_Request.Method = "GET";
using (WebResponse _Response = _Request.GetResponse())
{
var sr = new StreamReader(_Response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
var _Serializer = new JavaScriptSerializer();
var TokenData = _Serializer.Deserialize<MicrosoftToken>(result);
return View();
}
The callback method successfully returns the access_token, tokentype and expires_in and authentication_token, but refresh token is missing. Could you give me a clue on what i'm doing wrong?

huh, forgot to include the scope, wl.offline_access, also request must b POST with ContentType = "application/x-www-form-urlencoded"

Related

NodeJS Request - login into website

i'm very new to Javascript and i just want to login into website from NodeJS request. This website need information from the first time visited to login.
Here is my code.
var cheerio = require('cheerio');
var loginLink = 'link';
var loginJar = request.jar();
var ltValue = '';
request.get({url: loginLink, jar: loginJar}, function(err, httpResponse, html)
{
var dat = cheerio.load(html);
var arr = dat('input[name="lt"]');
ltValue = arr.attr('value');
arr = dat('input[name="execution"]');
executionValue = arr.attr('value');
/*Post body*/
var loginBody = 'username=' + usn + '&password=' + pwd + '&lt=' + ltValue + '&execution=' + executionValue
request.post({url: loginLink, jar: loginJar, method: 'post', json: true, body: loginBody, }}, function(err, res, b)
{
if (b.indexOf('errors') != -1)
console.log("Success");
else console.log("Fail");
});
});
I have write try it in C# and it work correctly but in my NodeJs code it always return fail. I have tried everytime but i couldn't do it. Please help me with this problem.
byte[] binData = Encoding.ASCII.GetBytes(loginBody)
string loginFile = "loginInfo.txt";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("link");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = binData.Length;
request.CookieContainer = cookieContainer;
using (Stream stream = request.GetRequestStream())
{
stream.Write(binData, 0, binData.Length);
}
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
File.WriteAllText(loginFile, reader.ReadToEnd());
}
string loginData = userID + " " + password;
File.WriteAllText("login.txt", loginData);

How to login through api from Google Script?

I'm now working on the api of Gatecoin and want to get my open order on Google Sheet. I'm trying this:
function GetOrder() {
var method = "GET"
var URL = "https://api.gatecoin.com/Trade/Orders"
var contentType = "application/json"
var d = new Date()
var now = d.getTime()
var msg = method + URL + contentType + now
var publicKey = :Public_key
var privateKey = :Private_key
var hash = Utilities.computeHmacSha256Signature(msg, privateKey, Utilities.Charset.US_ASCII);
var hashInBase64 = Utilities.base64Encode(hash);
var options ={
'contentType': 'application/json',
'method': method,
'API_PUBLIC_KEY': publicKey,
'API_REQUEST_SIGNATURE': hashInBase64,
'API_REQUEST_DATE': now
};
var rdata = UrlFetchApp.fetch("https://api.gatecoin.com/Trade/Orders", options)
}
But the response mentions I was not logged in. What am I doing wrong?
I believe your options should have headers defined in an object as such:
var options ={
“contentType”: “application/json”,
“method”: method,
“headers”: {
“API_PUBLIC_KEY”: publicKey,
“API_REQUEST_SIGNATURE”: hashInBase64,
“API_REQUEST_DATE”: now
}
};

How to create a valid signature for the mws amazon (javascript)?

var protocol = "https";
var method = "POST";
var host = "mws.amazonservices.com";
var uri = "/Products/2011-10-01";
var marketPlaceId = "ATVPDKIKX0DER";
function generateRequest(asin, action){
var today = new Date();
time = today.toISOString();
var parameters = {
// "ASINList.ASIN.1":asin,
"Query":asin,
"AWSAccessKeyId":AWSAccessKeyId,
"Action": action,
"MarketplaceId":marketPlaceId,
"SellerId": SellerId,
"SignatureMethod":"HmacSHA256",
"SignatureVersion":"2",
"Timestamp":time,
"Version":"2011-10-01"
};
parameters = $.param( parameters );
var messageToEncrypt = method+"\n"+host+"\n"+uri+"\n"+parameters;
var sig = CryptoJS.HmacSHA256(messageToEncrypt, SecretKey);
sig = sig.toString(CryptoJS.enc.Base64);
sig = encodeURIComponent(sig);
parameters = parameters+"&Signature="+sig;
var mwsRequest = protocol+"://"+host+uri+"?"+parameters;
return mwsRequest;
}
// var asaUrl = generateRequest('B01I94N9TC','GetMatchingProduct');
var asaUrl = generateRequest('B01I94N9TC','ListMatchingProducts');
$.ajax({
url:asaUrl,
method: "POST",
success: function(data){
console.log(data)
}
});
It gives an error
"Check your AWS Secret Access Key and signing method. Consult the service documentation for details"
but if you send to Get Matching Product is operating normally

Get signed_request in Node.js (Express) Facebook canvas app

is there any way how to get and parse signed_request in Node.js Facebook page tab app? I need to know page id and if user liked the page...
I did this a little while ago, and ended up writing a small library to do it. The original CoffeeScript can be found at https://gist.github.com/fbef51815ab6f062b51a#file_signed_request.coffee, here is a JavaScript translation:
var crypto = require('crypto');
SignedRequest = (function() {
function SignedRequest(secret, request) {
this.secret = secret;
this.request = request;
this.verify = this.verify.bind(this);
var parts = this.request.split('.');
this.encodedSignature = parts[0];
this.encoded = parts[1];
this.signature = this.base64decode(this.encodedSignature);
this.decoded = this.base64decode(this.encoded);
this.data = JSON.parse(this.decoded);
}
SignedRequest.prototype.verify = function() {
if (this.data.algorithm !== 'HMAC-SHA256') {
return false;
}
var hmac = crypto.createHmac('SHA256', this.secret);
hmac.update(this.encoded);
var result = hmac.digest('base64').replace(/\//g, '_').replace(/\+/g, '-').replace(/\=/g, '');
return result === this.encodedSignature;
};
SignedRequest.prototype.base64encode = function(data) {
return new Buffer(data, 'utf8').toString('base64').replace(/\//g, '_').replace(/\+/g, '-').replace(/\=/g, '');
};
SignedRequest.prototype.base64decode = function(data) {
while (data.length % 4 !== 0) {
data += '=';
}
data = data.replace(/-/g, '+').replace(/_/g, '/');
return new Buffer(data, 'base64').toString('utf-8');
};
return SignedRequest;
})();
module.exports = SignedRequest;
Which you can use like this:
var verifier = new SignedRequest(clientSecret, signedRequest);
verifier.verify() // whether or not the signed request verifies
verifier.data // the data from the signed request

restructure string in javascript

I have this string in which i need to re-structure using JavaScript.
Label=11121212&TopicArn=test&AWSAccountId.member.1=YYYYYYY&ActionName.member.1=createTopic&Action=AddPermission&Version=2010-03-31&AWSAccessKeyId=XXXXXXXXX&SignatureVersion=2&SignatureMethod=HmacSHA1&Timestamp=2012-05-02T16%3A06%3A09.000Z&Signature=C3uIh%2Bz%2Fik
For this example, AWSAccessKeyId should be the first part of the string and label should be 2nd last. There are others as well, similar to this.
Expected output --AWSAccessKeyId=XXXXXXXXX&AWSAccountId.member.1=YYYYYYYYY&Action=AddPermission&ActionName.member.1=Publish&Label=ios-sns-permission-label&Signature=dEaNL0ibP5c7xyl4qXDPFPADW0meoUX9caKyUIx1wkk%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-05-02T00%3A51%3A23.965Z&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A335750469596%3AiOSGoesWooooo-1335919882&Version=2010-03-31
Code that creates this incorrect string
exports.generatePayload = function(params, accessKeyId, secretKey, endpoint) {
var host = endpoint.replace(/.*:\/\//, "");
var payload = null;
var signer = new AWSV2Signer(accessKeyId, secretKey);
params = signer.sign(params, new Date(), {
"verb" : "POST",
"host" : host,
"uriPath" : "/"
});
var encodedParams = [];
for(var key in params) {
if(params[key] !== null) {
encodedParams.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
} else {
encodedParams.push(encodeURIComponent(key));
}
}
payload = encodedParams.join("&");
return payload;
}
I tried putting this in an array and restructure it but it didn't work for me.
Please advice how this can be done easily using JavaScript
exports.generatePayload = function(params, accessKeyId, secretKey, endpoint) {
var host = endpoint.replace(/.*:\/\//, "");
var payload = null;
var signer = new AWSV2Signer(accessKeyId, secretKey);
params = signer.sign(params, new Date(), {
"verb" : "POST",
"host" : host,
"uriPath" : "/"
});
var encodedParams = [];
if(params["AWSAccessKeyId"] != null)
{
encodedParams.push(encodeURIComponent("AWSAccessKeyId") + "=" + encodeURIComponent(params["AWSAccessKeyId"]));
}
if(params["AWSAccountId.member.1"] != null)
{
encodedParams.push(encodeURIComponent("AWSAccountId.member.1") + "=" + encodeURIComponent(params["AWSAccountId.member.1"]));
}
//other_ifs_for_param_keys_here
payload = encodedParams.join("&");
return payload;

Categories

Resources