Anche il token di accesso a Facebook ha un aspetto simile "1249203702 | 2.h1MTNeLqcLqw __. 86400.129394400-605430316 | -WE1iH_CV-afTgyhDPc"
se estrai la parte centrale usando | per dividere si ottiene
2.h1MTNeLqcLqw __. 86400.129394400-605430316
poi diviso di nuovo da -
l'ultima parte 605430316 è l'id utente.
Ecco il codice C # per estrarre l'id utente dal token di accesso:
public long ParseUserIdFromAccessToken(string accessToken)
{
Contract.Requires(!string.isNullOrEmpty(accessToken);
/*
* access_token:
* 1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
* |_______|
* |
* user id
*/
long userId = 0;
var accessTokenParts = accessToken.Split('|');
if (accessTokenParts.Length == 3)
{
var idPart = accessTokenParts[1];
if (!string.IsNullOrEmpty(idPart))
{
var index = idPart.LastIndexOf('-');
if (index >= 0)
{
string id = idPart.Substring(index + 1);
if (!string.IsNullOrEmpty(id))
{
return id;
}
}
}
}
return null;
}
AVVERTIMENTO:
la struttura del token di accesso non è documentata e potrebbe non adattarsi sempre allo schema precedente. Usalo a tuo rischio.
Aggiornamento a
causa di modifiche in Facebook. il metodo preferito per ottenere l'ID utente dal token di accesso crittografato è il seguente:
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
return (string)result["id"];
}
catch (FacebookOAuthException)
{
return null;
}