Google Contacts Api - 401 error when access User Contact - google-oauth

I am using oauth 1.0 and until now I can successfully get the Access Token from Google.
But when I want to retrieve user contacts from https://www.google.com/m8/feeds/contacts/default/full, it return 401 error and no further explanation.
I find that the information form Google playground may not be really accurate, for example the signature base string in step 3 and step 5 include oauth_version but it is wrong. (If you include oauth_version, it will return signature_invalid and oauth_version is not included )
This is my request :
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbGetContacts.ToString());
req.Method = "GET";
req.Headers.Add(authHeader);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
This is my header:
string authHeader = "Authorization: OAuth " +
"oauth_version=" + "\"" + "1.0" + "\"" + "\"," +
"oauth_nonce=" + "\"" + nonce + "\"," +
"oauth_timestamp=" + "\"" + timeStamp + "\"," +
"oauth_consumer_key=" + "\"" + GoogleconsumerKey + "\"," +
"oauth_token=" + "\"" + OauthToken+ "\"," +
"oauth_signature_method=" + "\"" + "HMAC-SHA1" + "\"," +
"oauth_signature=" + "\"" + UpperCaseUrlEncode(sig) + "\"";
Can anyone tell me how to fix the problem ?

OAuth1 is deprecated (by Google). Please don't spend any energy writing new code using OAuth1. With OAuth2 there are no signatures and crypto.
Is there a reason you need to use OAuth1? We would like to know. I work on OAuth at Google.

Actually:
If your application has certain unusual authorization requirements,
such as logging in at the same time as requesting data access (hybrid)
or domain-wide delegation of authority (2LO), then you cannot
currently use OAuth 2.0 tokens. In such cases, you must instead use
OAuth 1.0 tokens and an API key. You can find your application's API
key in the Google API Console, in the Simple API Access section of the
API Access pane.
According to https://developers.google.com/google-apps/contacts/v3/?hl=fr
So you need to pass an API key. You can do this be adding key='YOUR_API_KEY' to the URL
but how do you pass an API key if you are using a gdata client library?

Related

jira api - how to update fields on a jira issue that is closed/published

the following code works fine on a jira issue that is in open. but when this is tried on a closed/published issue i get error. wanted to see if this is even possible to be done? manually on closed/published jira issue, we can update those fields
Client client = Client.create();
WebResource webResource = client.resource("https://jira.com/rest/api/latest/issue/JIRA_KEY1");
String data1 = "{\r\n" +
" \"fields\" : {\r\n" +
" \"customfield_10201\" : \"Value 1\"\r\n" +
" }\r\n" +
"}";
String auth = new String(Base64.encode("user" + ":" + "pass"));
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").put(ClientResponse.class, data1);
Error received
Http Error : 400{"errorMessages":[],"errors":{"customfield_10201":"Field 'customfield_10201' cannot be set. It is not on the appropriate screen, or unknown."}}
There is probably a restriction that doesn't allow the value of that field to be changed once the issue is marked as complete.
Try opening that completed issue via the web interface and changing the field's value; if you can't do it via the web interface, then you can't do it the REST API.

PUT blob with Blob Service API in Postman - Authorization header

I need help constructing the Authorization header to PUT a block blob.
PUT\n\n\n11\n\n\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Sat, 25 Feb 2017 22:20:13 GMT\nx-ms-version:2015-02-21\n/myaccountname/mycontainername/blob.txt\n
I take this, UTF 8 encode it. Then I take my access key in my Azure account and HMAC sha256 this UTF 8 encoded string with the key. Then I output that in base64. Let's call this output string.
My authorization header looks like this: SharedKey myaccountname:output string
It is not working.
The header in Postman also has x-ms-blob-type, x-ms-date, x-ms-version, Content-Length, and Authorization. The body for now says hello world.
Can anyone help me make this successful request in Postman?
<?xml version="1.0" encoding="utf-8"?>
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:cdeb9a5e-0001-0029-5fb5-8f7995000000
Time:2017-02-25T22:22:32.0300016Z</Message>
<AuthenticationErrorDetail>The MAC signature found in the HTTP request 'jiJtirohvi1syXulqkPKESnmQEJI4GpDU5JBn7BM/xY=' is not the same as any computed signature. Server used following string to sign: 'PUT
11
text/plain;charset=UTF-8
x-ms-date:Sat, 25 Feb 2017 22:20:13 GMT
x-ms-version:2015-02-21
/myaccountname/mycontainername/blob.txt'.</AuthenticationErrorDetail>
</Error>
EDIT:
First, I want to thank you and everyone who responded. I truly truly appreciate it. I have one last question and then I think I'll be set!! I'm not using that code - I'm doing this all by hand. If I have my key: X2iiy6v47j1jZZH5555555555zzQRrIAdxxVs55555555555av8uBUNGcBMotmS7tDqas14gU5O/w== changed slightly for anonymity - do I decode it: using an online base64decoder. Then, when I have my string which now looks like this: PUT\n\n\n11\n\ntext/plain;charset=UTF-8\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Mon, 27 Feb 2017 21:53:13 GMT\nx-ms-version:2015-02-21\n/myaccount/mycontainer/blob.txt\n so I run this in https://mothereff.in/utf-8 and then use this in HMAC with my decoded key: https://www.liavaag.org/English/SHA-Generator/HMAC/ - using sha256 and base64 at the end.
Is that how I get the correct string to put here?: SharedKey myaccount:<string here>
I believe there's an issue with how you're specifying StringToSign here:
PUT\n\n\n11\n\n\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Sat,
25 Feb 2017 22:20:13
GMT\nx-ms-version:2015-02-21\n/myaccountname/mycontainername/blob.txt\n
If you notice the error message returned from the server, string to sign by server is different than yours and the difference is that the server is using Content-Type (text/plain;charset=UTF-8) in signature calculation while you're not. Please include this content type in your code and things should work just fine.
Here's the sample code (partial only) I used:
var requestMethod = "PUT";
var urlPath = "test" + "/" + "myblob.txt";
var storageServiceVersion = "2015-12-11";
var date = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
var blobType = "BlockBlob";
var contentBytes = Encoding.UTF8.GetBytes("Hello World");
var canonicalizedResource = "/" + accountName + "/" + urlPath;
var canonicalizedHeaders = "x-ms-blob-type:" + blobType + "\nx-ms-date:" + date + "\nx-ms-version:" + storageServiceVersion + "\n";
var stringToSign = requestMethod + "\n" +
"\n" + //Content Encoding
"\n" + //Content Language
"11\n" + //Content Length
"\n" + //Content MD5
"text/plain;charset=UTF-8" + "\n" + //Content Type
"\n" + //Date
"\n" + //If - Modified - Since
"\n" + //If - Match
"\n" + //If - None - Match
"\n" + //If - Unmodified - Since
"\n" + //Range +
canonicalizedHeaders +
canonicalizedResource;
string authorizationHeader = GenerateSharedKey(stringToSign, accountKey, accountName);
private static string GenerateSharedKey(string stringToSign, string key, string account)
{
string signature;
var unicodeKey = Convert.FromBase64String(key);
using (var hmacSha256 = new HMACSHA256(unicodeKey))
{
var dataToHmac = Encoding.UTF8.GetBytes(stringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
return string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", "SharedKey", account, signature);
}
According to your error message, it indicates that authorization signature is incorrect.
If the Content-Type "text/plain; charset=UTF-8" is not included in the header, please add it in the stringTosign and postman.
When we try to get the signature, we need to make sure the length of the blob.txt matches the Content length in the stringTosign. That means request body length should match the content length in the stringTosign.
I test it with Postman, it works correctly. We can get the signature with the code in another SO Thread. The following is my detail steps
Add the following header
Add the request body (example: Hello World)
Send the put blob request.
Update :
Please have a try to use the online tool to generate signature for test.

OneDrive API help in getting download link of file

I need to get download URL of the file using OneDrive API.
This works
string url = "https://apis.live.net/v5.0/" + FILE_ID + "/shared_read_link?access_token=" + AUTH_TOKEN
but this doesn't
string url = "https://apis.live.net/v5.0/" + FILE_ID + "/content?suppress_redirects=true?access_token=" + AUTH_TOKEN;
Its throwing error, unauthorized.. can someone tell why?
Thanks
Sujit
& should have been used in place of ?. So correct answer is
string url = "https://apis.live.net/v5.0/" + FILE_ID + "/content?suppress_redirects=true&access_token=" + AUTH_TOKEN;

Signature did not match. String to sign used was r

Trying to Construct a Shared Access Signature URI for a Blob access in a container
BlobHelper BlobHelper = new BlobHelper(StorageAccount, StorageKey);
string signature = "";
string signedstart = DateTime.UtcNow.AddMinutes(-1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
string signedexpiry = DateTime.UtcNow.AddMinutes(2).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
//// SET CONTAINER LEVEL ACCESS POLICY
string accessPolicyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<SignedIdentifiers>\n" +
" <SignedIdentifier>\n" +
" <Id>twominutepolicy</Id>\n" +
" <AccessPolicy>\n" +
" <Start>" + signedstart + "</Start>\n" +
" <Expiry>" + signedexpiry + "</Expiry>\n" +
" <Permission>r</Permission>\n" +
" </AccessPolicy>\n" +
" </SignedIdentifier>\n" +
"</SignedIdentifiers>\n";
BlobHelper.SetContainerAccessPolicy("xxxxxxx", "container", accessPolicyXml));
string canonicalizedresource = "/xxxxxxx/501362787";
string StringToSign = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}",
"r",
signedstart,
signedexpiry,
canonicalizedresource,
"twominutepolicy",
"2013-08-15",
"rscc",
"rscd",
"rsce",
"rscl",
"rsct"
);
using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageKey)))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
StringBuilder sasToken = new StringBuilder();
sasToken.Append(BlobHelper.DecodeFrom64(e.Item.ToolTip).ToString().Replace("http","https") + "?");
//signedversion
sasToken.Append("sv=2013-08-15&");
sasToken.Append("sr=b&");
//
sasToken.Append("si=twominutepolicy&");
sasToken.Append("sig=" + signature + "&");
//
sasToken.Append("st=" + HttpUtility.UrlEncode(signedstart).ToUpper() + "&");
//
sasToken.Append("se=" + HttpUtility.UrlEncode(signedexpiry).ToUpper() + "&");
//
sasToken.Append("sp=r");
string url = sasToken.ToString();
I am getting the following exception below
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:e424e1ac-fd96-4557-866a-992fc8c41841 Time:2014-05-22T18:46:15.3436786Z</Message>
<AuthenticationErrorDetail>Signature did not match. String to sign used was r 2014-05-22T18:45:06Z 2014-05-22T18:48:06Z /xxxxxxx/501362787/State.SearchResults.pdf twominutepolicy 2013-08-15 </AuthenticationErrorDetail>
</Error>
rscc, rscd, rsce, rscl, rsct are placeholders for overridden response headers. Your sasToken variable does not seem to override response headers, so you should just use empty strings with a new-line character when signing them. Moreover, it looks like your canonicalized resource also does not match the server's resource.
By the way, did you look at Azure Storage Client Library to create Shared Access Signature tokens? It provides lots of features and is the official SDK to access Microsoft Azure Storage.

CryptoJS (HMAC Sha256) giving incorrect output?

Let me start by saying I'm no expert in cryptography algorithms...
I am trying to build a method which formats an HTTP header for Windows Azure - and this header requires part of its message to be encrypted via HMAC with SHA256 (and then also base64 encoded).
I chose to use CryptoJS because it's got an active user community.
First, my code:
_encodeAuthHeader : function (url, params, date) {
//http://msdn.microsoft.com/en-us/library/windowsazure/dd179428
var canonicalizedResource = '/' + this.getAccountName() + url;
/*
StringToSign = Date + "\n" + CanonicalizedResource
*/
var stringToSign = date + '\n' + canonicalizedResource;
console.log('stringToSign >> ' + stringToSign)
var encodedBits = CryptoJS.HmacSHA256(stringToSign, this.getAccessKey());
console.log('encodedBits >> ' + encodedBits);
var base64Bits = CryptoJS.enc.Base64.stringify(encodedBits);
console.log('base64Bits >> ' + base64Bits);
var signature = 'SharedKeyLite ' + this.getAccountName() + ':' + base64Bits;
console.log('signature >> ' + signature);
return signature;
},
The method successfully returns a "signature" with the appropriate piece encrypted/encoded. However, Azure complains that it's not formatted correctly.
Some example output:
stringToSign >> Mon, 29 Jul 2013 16:04:20 GMT\n/senchaazurestorage/Tables
encodedBits >> 6723ace2ec7b0348e1270ccbaab802bfa5c1bbdddd108aece88c739051a8a767
base64Bits >> ZyOs4ux7A0jhJwzLqrgCv6XBu93dEIrs6IxzkFGop2c=
signature >> SharedKeyLite senchaazurestorage:ZyOs4ux7A0jhJwzLqrgCv6XBu93dEIrs6IxzkFGop2c=
Doing some debugging, I am noticing that CryptoJS is not returning the same value (HMAC with SHA256) as alternative implementations. For example, the string "Mon, 29 Jul 2013 16:04:20 GMT\n/senchaazurestorage/Tables" appears as:
"6723ace2ec7b0348e1270ccbaab802bfa5c1bbdddd108aece88c739051a8a767" via CryptoJS
"faa89f45ef029c63d04b8522d07c54024ae711924822c402b2d387d05398fc9f" via PHP hash_hmac('sha256', ... )
Digging even deeper, I'm seeing that most HMAC/SHA265 algorithms return data which matches the output from PHP... am I missing something in CryptoJS? Or is there a legitimate difference?
As I mentioned in my first comment, the newline ("\n") was causing problems. Escaping that ("\ \n", without the space inbetween) seems to have fixed the inconsistency in HMAC/SHA256 output.
I'm still having problems with the Azure HTTP "Authorization" header, but that's another issue.