I want to modify twitter API from 1.0 to 1.1. The name of application which use twitter API is "diaryromantis". That application maker is not me and doesn't use twitter4j.
And I add this : (This is from twitter4j)
ConfigurationBuilder cb = new ConfigurationBuilder();
String consumerkey = "xQ";
String consumersecret = "U";
String token = "787323";
String tokensecret = "n\I";
{
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerkey)
.setOAuthConsumerSecret(consumersecret)
.setOAuthAccessToken(token)
.setOAuthAccessTokenSecret(tokensecret);
}
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
But the application still can't run.
Related
In ASP.Net MVC Core 2, we are trying to call the Linkedin web API with OAuth authentication.
We are able to declare the OAuth authentication service and retrieve the access token from Linkedin as shown in the code below.
Now we would like to request the API from a controller. To do that, we have to get the access token from the OAuth service we have declared with the AddOAuth method. How can we do that? No way to find an example anywhere.
Thanx for your help, we are really stuck.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie("linkedin_login", options =>
{
options.LoginPath = new PathString("/login");
options.LogoutPath = new PathString("/logout");
})
.AddOAuth("LinkedIn", options =>
{
options.SignInScheme = "linkedin_login";
options.ClientId = Configuration["linkedin:clientId"];
options.ClientSecret = Configuration["linkedin:clientSecret"];
options.CallbackPath = new PathString("/signin-linkedin");
options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,formatted-name,email-address,picture-url,picture-urls,headline,public-profile-url,industry,three-current-positions,three-past-positions,positions::(original))";
// To save the tokens to the Authentication Properties we need to set this to true
// See code in OnTicketReceived event below to extract the tokens and save them as Claims
options.SaveTokens = true;
options.Scope.Add("r_basicprofile");
options.Scope.Add("r_emailaddress");
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
#region OnCreatingTicket
// Retrieve user info
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
//We have here the token: context.AccessToken
request.Headers.Add("x-li-format", "json"); // Tell LinkedIn we want the result in JSON, otherwise it will return XML
the solution is just :
var AccessToken = await HttpContext.GetTokenAsync("LinkedIn", "access_token");
with "LinkedIn" the scheme of the desired oAuth
I have the following code segment and I am trying to collect some tweets from the timeline of say "stefanjdecker". The actual credentials of mine have been changed to make myself anonymous.
SparkConf conf = new SparkConf().setMaster("local").setAppName("SparkTwitterHelloWorldExample");
JavaStreamingContext jssc = new JavaStreamingContext(conf, new Duration(600));
String consumerKey = "key";
String accessTokenSecret = "secret";
String consumerSecret = "consumer";
String accessToken = "token";
System.setProperty("twitter4j.oauth.consumerKey", consumerKey);
System.setProperty("twitter4j.oauth.consumerSecret", consumerSecret);
System.setProperty("twitter4j.oauth.accessToken", accessToken);
System.setProperty("twitter4j.oauth.accessTokenSecret", accessTokenSecret);
String[] filters = new String[] {"stefanjdecker"};
JavaReceiverInputDStream<Status> twitterStream = TwitterUtils.createStream(jssc,filters);
twitterStream.dstream().saveAsTextFiles("/Output/twitter","txt");
The above code runs successfully. However, tweets are not being written to the path I mentioned. Please someone help me to sort this out.
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.
Is there a possibility to configure OAuth2 AssertionFlow with Facebook in Thinktecture Identity Server v3?
There was a post on leastprivilege.com about implementing AssertionFlow for Microsoft OAuth and AuthorizationServer but I need to integrate with Facebook and, furthermore, AuthorizationServer is marked as deprecated and it's not maintained anymore.
In response to #NathanAldenSr's comment, I publish some code of my working solution.
Server side - custom validator:
public class FacebookCustomGrantValidator: ICustomGrantValidator
{
private readonly IUserService userService;
private const string _FACEBOOK_PROVIDER_NAME = "facebook";
// ...
async Task<CustomGrantValidationResult> ICustomGrantValidator.ValidateAsync(ValidatedTokenRequest request)
{
// check assetion type (you can have more than one in your app)
if (request.GrantType != "assertion_fb")
return await Task.FromResult<CustomGrantValidationResult>(null);
// I assume that fb access token has been sent as a response form value (with 'assertion' key)
var fbAccessToken = request.Raw.Get("assertion");
if (string.IsNullOrWhiteSpace(assertion))
return await Task.FromResult<CustomGrantValidationResult>(new CustomGrantValidationResult
{
ErrorMessage = "Missing assertion."
});
AuthenticateResult authebticationResult = null;
// if fb access token is invalid you won't be able to create Facebook client
var client = new Facebook.FacebookClient(fbAccessToken);
dynamic response = client.Get("me", new { fields = "email, first_name, last_name" });
// create idsrv identity for the user
authebticationResult = await userService.AuthenticateExternalAsync(new ExternalIdentity()
{
Provider = _FACEBOOK_PROVIDER_NAME,
ProviderId = response.id,
Claims = new List<Claim>
{
new Claim("Email", response.email),
new Claim("FirstName", response.first_name),
new Claim("LastName", response.last_name)
// ... and so on...
}
},
new SignInMessage());
return new CustomGrantValidationResult
{
Principal = authebticationResult.User
};
}
}
You can easily test it with OAuth2Client that is also provided by Thinktecture (in Thinktexture.IdentityModel Client Library nuget package).
string fbAccessToken = "facebook_access_token_you_aquired_while_logging_in";
string assertionType = "assertion_fb";
var client = new OAuth2Client(
new Uri("your_auth_server_url"),
"idsrv_client_id",
"idsrv_client_secret");
string idsrvAccessToken = client.RequestAssertionAsync(assetionType, fbAccessToken,).Result;
IdentityServer v3 also supports assertion flow. The samples wiki has two samples on that (called "Custom Grants):
https://github.com/thinktecture/Thinktecture.IdentityServer.v3.Samples/tree/master/source
I am converting an existing application from QBXML to use the QBOE API V3 for the QuickBooks Online accounts. I have managed to complete the OAuth and have what appears to be valid tokens/secrets using the DevDefined toolkit. I am stuck on generation of the oauth_signature. All the documentation points me to use the Intuit.Ipp DLL's however I can't because it is written to .net 4.0 framework and the server my application runs on only has 2.0 loaded. I can move my application but testing that upgrade would put me after the cut off deadline (4/16/2014). Is there a way I can build the signature using the DevDefined or some other option?
The application runs on IIS 6.0, DotNet Framework 2.0, with ASP.VB.
Is the cutoff 4/16 now? I didn't see that announced anywhere. I thought it was 3/15.
I haven't tested this on .NET 2.0 but this just uses DevDefined without all the overhead. It will handle the signing and the http request for you.
using System.Text;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
// etc...
public void doGet()
{
IOAuthSession session = CreateSession();
string resp = session.Request().Get().ForUrl("https://quickbooks.api.intuit.com/v3/company/"
+ realmId + "/query?query=select * from customer where DisplayName='" + name + "'").ToString();
}
public void doPost(string Name)
{
IOAuthSession session = CreateSession();
string reqBody = "<Customer xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\">";
reqBody += "<DisplayName>" + Name + "</DisplayName>";
reqBody += "</Customer>";
byte[] bytes = Encoding.UTF8.GetBytes(reqBody);
session.ConsumerContext.UseHeaderForOAuthParameters = true;
IConsumerRequest req = session.Request().WithRawContentType("application/xml").WithRawContent(bytes);
req = req.WithAcceptHeader("application/xml");
req = req.ForUrl("https://quickbooks.api.intuit.com/v3/company/"
+ realmI + "/customer");
string resp = req.Post().ToString();
}
private IOAuthSession CreateSession()
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = Properties.Settings.Default.consumerKey,
ConsumerSecret = Properties.Settings.Default.consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1
};
IOAuthSession session = new OAuthSession(consumerContext);
session.AccessToken = myAccessToken;
return session;
}