get permanent facebook access token - c#

I have used JSDK to authenticate user for my facebook app.
I am getting the access token but it gets expired within 1/2 hours.
So how can I get long term Access Token?
The code I have used is:
var fb = new FacebookClient();
Dictionary<string,Object> sParams=new Dictionary<string,Object>();
sParams.Add("client_id",My_App_ID);
sParams.Add("client_secret",My_App_Secret);
sParams.Add("grant_type","fb_exchange_token");
sParams.Add("fb_exchange_token",Short_lived_accessToken);
dynamic result = fb.Get("oauth/access_token",sParams);
fb.AccessToken = result.access_token;
but it gives me error Invalid JSON String at line dynamic result = fb.Get("oauth/access_token",sParams);
What wrong am I doing here?

Use this code:
var client = new FacebookClient(Short_lived_accessToken);
dynamic result = client.Post("oauth/access_token", new
{
client_id = My_App_ID,
client_secret = My_App_Secret,
grant_type = "fb_exchange_token",
fb_exchange_token = Short_lived_accessToken
});
Response.Write("Long live access token: [" + result.access_token + "]");
Hope it helps.

The return you will get from the endpoint simply is not JSON, but just plain text in the form
access_token=new_long-lived_access_token&expires=5130106
So you will have to tell your application somehow(?), that the result is not JSON; or you might have to use a different method altogether to make the request, if FacebookClient::Get always expects the answer to be JSON.

Related

ASP.Net Core 3.1 Identity - Generating Password Reset Token Issue

I am developing a site where the users will be able to click a "Forgot My Password" button to reset their passwords.
Currently, once the email has been validated, the following code should generate a token to be emailed to the user:
if(validUser != null)
{
var generationTime = DateTime.Now;
var pwToken = await _userManager.GeneratePasswordResetTokenAsync(validUser);
await _userManager.UpdateAsync(validUser);
var url = $"https://{Request.Host}/verify/{HttpUtility.UrlEncode(pwToken)}";
//EmailHelper.SendMagicLinkEmail(validUser, url, Request);
return new RedirectResult("/");
}
All information online regarding this seems to suggest that this is the way to do things. I have set up the Default token providers in the Startup.csfile too:
identityOptions: o => {
o.User.RequireUniqueEmail = true;
o.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultProvider;
o.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultProvider;
},
Yet when a token is generated it produces a large token such as this:
CfDJ8CnvAYtZf+1IjXpKUM7+umDYEaImg2SPFglPX3Y8RmYpEfg5zpK8xL54lvlbJUd54CaIzzYlff/GU+xKKS8mmG5UdC1zdk24nOsJNpIlmC3P5V72BchS4P9DGFTR77XiKbMAAYymnMomS2zCdTKh+E4bn9RI6FVinMecG1HR7nSHmOI2McbXHBFTanI/0uwxH5WI/Dj4AFTBP39ni7mfKkeWz2nJ5pTemELJJ6pYP50+
The problem here is obviously the forward slashes, which cause issues with routing so are encoded out here:
var url = $"https://{Request.Host}/verify/{HttpUtility.UrlEncode(pwToken)}";
The problem is that even with that, .Net Core seems to un-encode it and produce the following error when the generated link is accessed:
This error isn't necessarily the issue, and I do understand it's importance. Yet I can't seem to find any explanation as to why this token is behaving this way. All online examples seem to produce a fairly standard GUID style token, not something such as this.
Does anyone know why this might be happening?
Cheers
You may want to try the Url.Action() method:
Example:
var token = userManager.GeneratePasswordResetTokenAsync(user).Result;
var resetLink = Url.Action("ResetPassword","Account", new { token = token }, protocol: HttpContext.Request.Scheme);
var message = "Click here to reset your password";
//Then send your message to the user
Note in the example above the email must be HTML for the link to work
The token looks fairly normal to me.
I think the URL encoding method you'd want to use is Uri.EscapeDataString. What I've personally done is using a UriBuilder and escaped the query string values (in this case for email confirmation):
var uriBuilder = new UriBuilder
{
Scheme = "https",
Host = "my.website.com",
Path = "/confirmEmail",
Query = $"email={Uri.EscapeDataString(email)}&token={Uri.EscapeDataString(token)}"
};
var fullUrl = uriBuilder.Uri.AbsoluteUri;
For you that'd be:
var uriBuilder = new UriBuilder
{
Scheme = "https",
Host = Request.Host,
Path = $"/verify/{Uri.EscapeDataString(pwToken)}"
};
var fullUrl = uriBuilder.Uri.AbsoluteUri;

I got success to get a new facebook access token for long time 60 days . How can i test/check that it is for 60 days?

This is the method:
public static string RenewToken(string existingToken)
{
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token",
new
{
client_id = 137,
client_secret = "a45",
grant_type = "fb_exchange_token",
fb_exchange_token = existingToken
});
return result.access_token;
}
And in the top of the form i have two variables:
string ShortaccessToken
string LongaccessToken
The first contain the old/working short time access token.
The second contain the new/working long time access token code.
And i use it in my constructor used it once:
RenewToken(ShortaccessToken);
And got the new one token code and im using in my code now the long one variable and its working its posting.
But my question is now how can i check/find untill when my new access token code will work ? When it will expire what date ?
You can verify this by calling:
GET /debug_token?input_token={input-token}&access_token={access-token}
Where {access-token} is your App Access Token, as described here: https://developers.facebook.com/docs/facebook-login/access-tokens/#debug
Check the contents of the expires_at field.

Aweber C# Api unauthorized - AccessToken key is invalid

I am having an issue with the Aweber C# api from: http://aweber.codeplex.com/
I am getting an unauthorized response from the following code. I was wondering if someone could help me see what I am missing please?
String consumerKey = "####";
String consumerSecret = "####";
API api = new API(consumerKey, consumerSecret);
api.OAuthToken = "####";
api.OAuthTokenSecret = "####";
api.OAuthVerifier = "##";
Aweber.Entity.Account account = api.getAccount();
I am assuming I am missing something important, but I cant figure out what is is.
Thanks in advance for your help.
D.
You need to add following code before api.getAccount();
// Set callback url (if not set will default to this page)
api.CallbackUrl = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Authorize.aspx";
// Get request token
api.get_request_token();
// Save the token and secret in session
HttpContext.Current.Session.Add("oauth_token", api.OAuthToken);
HttpContext.Current.Session.Add("oauth_token_secret", api.OAuthTokenSecret);
// Will redirect user to the Aweber authorize page
api.authorize();

debug access token using c#

i want to know when the access token will expire
i am using httprequest and getting response from the request that contain the link:
https://developers.facebook.com/tools/debug/access_token?q=ACCESS_TOKEN
and searching for the word Expires and trying to read the string between parenthesis which contain (in about x minutes)
but getting error that logged out can any one help me please ?
string site = "https://developers.facebook.com/tools/debug/access_token?q=";
string token = "";
getRequest = (HttpWebRequest)WebRequest.Create(site + token);
string result;
HttpWebResponse res = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
result = sr.ReadToEnd();
}
Console.WriteLine(result);
Console.WriteLine(result.Contains("Expires"));
i am getting false i need to have a result that contain the string "Expires" and read the time that will expire
You can read the docs at https://developers.facebook.com/docs/howtos/login/debugging-access-tokens/
Make a request to https://graph.facebook.com/debug_token?input_token=INPUT_TOKEN&access_token=ACCESS_TOKEN
input_token: the Access Token to debug
access_token: your App Access Token or a valid User Access Token from a developer of the app.
If you are using the FB C# SDK (http://csharpsdk.org/)
var fb = new FacebookClient("app_access_token");
dynamic result = fb.Get("debug_token", new { input_token = "access_token_to_debug" });
var appId = result.data.app_id;
var isValid = result.data.is_valid;
var application = result.data.application;
var userId = result.data.user_id;
var expiresAt = result.data.expires_at;
var scopes = result.data.scopes;
You can learn how to get the app access token at http://csharpsdk.org/docs/faq I also updated the docs to include debugging the access token.
Note: When you get the access token from the user make sure to store the expiry dates too, so you can avoid this call.

Problem retrieving an access token with code returned

I am having a problem retrieving the user's access token after he/she has authorized my Facebook application to access their information and post for them, etc... Facebook returns a code query string to my website, so I can receive the access token for the user. I use the following code to get the access code.
string AppKey = "[REMOVED]";
string AppSecret = "[REMOVED]";
var oAuth = new Facebook.FacebookOAuthClient();
oAuth.AppId = AppKey;
oAuth.AppSecret = AppSecret;
oAuth.RedirectUri = new Uri("http://www.mywebsite.com");
Label3.Text = Request.QueryString["code"];
try
{
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
string accessTokenString = accessToken.ToString();
HttpCookie aCookie = new HttpCookie("MyWebsite_FBAccessToken");
aCookie.Value = accessTokenString;
Response.Cookies.Add(aCookie);
Response.Redirect("~/Process/ProcessToken.aspx");
}
catch (Facebook.FacebookOAuthException error)
{
Label2.Text = error.Message;
}
My code gets held up here:
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
And I receive the following error.
(OAuthException) Error validating verification code.
Does this seem like there is a problem with my code, or does it look like there may be a setting problem with my Facebook application? I know my App ID and Secret are correct.

Categories