I have worked with OAuth before (working with Twitter and PHP) and it was simple. I am trying to get OAuth to work with the EverNote API sample https://github.com/evernote/evernote-sdk-csharp (because, as they say, "Real applications authenticate with Evernote using OAuth"). I looked at these:
Simple C# Evernote API OAuth example or guide?
https://github.com/sethhitch/csharp-oauth-sample
http://blog.stevienova.com/2008/04/19/oauth-getting-started-with-oauth-in-c-net/
But, I still don't know how to do this... This is my code:
// Real applications authenticate with Evernote using OAuth, but for the
// purpose of exploring the API, you can get a developer token that allows
// you to access your own Evernote account. To get a developer token, visit
// https://sandbox.evernote.com/api/DeveloperToken.action
String authToken = "myAuthCode";
if (authToken == "your developer token") {
Console.WriteLine("Please fill in your developer token");
Console.WriteLine("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action");
return;
}
How can I add OAuth to this to get my authToken?
Thank you.
Check this sample project : http://discussion.evernote.com/topic/30584-here-is-a-net-oauth-assembly/ . I think this will help you to understand how oauth works.
For anyone trying to get this to work in MVC, I was playing around with Evernote, OpenAuth and C# this morning and managed to get it all working. I have put together a blog post / library explaining the experience and outlining how to do it with MVC here - http://www.shaunmccarthy.com/evernote-oauth-csharp/ - it uses the AsyncOAuth library: https://github.com/neuecc/AsyncOAuth
I wrote a wrapper around AsyncOAuth that you might find useful here: https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
One prickly thing to be aware of - the Evernote Endpoints (/oauth and /OAuth.action) are case sensitive
// Download the library from https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
// Configure the Authorizer with the URL of the Evernote service,
// your key, and your secret.
var EvernoteAuthorizer = new EvernoteAuthorizer(
"https://sandbox.evernote.com",
"slyrp-1234", // Not my real id / secret :)
"7acafe123456badb123");
// First of all, get a request token from Evernote - this causes a
// webrequest from your server to Evernote.
// The callBackUrl is the URL you want the user to return to once
// they validate the app
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);
// Persist this token, as we are going to redirect the user to
// Evernote to Authorize this app
Session["RequestToken"] = requestToken;
// Generate the Evernote URL that we will redirect the user to in
// order to
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);
// Redirect the user (e.g. MVC)
return Redirect(callForwardUrl);
// ... Once the user authroizes the app, they get redirected to callBackUrl
// where we parse the request parameter oauth_validator and finally get
// our credentials
// null = they didn't authorize us
var credentials = EvernoteAuthorizer.ParseAccessToken(
Request.QueryString["oauth_verifier"],
Session["RequestToken"] as RequestToken);
// Example of how to use the credential with Evernote SDK
var noteStoreUrl = EvernoteCredentials.NotebookUrl;
var noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
var noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
var noteStore = new NoteStore.Client(noteStoreProtocol);
List<Notebook> notebooks = client.listNotebooks(EvernoteCredentials.AuthToken);
You can also try the OAuth library found here : https://code.google.com/p/devdefined-tools/wiki/OAuth and follow the steps mentioned here.
The simple code to add is:
EvernoteOAuth oauth = new EvernoteOAuth(EvernoteOAuth.HostService.Sandbox, myConsumerKey, myConsumerSecret);
string errResponse = oauth.Authorize();
if (errResponse.Length == 0)
{
Console.WriteLine(string.Format("Token: {0}\r\n\r\nExpires: {1}\r\n\r\nNoteStoreUrl: {2}\r\n\r\nUserId: {3}\r\n\r\nWebApiUrlPrefix: {4}", oauth.Token, oauth.Expires, oauth.NoteStoreUrl, oauth.UserId, oauth.WebApiUrlPrefix));
}
else
{
Console.WriteLine("A problem has occurred in attempting to authorize the use of your Evernote account: " + errResponse);
}
You will need to use this assembly:
using EvernoteOAuthNet;
Available here:
http://www32.zippyshare.com/v/98249023/file.html
Related
Hello I am trying to get user info like name and address in an Xamarin app using Azure AD B2C for authentication.
So far I've gotten the authentication working fine
public async Task<MobileServiceUser> LoginAsync(MobileServiceClient client, MobileServiceAuthenticationProvider provider)
{
try
{
//login and save user status
var user = await client.LoginAsync(Forms.Context, provider);
Settings.AuthToken = user?.MobileServiceAuthenticationToken ?? string.Empty;
Settings.UserId = user?.UserId ?? string.Empty;
return user;
}
catch (Exception e)
{
}
return null;
}
However I would like to know how to get the user's name and birthday. I haven't been able to find a clear course of action for that.
You do not explicitly get this information using the MobileService SDK. Check out the complete documentation about App Service Authentication/Authorization here.
You will reach the point where it mentions:
Your application can also obtain additional user details through an
HTTP GET on the /.auth/me endpoint of your application. A valid token
that's included with the request will return a JSON payload with
details about the provider that's being used, the underlying provider
token, and some other user information. The Mobile Apps server SDKs
provide helper methods to work with this data.
So, in your Xamarin, after the user is successfully authentication, you have to explicitly make a HTTP GET request to /.auth/me and parse the result to get all information about the logged-in user.
Not sure how to do this in Xamarin, but here is how to do it in C# UWP (Universal Windows Platform):
var url = App.MobileService.MobileAppUri + "/.auth/me";
var clent = new Windows.Web.Http.HttpClient();
clent.DefaultRequestHeaders.Add("X-ZUMO-AUTH", this.user.MobileServiceAuthenticationToken);
var userData = await clent.GetAsync(new Uri(url));
at the of this code execution, the userData varibale will be a JSON srting with all user's claims.
Basically what I'm trying to do is to get recent tweets from a user and do stuff with them. I'm using Tweetinvi with PIN-based authentication, as described on the website, like this:
// Create a new set of credentials for the application
var appCredentials = new TwitterCredentials("CONSUMER_KEY", "CONSUMER_SECRET");
// Go to the URL so that Twitter authenticates the user and gives him a PIN code
var url = CredentialsCreator.GetAuthorizationURL(appCredentials);
// This line is an example, on how to make the user go on the URL
Process.Start(url);
// Ask the user to enter the pin code given by Twitter
var pinCode = Console.ReadLine();
// With this pin code it is now possible to get the credentials back from Twitter
var userCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(pinCode, appCredentials);
// Use the user credentials in your application
Auth.SetCredentials(userCredentials);
Now the problem is that I have to sign in and connect to Twitter every time I launch my application via browser, which is mildly annoying. I've tried to save my authentication details in a text file (Consumer Key, Consumer Secret, Access Token, Access Token Secret), and then just insert the info into appCredentials and userCredentials, but with no results, as I keep getting TwitterNullCredentialsException. So how do I save my credentials so that I don't have to reconnect on every launch?
I am the main developer of Tweetinvi.
If you store the 4 credentials information you can then reuse them with 2 different solutions :
Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
// OR
var creds = new TwitterCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
Auth.SetCredentials(creds);
The documentation might help you set up your application : https://github.com/linvi/tweetinvi/wiki/Introduction
I have wpf desktop application and I want Facebook login integration in this application so that users can share images from local machine, moreover I am using "Facebook.7.0.6" sdk. Apparently I am facing following issue on login screen.
Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
And below coding I am using in my application.
private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
// for .net 3.5
// var parameters = new Dictionary<string,object>
// parameters["client_id"] = appId;
dynamic parameters = new ExpandoObject();
parameters.client_id = appId;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
return fb.GetLoginUrl(parameters);
}
void facebookBrowser_Navigated(Object sender,NavigationEventArgs e)
{
var fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if (!fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
return;
if (oauthResult.IsSuccess)
LoginSucceeded(oauthResult);
}
Note : Let me know if Facebook have any change in term and condition for desktop application.
Thanks
After some study I got this link and now my application working fine.
Please set below settings on Facebook app first.
Native or desktop app? - Yes
Client OAuth login - Yes
Embedded browser OAuth Login - Yes
read more from this link :-https://www.hackviking.com/2014/11/facebook-api-login-flow-for-desktop-application/
Thanks
This error means you haven't configured well you app on facebook
If you are testing on localhost, you need to add a platform to your app, then configuring the "site url" for the example http://localhost. Then create a test app (a copy of your main app) and use it for your tests.
I need to validate a Google ID token passed from a mobile device at my ASP.NET web api.
Google have some sample code here but it relies on a JWT NuGet package which is .Net 4.5 only (I am using C#/.Net 4.0). Is anyone aware of any samples which do this without these packages or has achieved this themselves? The use of the package makes it very difficult to work out what I need to do without it.
According to this github issue, you can now use GoogleJsonWebSignature.ValidateAsync method to validate a Google-signed JWT. Simply pass the idToken string to the method.
var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken);
Assert.NotNull(validPayload);
If it is not a valid one, it will return null.
Note that to use this method, you need to install Google.Apis.Auth nuget firsthand.
The challenge is validating the JWT certificate in the ID token. There is currently not a library I'm aware of that can do this that doesn't require .Net 4.5 and until there is a solution for JWT validation in .NET 4.0, there will not be an easy solution.
However, if you have an access token, you can look into performing validation using oauth2.tokeninfo. To perform basic validation using token info, you can do something like the following:
// Use Tokeninfo to validate the user and the client.
var tokeninfo_request = new Oauth2Service().Tokeninfo();
tokeninfo_request.Access_token = _authState.AccessToken;
var tokeninfo = tokeninfo_request.Fetch();
if (userid == tokeninfo.User_id
&& tokeninfo.Issued_to == CLIENT_ID)
{
// Basic validation succeeded
}
else
{
// The credentials did not match.
}
The information returned from the Google OAuth2 API tells you more information about a particular token such as the client id it was issued too as well as its expiration time.
Note You should not be passing around the access token but instead should be doing this check after exchanging a one-time code to retrieve an access token.
ClientId also needs to be passed, which should be set from Google API Console. If only pass TokenId, GoogleJsonWebSignature throws error. This answer is in addition to #edmundpie answer
var settings = new GoogleJsonWebSignature.ValidationSettings()
{
Audience = new List<string>() { "[Placeholder for Client Id].apps.googleusercontent.com" }
};
var validPayload = await GoogleJsonWebSignature.ValidateAsync(model.ExternalTokenId, settings);
I wonder of someone know a working sample of logging in using Twitter (OAuth) for .NET
I'm currently using this one http://www.voiceoftech.com/swhitley/?p=681
but it only works if I set the callback url to "oob", if I set a real callback url I get "401 unauthorized".
Thanks!
I wrote an OAuth manager for this, because the existing options were too complicated.
OAuth with Verification in .NET
The class focuses on OAuth, and works specifically with Twitter. This is not a class that exposes a ton of methods for the entire surface of Twitter's web API. It is just OAuth. If you want to update status on Twitter, this class exposes no "UpdateStatus" method. I figured it's a simple matter for app designers to construct the HTTP message they want to send. In other words the HTTP message is the API. But the OAuth stuff can get a little complicated, so that deserves an API, which is what the OAuth class is.
Here's example code to request a "request token":
var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_CONSUMER_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_CONSUMER_SECRET;
oauth.AcquireRequestToken(SERVICE_SPECIFIC_REQUEST_TOKEN_URL, "POST");
THAT'S IT. In Twitter, the service-specific URL for requesting tokens is "https://api.twitter.com/oauth/request_token".
Once you get the request token, you pop the web browser UI in which the user will explicitly grant approval to your app, to access Twitter. You need to do this once, the first time the app runs. Do this in an embedded WebBrowser control, with code like so:
var url = SERVICE_SPECIFIC_AUTHORIZE_URL_STUB + oauth["token"];
webBrowser1.Url = new Uri(url);
For Twitter, the URL for this is "https://api.twitter.com/oauth/authorize?oauth_token=" with the oauth_token appended.
Grab the pin from the web browser UI, via some HTML screen scraping. Then request an "access token":
oauth.AcquireAccessToken(URL_ACCESS_TOKEN,
"POST",
pin);
For Twitter, that URL is "https://api.twitter.com/oauth/access_token".
You don't need to explicitly handle the access token; the OAuthManager class maintains it in state for you. But the token and secret are available in oauth["token"] and oauth["token_secret"], in case you want to write them off to permanent storage. To make requests with that access token, generate the authz header like this:
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
...where url is the resource endpoint. To update the user's status on Twitter, it would be "http://api.twitter.com/1/statuses/update.xml?status=Hello".
Then set the resulting string into the HTTP Header named Authorization, and send out the HTTP request to the url.
In subsequent runs, when you already have the access token and secret, you can instantiate the OAuth.Manager like this:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_CONSUMER_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_CONSUMER_SECRET;
oauth["token"] = your_stored_access_token;
oauth["token_secret"] = your_stored_access_secret;
Then just generate the authz header, and make your requests as described above.
Download the DLL
View the Documentation
Already solved my issue with http://www.voiceoftech.com/swhitley/?p=681
I was saving my app as "browser" but since I wasn't especifying a callback url it was transformed to "client" app on saving.
I am late to the conversation, but I have created a video tutorial for anyone else who is having this same task. Like you, I had a ton of fun figuring out the 401 error.
Video: http://www.youtube.com/watch?v=TGEA1sgMMqU
Tutorial: http://www.markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet
Code (in case you don't want to leave this page):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Twitterizer;
namespace PostFansTwitter
{
public partial class twconnect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var oauth_consumer_key = "gjxG99ZA5jmJoB3FeXWJZA";
var oauth_consumer_secret = "rsAAtEhVRrXUTNcwEecXqPyDHaOR4KjOuMkpb8g";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
accesstoken,
"Testing!! It works (hopefully).");
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
}
}
}
}
"DotNetOpenAuth" will be great helps for u. http://www.dotnetopenauth.net/
I've developed a C# library for OAuth that is really simple to use and get up and running with. The project is an open source project and I've included a demo application that works against
1. Google
2. Twitter
3. Yahoo
4. Vimeo
Of course any other OAuth provider will do as well. You can find the article and library here
OAuth C# Library