액세스 토큰을 사용하여 Facebook 사용자 ID를 얻는 방법
Facebook 데스크톱 애플리케이션이 있고 Graph API를 사용하고 있습니다. 액세스 토큰을 얻을 수 있지만 그 후에는 사용자 ID를 얻는 방법을 모릅니다.
내 흐름은 다음과 같습니다.
필요한 모든 확장 권한과 함께 사용자를 https://graph.facebook.com/oauth/authorize 로 보냅니다 .
내 리디렉션 페이지에서 Facebook에서 코드를 얻습니다.
그런 다음 API 키로 graph.facebook.com/oauth/access_token에 대한 HTTP 요청을 수행 하고 응답에서 액세스 토큰을 얻습니다.
그 시점부터 사용자 ID를 얻을 수 없습니다.
이 문제를 어떻게 해결할 수 있습니까?
Graph API를 사용하여 현재 사용자 ID를 얻으려면 다음 주소로 요청을 보내십시오.
https://graph.facebook.com/me?access_token=...
가장 쉬운 방법은
https://graph.facebook.com/me?fields=id&access_token="xxxxx"
그러면 사용자 ID 만 포함 된 json 응답이 표시됩니다.
페이스 북 액세스 토큰도 비슷하게 보입니다. "1249203702 | 2.h1MTNeLqcLqw __. 86400.129394400-605430316 | -WE1iH_CV-afTgyhDPc"
사용하여 중간 부분을 추출하면 | 당신을 나누기 위해
2.h1MTNeLqcLqw __. 86400.129394400-605430316
그런 다음 다시-
마지막 부분 605430316은 사용자 ID입니다.
다음은 액세스 토큰에서 사용자 ID를 추출하는 C # 코드입니다.
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;
}
경고 : 액세스 토큰의 구조는 문서화되지 않았으며 항상 위의 패턴에 맞지 않을 수 있습니다. 자신의 책임하에 사용하십시오.
업데이트 Facebook 변경으로 인해. 암호화 된 액세스 토큰에서 사용자 ID를 가져 오는 데 선호되는 방법은 다음과 같습니다.
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
return (string)result["id"];
}
catch (FacebookOAuthException)
{
return null;
}
onSuccess (LoginResult loginResult) 에서 아래 코드를 사용할 수 있습니다.
loginResult.getAccessToken (). getUserId ();
다른 Graph API를 누르기 만하면됩니다.
https://graph.facebook.com/me?access_token={access-token}
It will give your e-mail Id and user Id (for Facebook) also.
With the newest API, here's the code I used for it
/*params*/
NSDictionary *params = @{
@"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
@"fields": @"id"
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"me"
parameters:params
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSDictionary *res = result;
//res is a dict that has the key
NSLog([res objectForKey:@"id"]);
in FacebookSDK v2.1 (I can't check older version). We have
NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;
However according to the comment in FacebookSDK
@discussion This may not be populated for login behaviours such as the iOS system account.
So may be you should check if it is available, and then whether use it, or call the request to get the user id
Check out this answer, which describes, how to get ID response. First, you need to create method get data:
const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
const options = {
host: 'graph.facebook.com',
port: 443,
path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
method: 'GET'
};
let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
const request = https.get(options, (result) => {
result.setEncoding('utf8');
result.on('data', (chunk) => {
buffer += chunk;
});
result.on('end', () => {
callback(buffer);
});
});
request.on('error', (e) => {
console.log(`error from facebook.getFbData: ${e.message}`)
});
request.end();
}
Then simply use your method whenever you want, like this:
getFbData(access_token, '/me?fields=id&', (result) => {
console.log(result);
});
참고URL : https://stackoverflow.com/questions/3546677/how-to-get-the-facebook-user-id-using-the-access-token
'Programing' 카테고리의 다른 글
Html을 일반 텍스트로 어떻게 변환합니까? (0) | 2020.09.15 |
---|---|
C #의 팩토리 패턴 : 팩토리 클래스에서만 개체 인스턴스를 만들 수 있는지 확인하는 방법은 무엇입니까? (0) | 2020.09.15 |
CMD가 관리자로 실행 중인지 / 상승 된 권한이 있는지 감지하는 방법은 무엇입니까? (0) | 2020.09.15 |
웹 사이트에 Favicon 추가 (0) | 2020.09.15 |
Sourcetree-최신 버전으로 업그레이드, git-flow 누락 (0) | 2020.09.15 |