Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 7개 있습니다.)
.NET Framework: 193. 페이스북(Facebook) 계정으로 로그인하는 C# 웹 사이트 제작
; https://www.sysnet.pe.kr/2/0/953

.NET Framework: 198. 윈도우 응용 프로그램에 Facebook 로그인 연동
; https://www.sysnet.pe.kr/2/0/970

.NET Framework: 245. ASP.NET 서버 측 코드에서 페이스북 계정 연동하는 방법
; https://www.sysnet.pe.kr/2/0/1143

개발 환경 구성: 313. Nuget Facebook 라이브러리를 이용해 ASP.NET 웹 폼과 로그인 연동하는 방법
; https://www.sysnet.pe.kr/2/0/11182

개발 환경 구성: 436. 페이스북 HTTPS 인증을 localhost에서 테스트하는 방법
; https://www.sysnet.pe.kr/2/0/11855

개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
; https://www.sysnet.pe.kr/2/0/12189

닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
; https://www.sysnet.pe.kr/2/0/13526




Nuget Facebook 라이브러리를 이용해 ASP.NET 웹 폼과 로그인 연동하는 방법

Visual Studio의 Nuget 패키지 관리자를 통해 Facebook 라이브러리를 설치할 수 있습니다.

Install-Package Facebook

당연히 소스 코드도 공개한 상태입니다.

Facebook - The Facebook SDK for .NET helps developers build web, desktop, phone and Windows Store applications that integrate with Facebook.
; https://github.com/facebook-csharp-sdk/facebook-csharp-sdk

위의 라이브러리를 이용한 ASP.NET 최소 예제도 다음의 글에서 공개했습니다.

Facebook Login with ASP.NET Web Forms
; https://learn.microsoft.com/en-us/archive/blogs/nickpinheiro/facebook-login-with-asp-net-web-forms

예제 소스 코드는 다음의 github에 있습니다.

nickpinheiro/FacebookLoginASPnetWebForms 
; https://github.com/nickpinheiro/FacebookLoginASPnetWebForms

그런데, 실제로 위의 코드를 다운로드해 실행해 보면 다음과 같은 예외가 발생합니다.

Server Error in '/' Application.

The remote server returned an error: (400) Bad Request. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

Source Error: 


Line 46:             HttpWebRequest eat = (HttpWebRequest)HttpWebRequest.Create(eatTargetUri);
Line 47: 
Line 48:             StreamReader eatStr = new StreamReader(eat.GetResponse().GetResponseStream());
Line 49:             string eatToken = eatStr.ReadToEnd().ToString().Replace("access_token=", "");
Line 50: 

Source File: D:\MyGit\FacebookGraph\Account\user.aspx.cs ?? Line: 48 

Stack Trace: 


[WebException: The remote server returned an error: (400) Bad Request.]
   System.Net.HttpWebRequest.GetResponse() +1322
   FacebookLoginASPnetWebForms.account.user.GetFacebookUserData(String code) in D:\MyGit\FacebookGraph\Account\user.aspx.cs:48
   FacebookLoginASPnetWebForms.account.user.Page_Load(Object sender, EventArgs e) in D:\MyGit\FacebookGraph\Account\user.aspx.cs:24
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678

문제가 되는 코드를 보면,

Uri targetUri = new Uri("https://graph.facebook.com/oauth/access_token?client_id=" + ...);
HttpWebRequest at = (HttpWebRequest)HttpWebRequest.Create(targetUri);

System.IO.StreamReader str = new System.IO.StreamReader(at.GetResponse().GetResponseStream());
string token = str.ReadToEnd().ToString().Replace("access_token=", "");

string[] combined = token.Split('&');
string accessToken = combined[0];

Uri eatTargetUri = new Uri("https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=" + ... "&fb_exchange_token=" + accessToken);
HttpWebRequest eat = (HttpWebRequest)HttpWebRequest.Create(eatTargetUri);

최초의 "/oauth/access_token?client_id="으로의 요청은 값을 잘 반환하는데, 두 번째인 "/oauth/access_token?grant_type=" 요청에서 "Bad Request"라는 오류가 발생한 것입니다. 원인은 간단한데요, 첫 번째 요청의 반환값으로 받은 "accessToken" 변수의 값이 다음과 같이 설정되어 있기 때문입니다.

{
	"access_token":"...[생략]...",
	"token_type":"bearer",
	"expires_in":5182206
}

즉, 두 번째 요청의 URL에 전달되는 "fb_exchange_token=" + accessToken의 문자열로 JSON 텍스트 전체가 할당되기 때문에 당연히 Bad Request 오류가 발생하게 됩니다. 따라서, JSON 반환값 안에 있는 "access_token"의 값을 풀어내 그 값을 전달해야 합니다. 이를 위해 간단하게 AccessToken 클래스 하나 만들어 주고,

public class AccessToken
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}

다음과 같이 역 직렬화 한 다음 사용해 주시면 됩니다.

string accessToken = combined[0];

JavaScriptSerializer sr = new JavaScriptSerializer();
Facebook.AccessToken accessTokenInfo = sr.Deserialize<Facebook.AccessToken>(accessToken);

// 이하, access_token 인자가 필요한 요청마다 accessTokenInfo.access_token을 전달

다음은 GetFacebookUserData를 이렇게 해서 바꾼 전체 소스 코드입니다.

protected List<Facebook.User> GetFacebookUserData(string code)
{
    // Exchange the code for an access token
    Uri targetUri = new Uri("https://graph.facebook.com/oauth/access_token?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&client_secret=" + ConfigurationManager.AppSettings["FacebookAppSecret"] + "&redirect_uri=http://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + "/account/user.aspx&code=" + code);
    HttpWebRequest at = (HttpWebRequest)HttpWebRequest.Create(targetUri);

    System.IO.StreamReader str = new System.IO.StreamReader(at.GetResponse().GetResponseStream());
    string token = str.ReadToEnd().ToString().Replace("access_token=", "");

    // Split the access token and expiration from the single string
    string[] combined = token.Split('&');
    string accessToken = combined[0];

    JavaScriptSerializer sr = new JavaScriptSerializer();
    Facebook.AccessToken accessTokenInfo = sr.Deserialize<Facebook.AccessToken>(accessToken);

    // Exchange the code for an extended access token
    Uri eatTargetUri = new Uri("https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=" 
        + ConfigurationManager.AppSettings["FacebookAppId"] 
        + "&client_secret=" 
        + ConfigurationManager.AppSettings["FacebookAppSecret"] 
        + "&fb_exchange_token=" + accessTokenInfo.access_token);
    HttpWebRequest eat = (HttpWebRequest)HttpWebRequest.Create(eatTargetUri);

    StreamReader eatStr = new StreamReader(eat.GetResponse().GetResponseStream());
    string eatToken = eatStr.ReadToEnd().ToString().Replace("access_token=", "");

    // Split the access token and expiration from the single string
    string[] eatWords = eatToken.Split('&');
    string extendedAccessToken = eatWords[0];

    // Request the Facebook user information
    Uri targetUserUri = new Uri("https://graph.facebook.com/me?fields=first_name,last_name,gender,locale,link&access_token=" 
        + accessTokenInfo.access_token);
    HttpWebRequest user = (HttpWebRequest)HttpWebRequest.Create(targetUserUri);

    // Read the returned JSON object response
    StreamReader userInfo = new StreamReader(user.GetResponse().GetResponseStream());
    string jsonResponse = string.Empty;
    jsonResponse = userInfo.ReadToEnd();

    // Deserialize and convert the JSON object to the Facebook.User object type
    string jsondata = jsonResponse;
    Facebook.User converted = sr.Deserialize<Facebook.User>(jsondata);

    // Write the user data to a List
    List<Facebook.User> currentUser = new List<Facebook.User>();
    currentUser.Add(converted);

    // Return the current Facebook user
    return currentUser;
}

참고로, "nickpinheiro/FacebookLoginASPnetWebForms" 프로젝트를 fork한 제 github repo에 위의 변경 사항을 적용해 두었으니 참고하시면 됩니다.

stjeong/FacebookLoginASPnetWebForms 
; https://github.com/stjeong/FacebookLoginASPnetWebForms




위의 예제 프로젝트를 테스트하려면 우선 facebook 개발자 사이트에 접속해,

facebook for developers
; https://developers.facebook.com/apps

"새 앱 추가"를 누른 다음 "앱 ID"와 "앱 시크릿 코드"를 받아 예제 프로젝트의 web.config에 각각 값을 채워야 합니다.

<appSettings>
    <add key="FacebookAppId" value="...앱 ID..."/>
    <add key="FacebookAppSecret" value="...앱 시크릿 코드..."/>
</appSettings>

그다음 localhost에서 테스트할 수 있도록 "Facebook 로그인" / "설정" 메뉴에 가서 "유효한 OAuth 리디렉션 URI"로 자신의 테스트 URL을 등록해 주시면 됩니다.

facebook_sample_1.png

그나저나... 좋아졌군요. ^^ 예전에서는 localhost 등록이 안되어서 테스트 전용으로 "새 앱 추가"를 다시 해 URI를 등록해야 했었는데, 이젠 그럴 필요가 없어졌습니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/31/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12845정성태10/6/20218098.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216132오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216590스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202124807오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218377스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218429.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219495.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219146.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218088VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217678Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20218947.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217320오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216771VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217609VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216151VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218368오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202110020.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/20218147.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/20218128스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202110372.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/20217928개발 환경 구성: 603. GoLand - WSL 환경과 연동
12824정성태9/2/202117004오류 유형: 760. 파이썬 tensorflow - Dst tensor is not initialized. 오류 메시지
12823정성태9/2/20216740스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
12822정성태9/1/202111947오류 유형: 759. 파이썬 tensorflow - ValueError: Shapes (...) and (...) are incompatible [2]
12821정성태9/1/20217501.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법
12820정성태9/1/20217806VC++: 147. Golang - try/catch에 대응하는 panic/recover [1]파일 다운로드1
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...