Malformed access token 190 error - c#

when trying to redirect to gain a new access token an error occurred saying :
(OAuthException - #190) Malformed access token AQClEC8NbS1tbO4_HzqqZwVy2Inrk5I7vBpszPDPN0dVOV0ekurwNEpqzlWe2hQzl2KNZ5BwiSvL16bDPhR5IxFeJXEXBdM67uky7iwKbYKIVoRF__iyayyXBgcIp939gEZNtCUxyO4ZKZHQ9xmEwDstaOgq_bAvtygwv3YUeEYD9wftsytMZYwVxDO7rjq-2i3-XCYj643-6_1yKZ0dDahAB00iBqJqw1xiZ-l1kzStmA_pwMwO5dtBHZozp-L2hp0JEeTL0Fhc5CG1zbJ8Om6kyKBWyZuc0AtOrdSjgcBQBv9hQSF5pwsMZvFDGcjiwSc
what possibly could be the problem i am doing this method to redirect :
string redirecturl = #"https://graph.facebook.com/oauth/authorize?client_id=507061112747022&redirect_uri=http://localhost:63695/FacebookChatApi/Default.aspx";
Response.Redirect(redirecturl);
and i am reading the access token as follow :
string accessToken=Request["code"];
var client = new FacebookClient(accessToken); // here is where the error occurred
Is this the right method to get a client access token ?
why this error is occurring when reading the code value

according to Facebook Debug tool, your token is not a Token but a URL instead: https://developers.facebook.com/tools/debug/og/object?q=AQClEC8NbS1tbO4_HzqqZwVy2Inrk5I7vBpszPDPN0dVOV0ekurwNEpqzlWe2hQzl2KNZ5BwiSvL16bDPhR5IxFeJXEXBdM67uky7iwKbYKIVoRF__iyayyXBgcIp939gEZNtCUxyO4ZKZHQ9xmEwDstaOgq_bAvtygwv3YUeEYD9wftsytMZYwVxDO7rjq
I'm not sure who you get it, and why you get it instead of access token - you did not show enough code. From what I saw, I believe you generate your redirecturl incorrectly. Below is a piece of code from one of my project - please try it and let me know if it works for you:
// 1. redirect user to the login page:
var redirectUri = "http://localhost:63695/FacebookChatApi/Default.aspx";
var service = new FacebookClient();
var loginUrl = service.GetLoginUrl(new {
client_id = ConfigurationProvider.FacebookAppId,
client_secret = ConfigurationProvider.FacebookAppSecret,
redirect_uri = redirectUri,
response_type = "code",
scope = "manage_pages, publish_actions, user_photos, publish_stream" // Add other permissions as needed
});
Response.Redirect(loginUrl);
// 2. And when user authorizes, get the access token
// NOTE: code executes on FacebookChatApi/Default.aspx page
var redirectUri = "http://localhost:63695/FacebookChatApi/Default.aspx"; // must be the same as in the login call!
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = ConfigurationProvider.FacebookAppId,
client_secret = ConfigurationProvider.FacebookAppSecret,
redirect_uri = redirectUri,
code = code
});
var accessToken = result.access_token;

Related

Generate user token from AuthenticationContext

I am trying to generate a user token for the purpose of testing an API that requires one. The tests run automatically. I have the following code example, but it seems to be out of date
Uri endpointUri = new Uri("my endpoint");
string resource = "my rid";
string clientId = "my client id";
PlatformParameters parameters = new PlatformParameters(PromptBehavior.Auto);
string authContextURL = "my url";
var authenticationContext = new AuthenticationContext(authContextURL, new TokenCache());
// Here you are sending a request to AAD with the user credentials.
AuthenticationResult result = await authenticationContext.AcquireTokenAsync(resource: resource, clientId: clientId, redirectUri: endpointUri, parameters);
// If the request succeeded you can get the user access token as follows.
return result.AccessToken;
The reason I believe it to be out of date is that PlatformParameters now requires 2 parameters, and I cannot find what the 2nd parameter should be by default.
My question is, how can I create a user-context token to use in testing my API from the test code?
EDIT
According to this answer, PlatformParameters with 1 param is for .netframework, whereas I am using .net 6
Still looking to any leads there may be!

How to post using PostTaskAsync in Facebook C# SDK?

I'm using the Facebook C# SDK to authorize my app login and post on the user's timeline. So far the login feature works and permissions are authorized, but when my code gets to the PostTaskAsync method, my app crashes with an error stating:
The program '[1020] LC Points.WindowsPhone.exe' has exited with code 0 (0x0).
I've been following this example on SO but their is no Api method available in the SDK I'm using.
Does anyone know how to debug or resolve this posting issue?
I've submitted the publish_actions for review on the Facebook developer console, but don't think that's the reason the app is crashing.
This is the ShareApp Task I'm using to call the login and posting code:
private async Task ShareApp()
{
//Facebook app id
var clientId = "573586446116744";
//Facebook permissions
var scope = "public_profile, email, publish_actions";
var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
var fb = new FacebookClient();
var app = new FacebookClient(fb.AccessToken);
var loginUrl = fb.GetLoginUrl(new
{
client_id = clientId,
redirect_uri = redirectUri,
response_type = "token",
scope = scope
});
Uri startUri = loginUrl;
Uri endUri = new Uri(redirectUri, UriKind.Absolute);
WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None);
//Code to post app on the user's timeline after button click..crashes when program execution comes to this code:
var postArgs = new Dictionary<string, object>();
postArgs["link"] = "http://allaboutwindowsphone.com/software/developer/Brian-Varley.php";
postArgs["name"] = "More from BV Apps..";
postArgs["message"] = "I'm using LC Points to calculate my Leaving Cert Points!";
await app.PostTaskAsync("/me/feed", postArgs);
//app.Api("/me/feed", postArgs, HttpMethod.Post); //no Api method available which is why I've used PostTaskAsync instead.
}
This is the link to the repo on my GitHub for reference

Posting to FB Page error(s)

Scenario: I want to get user access token of the fb page admin by JS login and retrieving token ONE TIME, and will store that in database. Then daily, I want to do wall post to those page.
I am using JS to get the initial token and storing it. Then using c# FacebookSDK for the web requests.
FB.login(function (response) {
var r = response;
// get access token of the user and update in database
$("#FacebookAccessToken").val(response.authResponse.accessToken);
},
{
scope: 'manage_pages,publish_stream'
});
Now I am saving this token in database as I will be using this for future graph calls - is this right?
On server side when I need to do a post after a day I retrieve that token and do the processing as below:
// step 1 get application access token
var fb1 = new FacebookClient();
dynamic appTokenCLient = fb1.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "client_credentials",
scope = "manage_pages,publish_stream",
redirect_uri = siteUrl
});
var fbTokenSettingVal = GetTokenFromDB(); // getting access token from database which was stored during JS fb login
// step 2 extend token
var fb2 = new FacebookClient(appTokenCLient.access_token);
dynamic extendedToken = fb2.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "fb_exchange_token",
fb_exchange_token = fbTokenSettingVal.Val
});
var userExtendedToken = extendedToken.access_token; // get extended token and update database
// step 3 get page access token from the pages, that the user manages
var fb3 = new FacebookClient { AppId = appId, AppSecret = appSecret, AccessToken = userExtendedToken };
var fbParams = new Dictionary<string, object>();
var publishedResponse = fb3.Get("/me/accounts", fbParams) as JsonObject;
var data = JArray.Parse(publishedResponse["data"].ToString());
var pageToken = "";
foreach (var account in data)
{
if (account["name"].ToString().ToLower().Equals("PAGE_NAME"))
{
pageToken = account["access_token"].ToString();
break;
}
}
// step 4 post a link to the page - throws error !
var fb4 = new FacebookClient(pageToken);
fb4.Post("/PAGE_NAME/feed",
new
{
link = "http://www.stackoverflow.com"
});
The last 4th step throws error, when posting to selected page:
The user hasn't authorized the application to perform this action
Have tried several different ways, but in vain. Assume that there is just a simple step which I am doing wrong here.
Also, is it ok to extend the fb access token for user every time before making request?
Any way to check if token is expired or not?
If you want to use that access token for future. You need to take offline_access token and that token you need to store in database.
This offline accesstoken will be expire once user will change the password or delete your application from facebook account.
private void GetPermenentAccessTokenOfUser(string accessToken)
{
var client2 = new FacebookClient(accessToken);
//get permenent access token
dynamic result = client2.Post("oauth/access_token", new
{
client_id = _apiKey,
client_secret = _apiSecret,
grant_type = "fb_exchange_token",
fb_exchange_token = accessToken
});
_accessToken = result.access_token;
}
Looks like for new apps we need to apply for manage_pages permission from our application:
which I am doing now. As it shows error when doing login:
Also, the app needs to be live, so they can reproduce this permission and verify that we do need this permission to post to pages. Its good for fb users safety but a time taking process for developers.
Any way this can be skipped for testing purpose?

get an access token using Facebook C# SDK

Hi i am using the following code to get access token from facebook using C# SDK
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "clientId",
client_secret = "clientSecret",
redirect_uri = "redirectUri",
code = "code"
});
return result.access_token;
the above code works perfect most of the time but some times i gets this error
(OAuthException - #100) Invalid verification code format.
how to fix this problem??
What is your project type : WinForms , WPF , ASP.NET ?
if you are working with WinForms or WPF , you have to get the access_token form the Browser Control URL by requesting the OAuth Login Dialog and the return_type=token , then extract the valid access_token from the URL.
Otherwise , if you are working on Web Application using ASP.NET , you will have to redirect the user to the OAuth Dialog Login Page then the facebook will redirect you back with a code on the URL , you get this code from the QueryString and make an HTTPRequest to the Facebook to get the valid access_token .
you can use my method for doing that :
public string GetAccessTokenFromCode(string AppID, string AppSecret, string RedirectURL, string Code)
{
WebClient wc = new WebClient();
string u2 = "https://graph.facebook.com/oauth/access_token?client_id=" + AppID + "&redirect_uri=" + RedirectURL + "&client_secret=" + AppSecret + "&code=" + Code + "&state=anytexthere";
string access = wc.DownloadString(u2);
access = access.Substring(access.IndexOf("access_token") + 13);
if (access.Contains("&"))
{
string accesstoken = access.Substring(0, access.IndexOf("&"));
return accesstoken;
}
return access;
}
and you can call it from the Page_Load :
if (Request.QueryString["code"] != null)
{
code = Request.QueryString["code"].ToString();
string AT = GetAccessTokenFromCode(AppID, AppSecret, RedirectUrl, Code);
}
You should have the same redirect_uri as you did when asking for code.
Also there must be a trailing slash '/' at the end of the site url you configured in 'Website with Facebook Login' section on Facebook.
Here's a complete tutorial: Working with C# SDK
This page makes me wonder if your code should look more like this:
dynamic result = fbClient.Get("oauth/access_token", new
{
client_id = fbClient.AppId,
client_secret = fbClient.AppSecret,
grant_type = "fb_exchange_token",
fb_exchange_token = accessToken
});
Maybe your accessToken is timing out or something?
after downloading sdk from http://www.nuget.org/packages/Facebook.CSharp.SDK/
var config = new Dictionary<string, object>();
//your application id and secret from https://developers.facebook.com/apps
config.Add("appId", "3955.......");
config.Add("secret", "4c1d...............");
config.Add("fileUpload", true); //optional
FacebookClient client = new FacebookClient(config);
ulong facebookId = client.getUser(); //retrieve user id. if user is not added the app this value is 0
client.getAccessToken()
gives you the access token.

using Google Contacts Api Import Contacts C#

I am using Google Contacts Api. I am not sure whether I can send an Auth Token as a parameter.
string _token = _google.Token;
RequestSettings requestSettings = new RequestSettings("AppName",_token);
ContactsRequest contactsRequest = new ContactsRequest(requestSettings);
// Get the feed
Feed<Contact> feed = contactsRequest.GetContacts();
I get 401 Unauthorised as a response for this code, but if I send the username and password as parameters, I am able to get a response.
Whoops, sorry, I didn't quite get it right the first time. I'm using this code in a real app, I just do things a bit different in my code because I'm constantly refreshing tokens.
In any case, here's the proper logic:
// get this information from Google's API Console after registering your app
var parameters = new OAuth2Parameters
{
ClientId = #"",
ClientSecret = #"",
RedirectUri = #"",
Scope = #"https://www.google.com/m8/feeds/",
};
// generate the authorization url
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
// now use the url to authorize the app in the browser and get the access code
(...)
// get this information from Google's API Console after registering your app
parameters.AccessCode = #"<from previous step>";
// get an access token
OAuthUtil.GetAccessToken(parameters);
// setup connection to contacts service
var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));
// get each contact
foreach (var contact in contacts.GetContacts().Entries)
{
System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
}
FYI, after you call GetAccessToken() against your access code, your parameters data structure will include the AccessToken and RefreshToken fields. If you STORE these two values, you can set them in the parameters structure in subsequent calls (allowing you to skip asking for authorization in the future) and instead of calling GetAccessToken() simply call RefreshAccessToken(parameters) and you'll always have access to the contacts. Make sense? Here, take a look:
// get this information from Google's API Console after registering your app
var parameters = new OAuth2Parameters
{
ClientId = #"",
ClientSecret = #"",
RedirectUri = #"",
Scope = #"https://www.google.com/m8/feeds/",
AccessCode = "",
AccessToken = "", /* use the value returned from the old call to GetAccessToken here */
RefreshToken = "", /* use the value returned from the old call to GetAccessToken here */
};
// get an access token
OAuthUtil.RefreshAccessToken(parameters);
// setup connection to contacts service
var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));
// get each contact
foreach (var contact in contacts.GetContacts().Entries)
{
System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
}
Edit:
// generate the authorization url
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
// now use the url to authorize the app in the browser and get the access code
(...)
// get this information from Google's API Console after registering your app
var parameters = new OAuth2Parameters
{
ClientId = #"",
ClientSecret = #"",
RedirectUri = #"",
Scope = #"https://www.google.com/m8/feeds/",
AccessCode = #"<from previous step>",
};
// get an access token
OAuthUtil.GetAccessToken(parameters);
// setup connection to contacts service
var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));
// get each contact
foreach (var contact in contacts.GetContacts().Entries)
{
System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
}

Categories

Resources