Linq to Twitter - Bad Authentication data - twitter

I've the the latest version of Linq to Twitter (3.1.2), and I'm receiving the "Bad Authentication data" error with the code below:
var auth = new ApplicationOnlyAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = "xxxx",
ConsumerSecret = "xxxx"
}
};
using (var twitter = new TwitterContext(auth))
{
var users = twitter.User.Where(s => s.Type == UserType.Search && s.Query == "filter:verified").ToList();
}
I thought at first that it could be Twitter taking a while to accept my new credentials, but I used Twitter's OAuth tool with my keys, and they produced tokens without issue. Any ideas what I'm missing here?
I could not find a duplicate, as the code referenced # https://stackoverflow.com/questions/16387037/twitter-api-application-only-authentication-with-linq2twitter#= is no longer valid in the version I am running.

That query doesn't support Application-Only authorization. Here's the Twitter docs to that:
https://dev.twitter.com/rest/reference/get/users/search
Instead, you can use SingleUserAuthorizer, documented here:
https://github.com/JoeMayo/LinqToTwitter/wiki/Single-User-Authorization
Like this:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"]
}
};
To find out what type of authorization is possible, you can visit the L2T wiki at:
https://github.com/JoeMayo/LinqToTwitter/wiki
and each API query and command has a link at the bottom of the page to the corresponding Twitter API documentation.

Related

How to get an ACS app-only access token for Project Online

I'm trying to get an AppOnly access token for use in the Authorization Bearer header of my request to a REST endpoint in Project Online (SharePoint). Following is a snippet of the code that I was using to retrieve the access token.
private OAuth2AccessTokenResponse GetAccessTokenResponse()
{
var realm = TokenHelper.GetRealmFromTargetUrl([[our_site_url]]);
var resource = $"00000003-0000-0ff1-ce00-000000000000/[[our_site_authority]]#{realm}";
var formattedClientId = $"{ClientId}#{realm}";
var oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(
formattedClientId,
ClientSecret,
resource);
oauth2Request.Resource = resource;
try
{
var client = new OAuth2S2SClient();
var stsUrl = TokenHelper.AcsMetadataParser.GetStsUrl(realm);
var response = client.Issue(stsUrl, oauth2Request) as OAuth2AccessTokenResponse;
var accessToken = response.AccessToken;
}
catch (WebException wex)
{
using (var sr = new StreamReader(wex.Response.GetResponseStream()))
{
var responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
}
I keep getting 403 Forbidden as the response from the server, even if I include site collection admin credentials with my request. Does anyone out there have any ideas?
After creating a support ticket with Microsoft to figure this out we eventually decided to move away from using app permissions for console application authorization.
Our workaround was to create SharePointOnlineCredentials object using a service account, and then get the Auth cookie from the credentials object to pass with our WebRequest. This solution came from scripts found here: https://github.com/OfficeDev/Project-REST-Basic-Operations

Access email address in the OAuth ExternalLoginCallback from Facebook v2.4 API in ASP.NET MVC 5 [duplicate]

This question already has answers here:
Why new fb api 2.4 returns null email on MVC 5 with Identity and oauth 2?
(6 answers)
Closed 6 years ago.
With v2.3 of the Facebook API, provided the following was set, the users email address would be returned on the callback to ExternalLoginCallback;
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = "XXX",
AppSecret = "XXX",
Scope = { "email" }
});
However, any app that can only target v2.4 (released 8 July) no longer returns the email address to the ExternalLoginCallback.
I think this may possibly be related to the v2.4 changes as listed here;
Declarative Fields
To try to improve performance on mobile networks,
Nodes and Edges in v2.4 requires that you explicitly request the
field(s) you need for your GET requests. For example, GET
/v2.4/me/feed no longer includes likes and comments by default, but
GET /v2.4/me/feed?fields=comments,likes will return the data. For more
details see the docs on how to request specific fields.
How can I access this email address now?
To resolve this I had to install the Facebook SDK for .NET from nuget and query the email address separately.
In the ExternalLoginCallback method, I added a conditional to populate the email address from the Facebook Graph API;
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// added the following lines
if (loginInfo.Login.LoginProvider == "Facebook")
{
var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var access_token = identity.FindFirstValue("FacebookAccessToken");
var fb = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
loginInfo.Email = myInfo.email;
}
And to get the FacebookAccessToken I extended ConfigureAuth;
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = "XXX",
AppSecret = "XXX",
Scope = { "email" },
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
return Task.FromResult(true);
}
}
});
In MVC 6 (Asp.net Core 1.0), by configuring FacebookAuthentication in startup.cs like this:
app.UseFacebookAuthentication(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
options.Scope.Add("email");
options.UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name";
});
I could get the email. I.e:
var info = await _signInManager.GetExternalLoginInfoAsync();
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);

Google client API - limit oauth authentication to my domain

Has anyone had any experience of using the Google Client API to authorise against their domain by restricting the domain a user can login with?
The titbit that is required appears to be a qs parameter: hd='[Domain name]'
but there's nothing similar in the OAuth2Parameters parameters object
var oap = new OAuth2Parameters
{
AccessToken = Current == null ? null : Current.AccessToken,
RefreshToken = Current == null ? null : Current.RefreshToken,
ClientId = GoogleClientId,
ClientSecret = GoogleClientSecret,
Scope = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds https://www.googleapis.com/auth/userinfo.email",
RedirectUri = HttpContext.Current.Request.Url.Scheme.Concatenate("://", HttpContext.Current.Request.Url.Authority, "/Builder/Authentication/Receive"),
AccessType = "offline" //ensures a refresh token (tho not currently working),
*HD = //Hmm if only... :(((*
};
var authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(oap);
return Redirect(authorizationUrl);
so,in fact, all we need is to adjust the url thus:
var authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(oap);
authorizationUrl += "&hd=" + "mydomain.com".UrlEncode();
return Redirect(authorizationUrl);
Hope that helps someone down the line.
Use hd parameter.
Google documentation
Warning: This tag is documented in OAuth 1.0 API Reference. In version 2 is not documented but works.
Important: OAuth 1.0 has been officially deprecated as of April 20,
2012. It will continue to work as per our deprecation policy, but we encourage you to migrate to OAuth 2.0 as soon as possible.

Verify OAuth Token on Twitter

I'm storing the oauth info from Twitter in a Flash Cookie after the user goes though the oauth process. Twitter says that this token should only expire if Twitter or the user revokes the app's access.
Is there a call I can make to Twitter to verify that my stored token has not been revoked?
All API methods that require authentication will fail if the access token expires. However the specific method to verify who the user is and that the access token is still valid is GET account/verify_credentials
This question may be old, but this one is for the googlers (like myself).
Here is the call to twitter using Hammock:
RestClient rc = new RestClient {Method = WebMethod.Get};
RestRequest rr = new RestRequest();
rr.Path = "https://api.twitter.com/1/account/verify_credentials.json";
rc.Credentials = new OAuthCredentials
{
ConsumerKey = /* put your key here */,
ConsumerSecret = /* put your secret here */,
Token = /* user access token */,
TokenSecret = /* user access secret */,
Type = OAuthType.AccessToken
};
rc.BeginRequest(rr, IsTokenValid);
Here is the response:
public void IsTokenValid(RestRequest request, RestResponse response, object userState)
{
if(response.StatusCode == HttpStatusCode.OK)
{
var user = userState;
Helper.SaveSetting(Constants.TwitterAccess, user);
}
else
{
Dispatcher.BeginInvoke(() => MessageBox.Show("This application is no longer authenticated "))
}
}
I always borrow solutions from SO, this is my first attempt at giving back, albeit quite late to the question.
When debugging manually:
curl \
--insecure https://api.twitter.com/1/account/verify_credentials.json?oauth_access_token=YOUR_TOKEN
I am using TwitterOAuth API and here is the code based on the accepted answer.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $twitter_oauth_token, $twitter_oauth_secret);
$content = $connection->get("account/verify_credentials");
if($connection->getLastHttpCode() == 200):
// Connection works fine.
else:
// Not working
endif;

Can't twitter status using oAuth and .net Hammock library on Windows Phone 7

I've been able setup the oAuth calls to get the users access Token following a couple blog posts:
http://sudheerkovalam.wordpress.com/2010/08/28/a-windows-phone-7-twitter-application-part-1/
and
:/byatool.com/c/connect-your-web-app-to-twitter-using-hammock-csharp/comment-page-1/#comment-9955
But I'm having problems sending a status update. I can't find any examples so I may not be setting the proper values. Here's the code which keeps returning: "Could not authenticate with OAuth."
private void Tweet()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
Token = _settings.AccessToken,
TokenSecret = _settings.AccessTokenSecret,
Version = TwitterSettings.OAuthVersion,
};
var client = new RestClient
{
Authority = "http://twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true
};
var request = new RestRequest
{
Path = "/statuses/update.json",
Method = WebMethod.Post
};
request.AddParameter("status", TwitterTextBox.Text);
client.BeginRequest(request, new RestCallback(TwitterPostCompleted));
}
private void TwitterPostCompleted(RestRequest request, RestResponse response, object userstate)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
}
thanks for any help,
Sam
Ah figured it out finally I was using the wrong URL need to use:
Authority = "http://api.twitter.com" and not: "http://twitter.com/oauth"
Just in case other people find this I've written a blog post on using OAth with Hammock for Twitter. Might be of use to some people!

Resources