How to generate oauth_signature intuit ipp QBO API V3 - c#

I am having some issues with limitations of the .NET SDK and so would like to issue my own calls to the API and parse the JSON results. I am stuck on creating the authorization header parameter oauth_signature as outlined here.
For this parameter it states: Contains the value generated by running all other request parameters and two secret values through a signing algorithm
Does the "two secret values" refer to the OAuthAccessTokenSecret and the consumerSecret?
Does "all other request parameters" mean just those parameter values? Concatenated?
How do you use 2 secret values in an and HMACSHA1 signing algorithm? All examples I see just use one
What I have so far.
public static string GetOAuthAuthorization(string oauthToken, string oauthSecret, string consumerKey, string consumerSecret)
{
string oauth_token = oauthToken;
string oauth_nonce = Guid.NewGuid().ToString();
string oauth_consumer_key = consumerKey;
string oauth_signature_method = "HMAC-SHA1";
int oauth_timestamp = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
string oauth_version="1.0";
string dataString = oauth_token + oauth_nonce + oauth_consumer_key + oauth_timestamp;
//TODO: use following to create oauth_signature
byte[] hashkey = Encoding.ASCII.GetBytes(oauthSecret); //is this one of the secret values?
byte[] data = Encoding.ASCII.GetBytes(dataString);
HMACSHA1 hmac = new HMACSHA1(hashkey);
byte[] result = hmac.ComputeHash(data);
string oauth_signature=Convert.ToBase64String(result);
return string.Format("OAuth oauth_token='{0}',oauth_nonce='{1}',oauth_consumer_key='{2}',oauth_signature_method='{3}',oauth_timestamp='{4}',oauth_version='{5}',oauth_signature='{6}'",
oauth_token, oauth_nonce, oauth_consumer_key, oauth_signature_method,oauth_timestamp,oauth_version, oauth_signature
);
}

Please check the sample app provided by Intuit for V3. This is already implemented. You can set in your keys and debug-
https://github.com/IntuitDeveloperRelations/
When you had generated an app with IPP, you must have got a consumer key and consumer secret.
That is what is being referred in the line you have mentioned.
https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started
For other questions, just debug the sample code after setting in your app keys in web.config, you will get the answers.

Related

ASP NET Core Twitter OAuth Request Token Issues

Background
I have a back end application that has a Twitter app setup and I can query and pull user tweet/post data. This is great, however, right now on the front end I don't have full Twitter integration setup. What I mean by this is that on the front end the user can enter any Twitter username and I want to know for sure that the Twitter username entered actually belongs to the user. With a Twitter application key you can pull public Twitter data for any twitter account which works well for large scale data ingestion and in my case proof of concept kind of work. At the point I am now, I need to have the assumption enforced in the back end that the data being analyzed for a particular Twitter screen name is also owned by the user of the account on my web application.
The proposed Twitter Solution
Here is a bunch of reference documentation I have been trying to follow.
https://developer.twitter.com/en/docs/basics/authentication/guides/log-in-with-twitter
https://developer.twitter.com/en/docs/basics/authentication/api-reference/request_token
https://oauth.net/core/1.0/#anchor9
https://oauth.net/core/1.0/#auth_step1
I have been trying to follow this and I have had different permutations to the code posted below (one without the callback URL as parameters, one with etc.) but at this point, not very different. I have not had any success and it's been more than a couple of days, which is killing me.
The code
This is my attempt to follow the OAuth specification proposed above in the documentation. Note that this is ASP.NET Core 2.2 + code. Also, this is the code for just Step 1 in the Twitter guide for OAuth authentication and authorization.
public async Task<string> GetUserOAuthRequestToken()
{
int timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
string nonce = Convert.ToBase64String(Encoding.ASCII.GetBytes(timestamp.ToString()));
string consumerKey = twitterConfiguration.ConsumerKey;
string oAuthCallback = twitterConfiguration.OAuthCallback;
string requestString =
twitterConfiguration.EndpointUrl +
OAuthRequestTokenRoute;
string parameterString =
$"oauth_callback={WebUtility.UrlEncode(twitterConfiguration.OAuthCallback)}&" +
$"oauth_consumer_key={twitterConfiguration.ConsumerKey}&" +
$"oauth_nonce={nonce}&" +
$"oauth_signature_method=HMAC_SHA1&" +
$"oauth_timestamp={timestamp}" +
$"oauth_version=1.0";
string signatureBaseString =
"POST&" +
WebUtility.UrlEncode(requestString) +
"&" +
WebUtility.UrlEncode(parameterString);
string signingKey =
twitterConfiguration.ConsumerSecret +
"&" + twitterConfiguration.AccessTokenSecret;
byte[] signatureBaseStringBytes = Encoding.ASCII.GetBytes(signatureBaseString);
byte[] signingKeyBytes = Encoding.ASCII.GetBytes(signingKey);
HMACSHA1 hmacSha1 = new HMACSHA1(signingKeyBytes);
byte[] signature = hmacSha1.ComputeHash(signatureBaseStringBytes);
string authenticationHeaderValue =
$"oauth_nonce=\"{nonce}\", " +
$"oauth_callback=\"{WebUtility.UrlEncode(twitterConfiguration.OAuthCallback)}\", " +
$"oauth_signature_method=\"HMAC_SHA1\", " +
$"oauth_timestamp=\"{timestamp}\", " +
$"oauth_consumer_key=\"{twitterConfiguration.ConsumerKey}\", " +
$"oauth_signature=\"{Convert.ToBase64String(signature)}\", " +
$"oauth_version=\"1.0\"";
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(
baseUri: new Uri(twitterConfiguration.EndpointUrl),
relativeUri: OAuthRequestTokenRoute);
request.Content = new FormUrlEncodedContent(
new Dictionary<string, string>() {
{ "oauth_callback", twitterConfiguration.OAuthCallback }
});
request.Headers.Authorization = new AuthenticationHeaderValue("OAuth",
authenticationHeaderValue);
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request);
if (httpResponseMessage.IsSuccessStatusCode)
{
return await httpResponseMessage.Content.ReadAsStringAsync();
}
else
{
return null;
}
}
Notes
I have tried to remove the callback URL from the parameters as well and that didn't work. I have tried all sort of slightly different permutations (urlencoded my signature, added the callback URL in the query string, removed it etc), but I have lost track at this point the one's I have tried and haven't (encodings, quotes etc.).
Ignore the fact that I am not serializing the response into a model yet as the goal is to first hit a success status code!
I have an integration test setup for this method as well and I keep getting 400 Bad Request with no additional information (which makes sense), but is absolutely not helping with debugging.
[Fact]
public async Task TwitterHttpClientTests_GetOAuthRequestToken_GetsToken()
{
var result = await twitterHttpClient.GetUserOAuthRequestToken();
Assert.NotNull(result);
}
As an aside I had some other questions as well:
Is there a way to verify a user's Twitter account without going
through the OAuth flow? The reason I ask this is because getting
through OAuth flow is proving to be difficult
Is it safe to do the first step of the Twitter login workflow on the back end and return the response to the front end? The response
would carry a sensitive token and token secret. (If I were to answer
this myself I would say you have to do it this way otherwise you
would have to hard code app secrets into front end configuration
which is worse). I ask this because this has been on my conscious
since I have started this and I'm worried a bit.
Is there an OAuth helper library for C# ASP.NET Core that can make this easier?
I solved this by writing unit tests and working through the Twitter documentation on Creating A Signature. Since that example provides keys and results, it's possible to verify that your code is correct.
Since you asked about libraries - I wrote LINQ to Twitter with the hope of helping others like myself with this difficult task.
In addition to to signature, the page navigation can be challenging as your code works through the OAuth flow. Please review the Twitter documentation on Obtaining user access tokens to understand this better. I've also documented this in the LINQ to Twitter Wiki on Securing your Applications. Here's how this will work with LINQ to Twitter:
First, I have an OAuthController with a Begin action to redirect a user to for kicking off the authentication process:
public async Task<ActionResult> Begin()
{
//var auth = new MvcSignInAuthorizer
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore(HttpContext.Session)
{
ConsumerKey = configuration["Twitter:ConsumerKey"],
ConsumerSecret = configuration["Twitter:ConsumerSecret"]
}
};
string twitterCallbackUrl = Request.GetDisplayUrl().Replace("Begin", "Complete");
return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
}
Notice that it's using an MvcSignInAuthorizer, passing in credentials via the CredentialStore property. If you were using your own raw code, you would be setting up the HTTP request with the Authorization header.
Next, notice that I'm modifying the current URL so that it will reference the same controller, but with the Complete endpoint. That is the oauth_callback that gets sent to Twitter authorization.
That process redirects the user to the Twitter web site, they authorize your app, and then it uses the oauth_callback to redirect the user back to your site. Here's how you handle that:
public async Task<ActionResult> Complete()
{
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore(HttpContext.Session)
};
await auth.CompleteAuthorizeAsync(new Uri(Request.GetDisplayUrl()));
// This is how you access credentials after authorization.
// The oauthToken and oauthTokenSecret do not expire.
// You can use the userID to associate the credentials with the user.
// You can save credentials any way you want - database,
// isolated storage, etc. - it's up to you.
// You can retrieve and load all 4 credentials on subsequent
// queries to avoid the need to re-authorize.
// When you've loaded all 4 credentials, LINQ to Twitter will let
// you make queries without re-authorizing.
//
//var credentials = auth.CredentialStore;
//string oauthToken = credentials.OAuthToken;
//string oauthTokenSecret = credentials.OAuthTokenSecret;
//string screenName = credentials.ScreenName;
//ulong userID = credentials.UserID;
//
return RedirectToAction("Index", "Home");
}
Again, you can see that I'm using MvcAuthorizer and completing the request. After completing the request, you'll be able to pull out the oauth_token and oauth_token_secret, as well as screen_name and user_id. You can save these artifacts and re-use them for all subsequent activity by this user, making their experience better because they don't have to log in every time you need to make a request.
On your question about verification, there is a Verify Credentials endpoint.
LINQ to Twitter has an ASP.NET Core Sample, API Samples with 100% API coverate, and full documentation on the Wiki if you want to learn more.
After hours and hours of going through the documentation I found the answer out. Turns out I missed some small details from the guides.
When making a request to oauth/request_token, when you sign the
request, you don't use the access token secret (for this specific request). Also, see the "Getting Signing Key" section of the signing a request guide and read the last few paragraphs. Therefore the signing key
does not have the access token secret
You must UrlEncode every single key and value. You must UrlEncode the authorization header as well.
I will post the updated code for you all here in case you need this in C#. Note that this code is not clean. You should separate OAuth functionality into some other class. This was my attempt to just get it to work.
public async Task<string> GetUserOAuthRequestToken()
{
int timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
string nonce = Convert.ToBase64String(Encoding.ASCII.GetBytes(timestamp.ToString()));
string consumerKey = twitterConfiguration.ConsumerKey;
string oAuthCallback = twitterConfiguration.OAuthCallback;
string requestString =
twitterConfiguration.EndpointUrl +
OAuthRequestTokenRoute;
string parameterString =
$"oauth_callback={WebUtility.UrlEncode(twitterConfiguration.OAuthCallback)}&" +
$"oauth_consumer_key={WebUtility.UrlEncode(twitterConfiguration.ConsumerKey)}&" +
$"oauth_nonce={WebUtility.UrlEncode(nonce)}&" +
$"oauth_signature_method={WebUtility.UrlEncode(OAuthSigningAlgorithm)}&" +
$"oauth_timestamp={WebUtility.UrlEncode(timestamp.ToString())}&" +
$"oauth_version={WebUtility.UrlEncode("1.0")}";
string signatureBaseString =
"POST&" +
WebUtility.UrlEncode(requestString) +
"&" +
WebUtility.UrlEncode(parameterString);
string signingKey =
WebUtility.UrlEncode(twitterConfiguration.ConsumerSecret) +
"&";
byte[] signatureBaseStringBytes = Encoding.ASCII.GetBytes(signatureBaseString);
byte[] signingKeyBytes = Encoding.ASCII.GetBytes(signingKey);
HMACSHA1 hmacSha1 = new HMACSHA1(signingKeyBytes);
byte[] signature = hmacSha1.ComputeHash(signatureBaseStringBytes);
string base64Signature = Convert.ToBase64String(signature);
string authenticationHeaderValue =
$"oauth_nonce=\"{WebUtility.UrlEncode(nonce)}\", " +
$"oauth_callback=\"{WebUtility.UrlEncode(twitterConfiguration.OAuthCallback)}\", " +
$"oauth_signature_method=\"{WebUtility.UrlEncode(OAuthSigningAlgorithm)}\", " +
$"oauth_timestamp=\"{WebUtility.UrlEncode(timestamp.ToString())}\", " +
$"oauth_consumer_key=\"{WebUtility.UrlEncode(twitterConfiguration.ConsumerKey)}\", " +
$"oauth_signature=\"{WebUtility.UrlEncode(base64Signature)}\", " +
$"oauth_version=\"{WebUtility.UrlEncode("1.0")}\"";
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(
baseUri: new Uri(twitterConfiguration.EndpointUrl),
relativeUri: OAuthRequestTokenRoute);
request.Headers.Authorization = new AuthenticationHeaderValue("OAuth",
authenticationHeaderValue);
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request);
if (httpResponseMessage.IsSuccessStatusCode)
{
string response = await httpResponseMessage.Content.ReadAsStringAsync();
return response;
}
else
{
return null;
}
}

Twitter HMACSHA1 Signature Creation C#

I am trying to implement Twitter sign in via C# & I am getting a 401 Unauthorized error - "Could not authenticate you" which isn't that helpful. To try to diagnose the problem I want to make sure that the signature creation is working correctly.
Twitter's documentation page for signature creation is here. I have written a simple unit test that should generate a signature based on the values specified in the documentation. However the test fails as I get a different signature string. Are the values in the documentation wrong or is is#t the code I'm using? However all the C# Twitter code I've seen uses similar hashing code.
[TestMethod]
public void TwitterSignatureCreation() {
var signingKey = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE";
var baseString = "POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%25";
var hmac = new HMACSHA1( Encoding.ASCII.GetBytes( signingKey ) );
var hash = hmac.ComputeHash( Encoding.ASCII.GetBytes( baseString ) );
var signatureString = Convert.ToBase64String( hash );
var expectedSignatureString = "hCtSmYh+iHYCEqBWrE7C7hYmtUk=";
Assert.AreEqual( expectedSignatureString, signatureString );
}
Assert.AreEqual failed.
Expected:<hCtSmYh+iHYCEqBWrE7C7hYmtUk=>.
Actual:<hOhJgzPMpZtXHCTeluIS1VdHUH8=>.

Get user's email from Twitter API for External Login Authentication ASP.NET MVC C#

I have checked a couple of related questions to find an answer to my question, but all to no avail. This question Can we get email ID from Twitter oauth API? got me as far as getting the Twitter support to allow the permission on my app below:
Using this doc as a guide and the marked answer's code (modifying it a little bit)
var resource_url = "https://api.twitter.com/1.1/account/verify_credentials.json";
var postBody = "include_email=true";//
resource_url += "?" + postBody;
to generate a signature and make a request to get the user's details from twitter results in 401 Unauthorized in my MVC app.
However, when I use the twitter signature generator tool to generate the authorization header and use fiddler to make a GET request to https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true, I get the email only once and I have to regenerate my app keys in twitter to get it again.
Is there a doc on how to generate a valid signature and make a valid request to retrieve the Twitter user email via .Net TwitterAuthentication?
After almost going bald from pulling all my hairs out of my head, I finally got it to work. I found out that the Signature base string was slightly different from the one generated with my code. After little tweaks, I was able to generate a valid signature base string.
In Startup.cs, I added access_token and access_secret as claims. I did not use the one found on my app because the users need to invoke a new one as they attempt to login or register:
var twitterOptions = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions()
{
ConsumerKey = ConfigurationManager.AppSettings["consumer_key"],
ConsumerSecret = ConfigurationManager.AppSettings["consumer_secret"],
Provider = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationProvider
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken));
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_secret", context.AccessTokenSecret));
return Task.FromResult(0);
}
},
BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
{
"A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
"0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
"7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
"39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
"‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
"4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
"5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
"B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA
}),
CallbackPath = new PathString("/twitter/account/ExternalLoginCallback")
};
app.UseTwitterAuthentication(twitterOptions);
And finally in my controller, I just called my helper class to get the name and email from twitter:
if (loginInfo.Login.LoginProvider.ToLower() == "twitter")
{
string access_token = loginInfo.ExternalIdentity.Claims.Where(x => x.Type == "urn:twitter:access_token").Select(x => x.Value).FirstOrDefault();
string access_secret = loginInfo.ExternalIdentity.Claims.Where(x => x.Type == "urn:twitter:access_secret").Select(x => x.Value).FirstOrDefault();
TwitterDto response = MyHelper.TwitterLogin(access_token, access_secret, ConfigurationManager.AppSettings["consumer_key"], ConfigurationManager.AppSettings["consumer_secret"]);
// by now response.email should possess the email value you need
}
Helper class method:
This was the section I tweaked in order to make a valid request:
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url)
+ "&" + Uri.EscapeDataString(request_query), "%26", Uri.EscapeDataString(baseString));
public static TwitterDto TwitterLogin(string oauth_token, string oauth_token_secret, string oauth_consumer_key, string oauth_consumer_secret)
{
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resource_url = "https://api.twitter.com/1.1/account/verify_credentials.json";
var request_query = "include_email=true";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url) + "&" + Uri.EscapeDataString(request_query), "%26", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", oauth_timestamp=\"{4}\", oauth_token=\"{5}\", oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
resource_url += "?include_email=true";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
WebResponse response = request.GetResponse();
return JsonConvert.DeserializeObject<TwitterDto>(new StreamReader(response.GetResponseStream()).ReadToEnd());
}
}
public class TwitterDto
{
public string name { get; set; }
public string email { get; set; }
}
This is all you need to get the twitter user's email. I hope it helps someone struggling with this. Please note that the steps mentioned in the question is also very important.
Updates version .netcore 3.1
It is very simple to implement the twitter API in .netcore compared to the solution above. First, you need to create an app on Twitter Create Twitter App
Supply all necessary information such as app name, description, websiteURL (https://example.com will do for local development), and so on. For your callback url, provide the local url you are using. In my case, https://localhost:44318/signin-twitter and ensure that you tick "request email address from users" save and then regenerate the consumer API Keys under the "Keys and tokens" tab see image below:
After you are done with the Twitter administration,
Install the nuget package in your solution in Visual Studio:
Install-Package Microsoft.AspNetCore.Authentication.Twitter
Update your .NetCore Application Startup Class (ConfigureServices method) in visual studio to initialize the Twitter Authentication mechanism with the code below:
services.AddAuthentication().AddTwitter(options =>
{
options.ConsumerKey = twitterConsumerApiKey;
options.ConsumerSecret = twitterConsumerSecretKey;
options.RetrieveUserDetails = true;
}); // twitterConsumerApiKey and twitterConsumerSecretkey can be found under the "Keys and tokens" tab of the Twitter App previously created.
The process is complete and you should be able to get emails of users upon authentication. For more information check out Twitter external sign-in setup with ASP.NET Core
you have to change your code to call the GET account/verify_credentials method after the user is logged in with twitter. And it is important to set the parameter include_email to true. When this is set to true email will be returned in the user objects as a string.
I'm using this library https://www.nuget.org/packages/linqtotwitter
so that I do not have to write code for handling twitter api requests
var twitterCtx = new TwitterContext(authTwitter);
var verifyResponse = await
(from acct in twitterCtx.Account
where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
select acct)
.SingleOrDefaultAsync();
see how I have done this here
http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
it is an easy and clean solution

Could you explain the little difference between my two hash?

I'm trying to implement a WCF OAuth restful Web API service.
Without knowing the code could you explain the little difference between my two hash:
dictionary["oauth_signature"] "URirekG5i5MbWxoinc4bi4H8j1g%3D" string
hash "URirekG5i5MbWxoinc4bi4H8j1g=" string
I use RESTClient (firefox addon) to test my WCF OAuth restful Web API service. I followed this article.
It seems something is added to the end of dictionary["oauth_signature"] or something is missing in my generated hash. But what?
if (dictionary["oauth_consumer_key"] != null)
{
// to get uri without oauth parameters
string uri = context.UriTemplateMatch.RequestUri.ToString();
string consumersecret = "suryabhai";
OAuthBase oauth = new OAuthBase();
string hash = oauth.GenerateSignature(
new Uri(uri),
dictionary["oauth_consumer_key"],
consumersecret,
null, // totken
null, //token secret
"GET",
dictionary["oauth_timestamp"],
dictionary["oauth_nonce"],
out normalizedUrl,
out normalizedRequestParameters
);
Authenticated = dictionary["oauth_signature"] == hash;
}
return Authenticated;
Somewhere in your application, your hash got URL encoded. That means that the = sign, a special character in URLs, was encoded to %3D. If you decode it, they will match.

Azure ACS Credential Confusion

I downloaded the source for this project http://code.msdn.microsoft.com/windowsazure/MVC4-Web-API-With-SWT-232d69da#content because I am trying to understand ACS authentication and how to apply it in my MVC Web API.
The code has this:
// USE CONFIGURATION FILE, WEB.CONFIG, TO MANAGE THIS DATA
static string serviceNamespace = "<YOUR SERVICE NAMESPACE>";
static string acsHostUrl = "accesscontrol.windows.net";
static string realm = "<REALM>";
static string uid = "USERNAME";
static string pwd = "PASSWORD";
static string serviceUrl = "http://localhost:51388/api";
static string serviceAction = #"/values";
What USERNAME and PASSWORD is it requesting that I use? Does it want me to create a "Service Identity" and use the "password" option?
You need to read the associated article found at: http://blogs.msdn.com/b/alikl/archive/2011/06/05/how-to-request-swt-token-from-acs-and-how-to-validate-it-at-the-rest-wcf-service-hosted-in-windows-azure.aspx follow the steps to Configure ACS to Issue a SWT Token. The information you enter when completing the section "To configure a service identity for the REST web service" is what goes here.
If you are using a Symmetric key for your password then you need the client to request a token from ACS in a different way than the example. The following code is an example of what that request looks like and was taken from http://msdn.microsoft.com/en-us/library/hh674475.aspx. See the section "SWT token requests".
WebClient client = new WebClient();
client.BaseAddress = string.Format("https://mysnservice.accesscontrol.windows.net");
NameValueCollection values = new NameValueCollection();
// add the wrap_scope
values.Add("wrap_scope", "http://mysnservice.com/services");
// add the format
values.Add("wrap_assertion_format", "SWT");
// add the SWT
values.Add("wrap_assertion", "Issuer=mysncustomer1&HMACSHA256=b%2f%2bJFwbngGdufECFjQb8qhb9YH0e32Cf9ABMDZFiPPA%3d");
// WebClient takes care of the remaining URL Encoding
byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
// the raw response from ACS
string response = Encoding.UTF8.GetString(responseBytes);

Categories