Login with Twitter account in Asp.net MVC - asp.net-mvc

I am trying to let users login with their twitter acount for my web site. I am using Tweetsharp library.
Now the problem is: after i enter twitter user name and password, the twitter page shows me a number like "7825362101" and says to enter this number into the concern web site.
I have no clue what shall my website do with that number!! I already have 'consumer key' and 'consumer secret' while i created the app in twitter.
I hope someone can help me!!
cheers

You don't need to do anything with that number if you are using the Tweetsharp in a web application. Just do the following in your controller, this will return a list of tweets from the public timeline:
private readonly string _consumerKey = "yourconsumerkey";
private readonly string _consumerSecret = "yourconsumersecretkey";
public ActionResult Index()
{
var service = new TwitterService(_consumerKey, _consumerSecret);
IEnumerable<TwitterStatus> model = service.ListTweetsOnPublicTimeline();
return View(model);
}

Spring.NET Twitter provides a sample for ASP.NET MVC.
http://www.springframework.net/social-twitter/

I think something is missing on redirect to Twitter authentication.Twitter API not getting all required values. So just follow the below link to authenticate your web application using Tweetsharp library
http://tutorialslink.com/Articles/Login-with-Twitter-account-in-Aspnet-MVC/24

Related

Unable to retrieve LinkedIn Authorization Code

I'm building an app that I would use to make posts to LinkedIn. I'm using Visual Studio 2017 (asp.net mvc c#).
I have already created an app in LinkedIn with Client ID and Client Secret.
I have also create an async Function GetCode() my application in Visual Studio.
This function makes a request to this url:
string url = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=kjahldj9384&state=DCEEFWKDHIUs5dffef424&redirect_uri=http://localhost:51272/";
When i run the application and this function gets called, I'm redirected to the LinkedIn Authentication page to login. But when I enter the LinkedIn login credentials and hit login, it takes me to this page: https://www.linkedin.com/uas/login-submit which displays the error message:
Request Error
We’re sorry, there was a problem with your request. Please make sure you have cookies enabled and try again.
Or follow this link to return to the home page.
This is my GetCode function:
//Get LinkedIn Code
[HttpGet]
[Route("api/LinkedIn/GetCode")]
public async Task<HttpResponseMessage> GetCode()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Content-Type", "application/x-www-form-urlencoded");
string url = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=54565kggfh&state=DCEEFW55754FD5dffef424&redirect_uri=http://localhost:57313/";
HttpResponseMessage apiResponseMsg = await client.GetAsync(new Uri(url));
return apiResponseMsg;
}
}
Is there something I'm doing wrong?
First, make sure to add your redirect_uri to OAuth 2.0 Settings in the Linkedin developer portal (under Auth tab). If that isn't the issue, try below.
If you build the same URL, and redirect the page to it instead of using a response message, then you should be sent back to your website with the code as a query parameter (http://localhost:60137/?code=xxxxxxxxxxxxx). I made a working example with a test application:
[HttpGet]
public ActionResult GetCode()
{
//build url from config file
string url = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=78z99sg1ncgbma&redirect_uri=http://localhost:60137";
return new RedirectResult(url);
}
Hope this helps.

When using Twitter OAuth with TweetSharp I keep getting asked to authorize my app every time a user wants to log in

I'm trying to implement OAuth with twitter so my users can log into my site using their Twitter IDs. For this I am using the TweetSharp library. Following the examples they have I wrote the following code which seems to work.
public ActionResult Login(string oauth_token, string oauth_verifier)
{
var service = new TwitterService(consumerKey, consumerSecret);
if (oauth_token == null)
{
var requestToken = service.GetRequestToken(Request.Url.ToString());
var uri = service.GetAuthorizationUri(requestToken);
return new RedirectResult(uri.ToString(), false);
}
else
{
var requestToken = new OAuthRequestToken { Token = oauth_token };
OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
TwitterUser user = service.VerifyCredentials(new VerifyCredentialsOptions());
TempData["response"] = string.Format("Your username is {0}", user.ScreenName);
return RedirectToAction("Success");
}
}
public ActionResult Success()
{
ViewBag.Response = TempData["response"];
return View();
}
However, there is a problem. Every time the user logs into the system twitter asks them to authorize the application even though they have done it before. Is there a way to prevent this behavior? I have also implemented OAuth with Facebook and Google and I don't need to authorize the application every time I want to log into the system.
Unfortunately not as far as I'm aware. Twitter uses OAuth 1.1 rather than OAuth 2.0 like Facebook and Google, so there is a manual step in the middle in which users are asked to authorise the application even though they have done already. I'm having exactly the same issue and it appears to be something we have to live with.
I was having the same problem with a slightly older app I was trying to resurrect. I noticed that the problem went away when I selected "Sign in with Twitter" in my app settings at http://dev.twitter.com/apps.

Get Google user name when using OAuthWebSecurity in ASP.NET MVC 4?

I've created a standard boilerplate ASP.NET MVC 4 Internet project. When using OAuthWebSecurity to enable my web site to do social login with Facebook, I see how I can access the Facebook user name in the ExternalLoginCallback() action in the AccountController by accessing the AuthenticationResult's ExtraData:
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication( Url.Action( "ExternalLoginCallback", new { ReturnUrl = returnUrl } ) );
var facebookName = result.ExtraData["name"];
When logging in with Google, however, ExtraData contains only "email". Is it possible to get the Google user name? Am I missing a configuration tweak somewhere?
Found my answer here: Plugging custom OAuth/OpenID providers. This has been a known issue since August 2012 and as yet (DotNetOpenAuth.AspNet 4.2.2.13055, April 2013) has not been fixed.
The workaround is to write your own Google provider, and the blog post above includes a complete working example. It is then a simple matter to get the Google user name:
var googleName = result.ExtraData["firstName"] + " " + result.ExtraData["lastName"];

How to obtain email address from Facebook using ASP.MVC and DotNetOpenAuth

I'm trying to set up authentication in my app. I have the posting to the external website working (facebook and google)
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get), ValidateInput(false)]
public ActionResult OpenIdLogOn(string returnUrl)
{
var redirectUrl = "~/Companies/LogIn";
var provider = Request.Form["provider"];
if (Common.IsNull(provider))
return View();
OpenAuth.RequestAuthentication(provider, redirectUrl);
return View();
}
This works by figuring out what button was clicked (Login with facebook / Google) Then requests authentication. When the authentication has finished and I get a post back, I try to retrieve the email address.
public ActionResult LogIn()
{
var redirectUrl = "~/Companies/LogIn/OpenIdLogOn";
var response = Response;
var userEmail = Request.Params[16];
if (!String.IsNullOrEmpty(ReturnUrl))
{
Response.Redirect("~/Bloggers");
}
ViewBag.OAuthProviders = OpenAuth.AuthenticationClients.GetAll().ToList();
return View();
}
The following will work if I log in with google -
var userEmail = Request.Params[16];
but facebook doesn't send the email back. Well I cant see it in the request. There must be a better way of doing this than using Request.Params[16];
also. Help would be much appreciated.
Without being able to see what OpenAuth is, it's pretty hard to say what the new code should look like. But suffice it to say that you should absolutely never scrape the email address directly from the request. All security offered by OAuth and OpenID are worthless when you do that. You need to get the email address from the security library you're using.
For Google, that means getting it from the FetchResponse or ClaimsResponse extensions of the response.
For Facebook, that means using the access token returned from the login to fetch the email address from Facebook and verify the audience field to make sure the access token isn't being redirected to your site as part of a user spoofing attack.

ASP.NET MVC Facebook

I am trying to do a seemingly simple thing, but having trouble accomplishing it. I am trying to automate the posting on my Facebook wall. Basically I have a ASP.NET MVC website that I post updates on, and I want to automatically submit the post to my wall.
I see a lot of stuff on FB Connect and getting data, I just want to post.
Thanks for any help or guidance.
UPDATE: Just trying to resurrect and be a little more clear in my description as I am not getting anywhere.
I have a page that I want with a text box and a button. When I submit the form I want the message to post to my Facebook wall. I thought it was Facebook Connect, but I am getting no where as to how to automatically authenticate myself and post to my wall.
I would like to use C# rather than JavaScript.
private const string ApplicationKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private const string SecretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
private Facebook.Rest.Api _facebookAPI;
private Facebook.Session.ConnectSession _connectSession;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
_connectSession = new Facebook.Session.ConnectSession(ApplicationKey, SecretKey);
if (_connectSession.IsConnected())
{
_facebookAPI = new Facebook.Rest.Api(_connectSession);
string response = _facebookAPI.Stream.Publish("This is a generated test");
}
return View();
}
}
The IsConnected() is returning false.
Any help is appreciated.
This code was right, the problem was that I had not added my application to my profile. Dumb miss, but my thought is that the whole thing is poorly documented. I have another issue with offline access, but that is for a different post.
string apiKey = "XXXXXXXXX";
string apiSecret = "XXXXXXXXXXXX";
Facebook.Session.ConnectSession._connectSession = new Facebook.Session.ConnectSession(apiKey, apiSecret);
if (_connectSession.IsConnected)
{
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
string response = api.Stream.Publish("Test", null, null, null, api.Users.Session.UserId);
}
It could be that you tested your Website on your localhost. The Facebook Cookie is not written out, when you test your Website on localhost. See this link http://forum.developers.facebook.net/viewtopic.php?pid=247332
This might solve your problem:
Add "127.0.0.1 localhost.local" to your file
Update your FB application Connect settings to use "http://localhost.local/" URL and "localhost.local" domain.
Create an IIS Web site on port 80 with the name "localhost.local". I had to stop my default web site, which is also on port 80
Update my Visual Studio 2010 web application to use IIS with the "http://localhost.local/" url.
To see cookies, make sure to install FireCookies, along with FireBug.

Resources