I've this code which is not working.
If i try to post in twitter with the generated access token and access token secret from the page, it works perfectly, but if i try to retrieve the access tokens it doesn't work, it goes to the page, i authorize the app and it doesn't retrieve the tokens, can anyone help me please?
var oauth_consumer_key = "******************************";
var oauth_consumer_secret = "**************************************";
var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);
OAuthRequestToken requestToken = service.GetRequestToken();
string authUrl = service.GetAuthorizationUri(requestToken).ToString();
Process.Start(authUrl);
TILL THIS POINT THE CODE IS WORKING.
START OF NOT WORKING CODE
OAuthAccessToken accessToken = service.GetAccessToken(requestToken);
string token = accessToken.Token.ToString();
string tokenSecret = accessToken.TokenSecret.ToString();
Console.WriteLine(accessToken.Token);
Console.WriteLine(accessToken.TokenSecret);
Console.ReadKey();
service.AuthenticateWith(accessToken.Token,accessToken.TokenSecret);
This part is working if i authenticate directly with the strings generated in the app page
//service.AuthenticateWith("*****************************", "***********************************");
service.SendTweet(new SendTweetOptions
{
Status = "yayayayayayayayayayyayayay"
});
I really dont understand why it doesn't work, can someone please help me?
Thank you so much guys
Related
So far I followed this post and it helped me so much, however, I now get a "invalid_grant".
Following : https://developer.apple.com/documentation/signinwithapplerestapi/errorresponse I understand that I have an issue either because of the authorization grant or refresh token is invalid.
In despite of my searches and tries (and retries), I am still stuck and I don't know where does it come from. I used the app given at https://developer.apple.com/documentation/authenticationservices/adding_the_sign_in_with_apple_flow_to_your_app
Now that I get my token from the app above, I try to validate it from C# backend but I get a 400 response code invalid_grant.
The only difference I could notice from the post is that I don't have any [Verify] button (option) or [Download] button from the portal compared to the image below. I don't know if this is related but I am trying to provide as much details as I can:
Hopefully someone can help, thanks for any help :) feel free to ask for more details if required
Max
I also had the same issue, I found the solution here:
https://forums.developer.apple.com/thread/118135
as explained in the link, when you are using the code you got from the app, you should use app id instead of service id.
Could you share how you try to create the JWT?
I ve tried a couple of stuff Im at this right know (which doesnt work either, Ill update if I find a real solution)
const string iss = "7#######G"; // team ID
const string aud = "https://appleid.apple.com";
const string sub = "com.######.weblogin"; // serviceid
const string privateKey = "MIGTA#######"; // contents of .p8 file
var d = DateTime.UtcNow.AddDays(-5);
var cngKey = CngKey.Import(
Convert.FromBase64String(privateKey),
CngKeyBlobFormat.Pkcs8PrivateBlob);
var handler = new JwtSecurityTokenHandler();
var securityKey = new ECDsaSecurityKey(new ECDsaCng(cngKey) { KeySize = 256 , HashAlgorithm = CngAlgorithm.ECDsaP256});
securityKey.KeyId = "G#######W";
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.EcdsaSha256);
return handler.CreateEncodedJwt(iss, aud, new ClaimsIdentity(new List<Claim> { new Claim("sub", sub) }),d, expires: d.AddMonths(3),d, signingCredentials: signingCredentials);
Headers look like that in the jwt, from what Ive gathered there might be the "typ" header which is not present in many implentation, perhaps I shoud get rid of it :
{
"alg": "ES256",
"kid": "G#######W",
"typ": "JWT"
}
body:
{
"sub": "com.#####.weblogin",
"nbf": 1583088895,
"exp": 1591037695,
"iat": 1583088895,
"iss": "7######G",//teamid
"aud": "https://appleid.apple.com"
}
I've been trying to integrate the Instagram API in my app, but am stuck with the authentication. I had it working completely fine when I was just using the implicit flow version which gave me the access_token as part of the URI fragment.
However, now I'm changing to the server-side flow, in which I receive a code after the user logs in. I then post this code to the access token URL, which will then give me the access_token as well as certain information about the user, such as their username and profile picture link.
I am using the InstaSharp library, modifying the source code.
HttpClient client = new HttpClient { BaseAddress = new Uri(config.OAuthUri + "access_token/", UriKind.Absolute) };
var request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
request.AddParameter("client_secret", config.ClientSecret);
request.AddParameter("client_id", config.ClientId);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("redirect_uri", config.RedirectUri);
request.AddParameter("code", code);
return client.ExecuteAsync<OAuthResponse>(request);
After creating my request, it is formatted as so:
{Method: POST, RequestUri: 'https://api.instagram.com/oauth/access_token/?client_secret={CLIENT_SECRET}&client_id={CLIENT_ID}&grant_type=authorization_code&redirect_uri=http://instagram.com &code={CODE}', Version: 1.1, Content: , Headers: { }}
(I inserted the space between the redirect_uri and code because it wouldn't let me post the question otherwise)
Everything appears normal in the address, but I always receive an error in the retuned json file:
"{"code": 400, "error_type": "OAuthException", "error_message": "You must provide a client_id"}"
I have no clue what is causing this error. Any help is greatly appreciated!
Thanks!
Elliott
Are you using the latest version of InstaSharp? Fork it here. You can check the README.md there although it's a bit outdated and you need to tweak some config. Here's how you can do it with the latest version that is in github:
// create the configuration in a place where it's more appropriate in your app
InstaSharpConfig = new InstagramConfig(
apiURI, oauthURI, clientId, clientSecret, redirectUri);
// then here's a sample method you can have to initiate auth
// and catch the redirect from Instagram
public ActionResult instagramauth(string code)
{
if (string.IsNullOrWhiteSpace(code))
{
var scopes = new List<InstaSharp.Auth.Scope>();
scopes.Add(InstaSharp.Auth.Scope.likes);
var link = InstaSharp.Auth.AuthLink(
oauthURI, clientId, redirectUri, scopes);
// where:
// oauthURI is https://api.instagram.com/oauth
// clientId is in your Instagram account
// redirectUri is the one you set in your Instagram account;
// for ex: http://yourdomain.com/instagramauth
return Redirect(link);
}
// add this code to the auth object
var auth = new InstaSharp.Auth(InstaSharpConfig);
// now we have to call back to instagram and include the code they gave us
// along with our client secret
var oauthResponse = auth.RequestToken(code);
// save oauthResponse in session or database, whatever suits your case
// oauthResponse contains the field Access_Token (self-explanatory),
// and "User" that'll give you the user's full name, id,
// profile pic and username
return RedirectToAction("action", "controller");
}
Take note that you can split up the "instagramauth" method. Did it that way for brevity.
Let me explain my question :
In the image we can see a twitter access_token & secret (present on twitter app details page)
when I use the above two and try to update the status it works.
Twitter twitter = TwitterFactory.getSingleton();
twitter.setOAuthConsumer(Tweet.consumer_key, Tweet.consumer_secret);
twitter.setOAuthAccessToken(new AccessToken(u.getTwittertoken(), u.getTwittersecret()));
twitter.updateStatus("test");
But the oauth_token & oauth_secret that I get through using twitter4j callbackURL
don't work with the above code. I always get Invalid/Expired Token error.
I don't know what can be the error. Because it used to work once, but stopped suddenly (don't know exactly when)
Please help! It'll be great if someone can share their code for both - getting & saving the token into database & then getting it again from the db to update the status.
For those who face the same error, here's what I was doing wrong :
I was trying the token & secret received in twitter-response. Although the correct method is to retrieve them from accessToken which has to be retrieved using oauth_verifier being sent in twitter-response.
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey(Tweet.consumer_key);
cb.setOAuthConsumerSecret(Tweet.consumer_secret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
RequestToken requestToken = (RequestToken) mapSession.get("rtoken");
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
System.out.println("Request Token : " + ToStringBuilder.reflectionToString(requestToken, ToStringStyle.SHORT_PREFIX_STYLE));
System.out.println("Access Token : " + ToStringBuilder.reflectionToString(accessToken, ToStringStyle.SHORT_PREFIX_STYLE));
System.out.println(accessToken.getToken()); //use this further
System.out.println(accessToken.getTokenSecret()); //use this further
I am using Google OAuth to authenticate the user in my GAE application. After the user clicks on "Grant Access", I want to return to my application. I tried setting the callback URL, but instead of being called independently, it gets appended to the current URL in the browser, and thus shows as an invalid URL.
Here is my code:
OAuthGetTemporaryToken requestToken = new OAuthGetTemporaryToken(REQUEST_TOKEN_URL);
requestToken.consumerKey = CONSUMER_KEY;
requestToken.transport = TRANSPORT;
requestToken.signer = signer;
requestToken.callback="www.mail.yahoo.com";
OAuthCredentialsResponse requestTokenResponse = requestToken.execute();
// updates signer's token shared secret
signer.tokenSharedSecret = requestTokenResponse.tokenSecret;
OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(AUTHORIZE_URL);
authorizeUrl.temporaryToken = requestTokenResponse.token;
This line sends it to the Google OAuth page.
resp.sendRedirect(authorizeUrl.build());
I have set the callback parameter as shown above, but it's not working. Please help! Thanks in advance.
This is OAuth1 stuff, which is deprecated. Try using OAuth 2.0 instead. Start at https://developers.google.com/accounts/docs/OAuth2
anyone ever used C# in combination with the library RestSharp and OAuthBase in order get some interaction with LinkedIn?
I'm looking for a working example using these tools to do proper authorization (oAuth 2.0) and to publish a post using the share API on LinkedIn.
So far I've been successful using these tools to obtain valid access tokens (I can use it to obtain profile information for example), but posting via the share API got me stuck on authentication.
Any help would be very much appreciated!!
it turned out to be much simpler than I was thinking.... (doesn't it allways?)
The main point to take into account is: oAuth 2.0 does not require signatures, nonce, timestamps, authorization headers ... none of that.
If you want to post on LinkedIn using the sahres API and using oAuth2.0 ... OAuthbase is not needed.
Simply follow the oauth 2.0 authentication flow as described here:
http://developer.linkedin.com/documents/authentication
And then you can use the following code as a starting point:
var shareMsg = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new
{
title = "Test post to LinkedIn",
submitted_url = "http://www.somewebsite.com",
submitted_image_url = "http://www.somewebsite.com/image.png"
},
visibility = new
{
code = "anyone"
}
};
String requestUrl = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=" + accessToken;
RestClient rc = new RestClient();
RestRequest request = new RestRequest(requestUrl, Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = DataFormat.Json;
request.AddBody(shareMsg);
RestResponse restResponse = (RestResponse)rc.Execute(request);
ResponseStatus responseStatus = restResponse.ResponseStatus;
Happy coding!!