Instagram API returning error when requesting access_token on Windows Phone - oauth

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.

Related

Call Graph API from MVC App

SUMMARY UPDATE:
I got a sample working today thanks to the many good replies. Thanks all. My primary goal was to get current user information (ME) without using secret key. First I just used the secret key from the App Reg and this will authenticate the App and not the user. This does of course not work when calling ME. My next finding was if you want the users token, you still need the App Reg token, and then you request the users token. This requires less permissions on the App Reg, but requires to request two tokens. I ended up skipping ME and just requesting information for a specified user (through the APp Reg permissions):
$"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName"
Both both approaches should be viable. I updated code below with working sample.
I am trying to do a very simple call to graph API to get companyName from current user. Found some samples but they seemed to be very complicated. The MVC app is authenticated trough an Application Registration in AAD.
I guess the application registration needs to be authorized to access Graph API. Or is more needed here? Getting company name should be fairly simple:
https://graph.microsoft.com/v1.0/me?$select=companyName
Does anyone have a snippet for calling the graph API, my best bet would be you need to extract a bearer token from the controller? ALl help is appreciated.
Working snippet:
public async Task<ActionResult> Index()
{
string clientId = "xxx";
string clientSecret = "xxx";
var email = User.Identity.Name;
AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/xxx.onmicrosoft.com/oauth2/token");
ClientCredential creds = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
HttpClient http = new HttpClient();
string url = $"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName";
//url = "https://graph.windows.net/xxx.onmicrosoft.com/users?api-version=1.6";
// Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
var json = response.Content.ReadAsStringAsync();
return View();
}
To add one last item, here is a link to an MVC sample on Git that uses an MVC application to send email. It illustrates how to call the MS Graph API to get various pieces of information. Keep in mind, if you are using an application only scenario, ME will not work, the sample illustrates how to obtain a delegated token for a user and use that toke to do work:
https://github.com/microsoftgraph/aspnet-connect-rest-sample
If I am reading this code snippet correctly, You are requesting a application only token for the Graph.Microsoft.Com resource, then attempting to use that toke with this URI:
url = "https://graph.windows.net/thomaseg.onmicrosoft.com/users?api-version=1.6"
This will not work because you are mixing resources, AAD Graph and MS Graph. The ME endpoint does not make since in this scenario because you are using the application only flow. This flow does not support the ME endpoint. ME is designed for use with a delegated token. the ME endpoint represents the signed in user, since and application is not a user, ME is meaningless.
You will need to target the user specifically:
https://graph.microsoft.com/v1.0/Users/[UPN or ID of user]?$select=companyName
Should work if your application has been granted the appropriate permission scopes.

OAuth1 Authentication in RestSharp for Twitter API GET and POST methods

Using Postman I'm successfully able to query and create tailored audiences using the Twitter API, using Postman's OAuth 1.0 Authorization. However when trying to do the same with RestSharp I get an Unauthorized error.
"UNAUTHORIZED_ACCESS" - "This request is not properly authenticated".
My GET request authenticates fine, but the POST request fails.
_twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
};
var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
//this works and gives me a list of my tailored audiences
var response1 = _twitterRestClient.Execute(restRequest1);
var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences?name=SampleAudience2&list_type=EMAIL", TwitterAccountId), Method.POST);
// this results in an "Unauthorized" status code , and the message {\"code\":\"UNAUTHORIZED_ACCESS\",\"message\":\"This request is not properly authenticated\"}
var response2 = _twitterRestClient.Execute(restRequest2);
Turns out this is due to a quirk in RestSharp OAuth1 implementation. I think its related to this issue - https://www.bountysource.com/issues/30416961-oauth1-not-specifing-parameter-type . Part of creating an OAuth1 signature involves gathering all the parameters in the request and other details and then hashing it all. It looks like when the HTTP Method is a POST, then RestSharp is not expecting parameters in the querystring (which makes sense), its expecting them in the post body. Anyhow if you add parameters explicitly then they are picked up and the OAuth1 signing works. (Turns out the twitter API works if these params are in the post body, so I didn't need to explicitly add them to the query string). Updated code that now works:
_twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
};
var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
var response1 = _twitterRestClient.Execute(restRequest1);
var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.POST);
restRequest2.AddParameter("name", "SampleAudience2");
restRequest2.AddParameter("list_type", "EMAIL");
var response2 = _twitterRestClient.Execute(restRequest2);

Get access_token using Windows Service's or Console App. for Instagram Api

My windows service is collect instagram datas from instagram api. I was using client_id but this uses format is removed.
Instagram api is want to access_token but Oauth 2.0 is web-based. or not?
I using .NET and my application type is windows service and web request don't work because this call url: "https://www.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code" is have one more contain redirect. so web response haven't contain my web application link also auto redirect is open..
what should I do?
Thanks..
Steps to get instagram access token
register ur application in instagram account.
get a client id and client secret.
Step 1: HIT the below url.
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
step 2: after hitting above url you will be taken to login page. enter the login credentials and take the code from address bar.
it will be live for only 20 seconds i guess.
step 3: The code which you got put it in CODE parameter in the below source code, then run the below code in console application n hit breakpoint at response. you will get access token and userid.
public void GetDataInstagramToken()
{
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "CLIENT-ID");
parameters.Add("client_secret", "CLIENT-Secret");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "REDIRECT-URI");
parameters.Add("code", "CODE");
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
}
catch (Exception)
{
//exception catch
}
}

how to get user information from Withings api on grails

I'm trying to get user information from Withings Api, i've already success login into Withings with Oauth using Scribe library(Java). But there is a problem when i sent request to get user information follow Withings Api document it always return result with error code.
I've tried some way but it didn't work. Can someone help me to solve this problem.
Withings Api http://www.withings.com/en/api#documentation
First i call withings action in WithingsController.groovy to get authentication.
After authenticate success server return access token, in withingsCallback action i get user information.
Result return when get user information is result code of Withings Api
{"status":2554}
This is my code
WithingsService.groovy
def getAuthDetails(callbackUrl) {
if (!authService) {
authService = new ServiceBuilder()
.provider(WithingsApi.class)
.apiKey( grailsApplication.config.oauth.withings.key as String )
.apiSecret( grailsApplication.config.oauth.withings.secret as String )
.callback( callbackUrl as String )
.build();
}
Token requestToken = authService.getRequestToken();
[ authUrl : authService.getAuthorizationUrl(requestToken), requestToken : requestToken ]
}
def getWithingsUserInformation(Token accessToken,String userId){
String url = 'http://wbsapi.withings.net/user?action=getbyuserid&userid='+userId;
OAuthRequest request = new OAuthRequest( Verb.POST, url )
authService.signRequest(accessToken, request)
Response response = request.send()
return response
}
def getAccessToken( params, requestToken ){
requestToken = requestToken as Token
Verifier verifier = new Verifier( params.oauth_verifier )
authService.getAccessToken(requestToken, verifier);
}
WithingsController.groovy
def withings() {
def authInfo = withingsService.getAuthDetails(createLink(action: 'withingsCallback', controller: 'withings', absolute: 'true'))
if (authInfo.requestToken)
{
session["withings_requestToken"] = authInfo.requestToken
}
}
def withingsCallback(){
def accessToken = withingsService.getAccessToken(params, session["withings_requestToken"])
session["withings_accessToken"] = accessToken
if(accessToken) {
def profile
String userId = params.userid
profile = withingsService.getWithingsUserInformation(accessToken,userId)
}
}
Unless I'm missing something, it looks like you are not redirecting your user to get the "access token". After you get a request token:
you then generate a authentication url
redirect the user to this authentication url
they will authenticate
if authentication is successful, provider will call your callback with access token
So your withings action should include:
def withings() {
def authInfo = withingsService.getAuthDetails(createLink(action: ....
if (authInfo.requestToken)
{
session["withings_requestToken"] = authInfo.requestToken
}
//are you missing this?
redirect(authInfo.authUrl)
}
If you're using some type of http debugging/logging, check for the following request after your withings action.
https://oauth.withings.com/account/authorize?
oauth_callback=http%3A%2F%2Fexample.com%2Fget_access_token
&oauth_consumer_key=c331c571585e7c518c78656f41582e96fc1c2b926cf77648223dd76424b52b
&oauth_nonce=369f9ceb2f285ac637c9a7e9e98019bd
&oauth_signature=OR9J9iEl%2F2yGOXP2wk5c2%2BWtYvU%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1311778988
&oauth_token=5bb105d2292ff43ec9c0f633fee9033045ed4643e9871b80ce586dc1bf945
&oauth_version=1.0
Though this is unrelated to the question initially asked, I thought I would post here since this was a common stopping ground for me reaching a Withings 2554 error.
If updating to the newest version of Withings Api for access token authentication, the current version of the Withings Api will now also cause this 2554 status code if you do not attach action: requesttoken to the access token request body.
Additionally, when pulling apart the response, make sure to drill into the body of the payload, since the latest version of the Withings access token api delivers its payload contents differently. This may be a no brainer for those implementing from scratch, but if you are using an oauth library, most of this behavior is abstracted by the library, and it likely won't be anticipating the payload structure to contain the body field.
more info here: https://developer.withings.com/api-reference#operation/oauth2-getaccesstoken

Require Google to return email address as part of OAuth

I am using OAuth to access Gmail with dotNetOAuth. How can I force Google to return user's email address as part of callback after authorization?
By default, Google OAuth callback only returns the token secret and access tokens.
First you need to add the following scope (https://www.googleapis.com/auth/userinfo.email) to your oauth request.
After you're back to your app from Google and you have your access token, you can make a request using the access token to https://www.googleapis.com/userinfo/email?alt=json.
This will return the email address. More info at http://sites.google.com/site/oauthgoog/Home/emaildisplayscope
For getting the Email Id, you need to add the scope "https://wwww.googleapis.com/auth/userinfo.email"
Then you will get id_token in the response.
Response={
"access_token" : "ya29.eAG__HY8KahJZN9VmangoliaV-Jn7hLtestkeys",
"token_type" : "Bearer",
"expires_in" : 3600,
"id_token" : "id_token_from_server",
"refresh_token" : "1/GIHTAdMo6zLVKCqNbA"
}
Then use this id_token as below POST request:
https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=id_token_from_server
And you will get response like below:
Response={
"issuer": "accounts.google.com",
"issued_to": "80780.apps.googleusercontent.com",
"audience": "8078909.apps.googleusercontent.com",
"user_id": "1118976557884",
"expires_in": 3598,
"issued_at": 1456353,
"email": "emailId#gmail.com",
"email_verified": true
}
Make sure you add "www" in the APIs as shown above...
OAuth doesn't provide a facility for extra parameters during an OAuth handshake, so I don't think you can force Google to supply it. There is likely a Google API however that you can use your OAuth access token to call to fetch the email address after the handshake, however.
request OAuth scope to include the "Email Display Scope" https://www.googleapis.com/auth/userinfo.email
scope="http://www.google.com/m8/feeds/ https://www.googleapis.com/auth/userinfo.email"
Then use REST API like Hammock to get address
RestClient client = new RestClient
{
Authority = "https://www.googleapis.com",
};
RestRequest request = new RestRequest
{
Path = "userinfo/email?alt=json",
Credentials = OAuthCredentials.ForProtectedResource(
this.requestSettings.ConsumerKey,
this.requestSettings.ConsumerSecret,
this.requestSettings.Token,
this.requestSettings.TokenSecret)
};
var response = client.Request(request);
Here's a c# function for when you have pre-authorized the request as detailed above:
private void FetchUsersEmail(token)
{
var emailRequest = #"https://www.googleapis.com/userinfo/email?alt=json&access_token=" + token;
// Create a request for the URL.
var request = WebRequest.Create(emailRequest);
// Get the response.
var response = (HttpWebResponse) request.GetResponse();
// Get the stream containing content returned by the server.
var dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
var reader = new StreamReader(dataStream);
// Read the content.
var jsonString = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
dynamic json = JValue.Parse(jsonString);
var currentGoogleEmail = json.data.email;
}
(JValue is part of JSON.Net)
In php, apiOauth2Service.php class provides methods to access logged in user info. For this you can use userinfo->get() method. Make sure you also use scope https://www.googleapis.com/auth/userinfo.email.
This will work with same access token. Also you should try looking in other APIs for similar kind of information in return. This is much easier to look through oAuth_playground >> http://code.google.com/apis/explorer/
If you request the userinfo.email scope, Google returns an id_token along with the access_token.
The id_token can be unencrypted to provide the user's email address, at www.googleapis.com?/oauth2/v1/tokeninfo?id_token=IDTOKENHERE
More information here: https://developers.google.com/accounts/docs/OAuth2Login

Resources