Skip to content

Instantly share code, notes, and snippets.

@bthubbard
Created October 5, 2012 01:00
Show Gist options
  • Save bthubbard/3837451 to your computer and use it in GitHub Desktop.
Save bthubbard/3837451 to your computer and use it in GitHub Desktop.
Windows 8 Evernote oAuth Example
/*
Quick and dirty code strung together from an Evernote example which used ReactiveOAuth and the MSFT examples.
*/
public sealed partial class Authenication : YourApp.Common.LayoutAwarePage
{
private const string parametersQueryString = @"/oauth?oauth_consumer_key={0}&oauth_signature={1}&oauth_signature_method=PLAINTEXT&oauth_timestamp={2}&oauth_nonce={3}";
private const string callBackUrl = "http://localhost/YouApp";
private const string oAuthToken = "oauth_token";
private string postResponse;
public Authenication()
{
this.InitializeComponent();
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
protected override void SaveState(Dictionary<String, Object> pageState)
{
}
private async Task<String> SendData(string evernoteUrl)
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(evernoteUrl);
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse) await Request.GetResponseAsync();
StreamReader ResponseDataStream = new StreamReader(Response.GetResponseStream());
return ResponseDataStream.ReadToEnd();
}
private string TimeSinceEpoch()
{
var sinceEpoch = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
return Math.Round(sinceEpoch.TotalSeconds).ToString();
}
private async void Authenticate()
{
var temporaryCredentialRequest = SetupOAuthUrl() + "&oauth_callback=" + Uri.EscapeDataString(callBackUrl);
postResponse = await SendData(temporaryCredentialRequest);
if (!string.IsNullOrWhiteSpace(postResponse))
{
var splitted = SplitOAuthResponseAndGetOAuthToken(postResponse);
string token = splitted[oAuthToken];
string secondoAuthUrl = ResourceManager.Current.MainResourceMap.GetValue("Settings/EvernoteBaseUrl").ValueAsString
+ "/OAuth.action?oauth_token=" + token;
var startUrl = new Uri(secondoAuthUrl);
var endUrl = new Uri(callBackUrl);
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUrl, endUrl);
if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
string payload = webAuthenticationResult.ResponseData.ToString();
var tokenishStuff = SplitOAuthResponseAndGetOAuthToken(payload.Substring(payload.IndexOf('?') + 1));
token = tokenishStuff[oAuthToken];
var verifier = tokenishStuff["oauth_verifier"];
string accessTokenRequest = SetupOAuthUrl() + "&oauth_token=" + token + "&oauth_verifier=" + verifier;
postResponse = await SendData(accessTokenRequest);
if (!string.IsNullOrWhiteSpace(postResponse))
{
splitted = SplitOAuthResponseAndGetOAuthToken(postResponse);
string userCredentialID = Uri.UnescapeDataString(splitted[oAuthToken]);
string noteUrl = Uri.UnescapeDataString(splitted["edam_noteStoreUrl"]);
string userId = Uri.UnescapeDataString(splitted["edam_userId"]);
//Do something with them now..
}
}
else
{
// something bad happened or the user cancelled.
}
}
}
private Dictionary<string, string> SplitOAuthResponseAndGetOAuthToken(string response)
{
var splitted = response.Split('&').Select(s => s.Split('=')).ToDictionary(s => s.First(), s => s.Last());
return splitted;
}
private string SetupOAuthUrl()
{
var rand = new Random();
var nonce = rand.Next(1000000000);
var temporaryCredentialRequest = ResourceManager.Current.MainResourceMap.GetValue("Settings/EvernoteBaseUrl").ValueAsString
+ string.Format(
parametersQueryString,
ResourceManager.Current.MainResourceMap.GetValue("Settings/ConsumerKey").ValueAsString,
Uri.EscapeDataString(ResourceManager.Current.MainResourceMap.GetValue("Settings/ConsumerSecret").ValueAsString + "&"),
this.TimeSinceEpoch(),
nonce.ToString());
return temporaryCredentialRequest;
}
private void Authenticate_Click(object sender, RoutedEventArgs e)
{
this.Authenticate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment