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




ASP.NET 서버 측 코드에서 페이스북 계정 연동하는 방법

제 웹 사이트는 전에 설명드린 것처럼, 클라이언트 측의 "Login" 버튼을 통해서 자바 스크립트를 이용하여 로그인이 이루어지는 방식으로 페이스북과 연동이 됩니다.

페이스북(Facebook) 계정으로 로그인하는 C# 웹 사이트 제작
; https://www.sysnet.pe.kr/2/0/953

Facebook 연동 - API Error Description: Invalid OAuth 2.0 Access Token
; https://www.sysnet.pe.kr/2/0/959

그런데, (당연하겠지만 ^^) 서버 측에서 로그인 처리를 하는 방법도 있습니다. 이번엔 그 방법을 알아보고, 제 웹 사이트에서도 그렇게 적용해 보았습니다. ^^




그사이 제법 편한 라이브러리도 공개되어 있더군요.

Facebook Graph Toolkit - Latest Release: Version 2.0 beta
; http://fgt.codeplex.com/

ASP.NET Sample App
; http://www.facebook.com/apps/application.php?id=110010620072#!/apps/application.php?id=110010620072&sk=wall&filter=2

Site Integration Example
; http://computerbeacon.net/downloads/getfile.ashx?filename=fbsitetest_v2.zip

위의 "http://fgt.codeplex.com/" 웹 사이트를 통해서 "Facebook Graph Toolkit 2.1" 다운로드해 아래의 2가지 DLL을 제 웹 사이트에 참조 추가했습니다.

  • Facebook Graph Toolkit.dll
  • JSON.dll

이제 web.config을 열어서 "Facebook Graph Toolkit"과 "Facebook"을 연결하기 위한 설정을 해줍니다.

<configSections>
    <section name="FacebookGraphToolkitConfiguration" type="Facebook_Graph_Toolkit.FacebookGraphToolkitConfiguration"/>
</configSections>

<FacebookGraphToolkitConfiguration FacebookAppID="xxxxxxxxxxx" FacebookAppSecret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>

그다음, '세션' 설정을 추가해 주어야 합니다. 왜냐하면, "Facebook Graph Toolkit"에서 내부적으로 ASP.NET 세션을 사용하기 때문인데요. 음... 어쩔 수 없군요. ^^ 제 웹 사이트의 경우에 세션을 사용하지는 않았지만, 이것 때문에 활성화를 시켰습니다.

<system.web>
    ...[생략]...
    <sessionState mode="InProc"/>
    <pages enableSessionState="true" ...[생략]... />
</system.web>

자, 이제 소스 코드를 변경해 볼텐데요. 로그인 버튼을 포함한 aspx의 cs 파일을 열어서, SocialPage를 상속받도록 변경해 주어야 합니다.

using Facebook_Graph_Toolkit;

public class MyPage : SocialPage
{
...
}

그다음, 해당 페이지의 PreInit 이벤트에서 "ExtendedPermissions"를 설정합니다. 지난번 글에 보면, 제 홈페이지의 경우 fb:login 버튼에 이 값들을 설정해 두고 있었는데요.

<fb:login-button perms="email,user_website"></fb:login-button>

만약, 위와 같은 정보가 필요 없다면, 이 부분의 설정은 생략해도 됩니다. 하지만, 제 웹 사이트의 경우에는 필요했기 때문에 아래와 같이 OnPreInit 메서드를 재정의 해주었습니다.

protected override void OnPreInit(EventArgs e)
{
    base.OnPreInit(e);

    this.ExtendedPermissions = "email,user_website";
}

그다음, 로그인 버튼을 aspx 웹 페이지에 추가해 주고,

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="/login-button.png" 
    onclick="ImageButton1_Click" />

로그인 버튼이 눌렸을 때의 서버 측 이벤트 핸들러에서 단순하게 SocialPage.RedirectToFacebookAuthorization 메서드를 호출해 주면 됩니다.

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    this.RedirectToFacebookAuthorization();
}

그럼, 내부적으로 "https://graph.facebook.com/oauth/authorize" 웹 페이지를 클라이언트 측 웹 브라우저가 방문하게 되고 로그인하게 됩니다. 정상적으로 로그인을 했으면 facebook 측에서는 다시 사용자가 원래 방문했던 웹 사이트로 redirection을 해줍니다.

그럼, Page의 부모 클래스였던 SocialPage의 OnLoad 메서드 내에서는, 재지정되어 전송된 URL로부터 "code" 쿼리 문자열 값을 알아내서 내부적으로 SocialPage.Api 클래스에 기본적인 Facebook 관련 정보들을 설정해 줍니다.

이때부터는, facebook으로부터 자유롭게 정보 조회를 할 수 있는데요. 예를 들어, 현재 로그인한 사용자 정보는 다음과 같이 구할 수 있습니다.

Facebook_Graph_Toolkit.GraphApi.User fbUser = new User("me", Api.AccessToken);

string userName = fbUser.Name;
string email = fbUser.Email;
string uid = fbUser.ID;




그런데, 2가지 문제가 있더군요. 첫 번째는, fbUser에서 제공되는 정보에는 확장 속성으로 요청한 "user_website" 값이 없다는 점입니다. 이를 해결하려면 페이스북에서 배포되는 Graph API를 그대로 사용하면 됩니다. 어차피 AccessToken 값만 있으면 되기 때문에 다음과 같이 구해올 수 있습니다.

Facebook.FacebookAPI api = new Facebook.FacebookAPI(Api.AccessToken);
Facebook.JSONObject me = null;
me = api.Get("/me");

if (me.Dictionary.ContainsKey("website") == true)
{
    Facebook.JSONObject value = me.Dictionary["website"];
    if (value != null)
    {
        string user_website = value.String;
    }
}

또 한 가지는, 이건 아마도 페이스북의 문제인 것 같습니다.

예를 들어, 사용자가 방문한 웹 사이트가 "http://test.com"라고 할 때, 이런 URL로 방문한 상태에서는 정상적으로 페이스북 로그인이 이뤄지지만, 쿼리 문자열을 하나라도 포함하고 있으면 예외가 발생했습니다. 즉, "http://test.com/test.aspx?myValue=0"과 같이 myValue라는 쿼리 문자열을 포함하면 "Facebook Graph Toolkit"을 사용하면 예외가 발생하고 이벤트 로그에 다음과 같은 기록을 볼 수 있습니다.

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Date:          2011-10-09 오후 10:10:28
Event ID:      1309
Task Category: Web Event
Level:         Warning
Keywords:      Classic
User:          N/A
Computer:      Web2008.testpc.co.kr
Description:
Event code: 3005 
Event message: An unhandled exception has occurred. 
Event time: 2011-10-09 오후 10:10:28 
Event time (UTC): 2011-10-09 오후 1:10:28 
Event ID: 478a718c878c40dea2b712c611343e81 
Event sequence: 36 
Event occurrence: 3 
Event detail code: 0 
 
Application information: 
    Application domain: /LM/W3SVC/1/ROOT-39-129632393463486808 
    Trust level: Full 
    Application Virtual Path: / 
    Application Path: C:\inetpub\wwwroot\ 
    Machine name: Web2008 
 
Process information: 
    Process ID: 3108 
    Process name: w3wp.exe 
    Account name: NT AUTHORITY\SYSTEM 
 
Exception information: 
    Exception type: FacebookException 
    Exception message: OAuthException : Error validating verification code.
   at Facebook_Graph_Toolkit.Helpers.WebResponseHelper.GetWebResponseObject(String url)
   at Facebook_Graph_Toolkit.Helpers.WebResponseHelper.GetWebResponse(String url)
   at Facebook_Graph_Toolkit.SocialPage.OnLoad(EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
 
Request information: 
    Request URL: http://test.com/test.aspx?myValue=0&code=...[생략]... 
    Request path: /Default.aspx 
    User host address: 192.168.50.2
    User:  
    Is authenticated: False 
    Authentication Type:  
    Thread account name: NT AUTHORITY\SYSTEM 
 
Thread information: 
    Thread ID: 25 
    Thread account name: NT AUTHORITY\SYSTEM 
    Is impersonating: False 
    Stack trace:    at Facebook_Graph_Toolkit.Helpers.WebResponseHelper.GetWebResponseObject(String url)
   at Facebook_Graph_Toolkit.Helpers.WebResponseHelper.GetWebResponse(String url)
   at Facebook_Graph_Toolkit.SocialPage.OnLoad(EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

문제의 원인을 파악하기 위해서는 SocialPage.RedirectToFacebookAuthorization 메서드 내부를 들여다 보아야 합니다.

protected void RedirectToFacebookAuthorization()
{
    this.FacebookAppConfigManager.Initialize();
    string url = string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", this.FacebookAppConfigManager.FacebookAppID, base.Request.Url.AbsoluteUri, this.ExtendedPermissions);
    base.Response.Redirect(url, true);
}

보시면, redirect_uri에 "base.Request.Url.AbsoluteUri" 값을 사용하는데, 결국 "http://test.com/test.aspx?myValue=0" 값이 들어가는 것을 볼 수 있는데요. "Facebook Graph Toolkit"을 사용하지 않고 직접 페이스북에 쿼리 문자열을 포함한 체로 방문을 해봐도 오류가 발생합니다. (쿼리 문자열 부분을 제외하면 로그인이 성공합니다.) 비록, 페이스북 자체에서 쿼리 문자열을 받아들이는 것에 오류가 있다는 것이지만 사용자 웹 사이트에서는 redirect_uri 값으로 넘어가는 URL에 쿼리 문자열이 들어가지 않도록 주의를 해줘야 합니다.

만약, 부득이하게 쿼리 문자열이 포함되어 있는 웹 페이지에서 로그인 시도가 발생한다면? 어쩔 수 없습니다. "Facebook Graph Toolkit"의 소스 코드를 변경해 주는 것이 좋습니다. (소스 코드는 "http://fgt.codeplex.com/" 내에서 다운로드 할 수 있습니다.)

가능한 변경을 최소화하기 위해, 제 경우에는 "this.FacebookAppConfigManager.Initialize();"의 Initialize 메서드를 internal에서 public으로 바꿔주고 다시 소스 코드를 빌드했습니다. 그런 다음, 직접 SocialPage를 상속받은 웹 페이지에서 "RedirectToFacebookAuthorization" 역할을 하는 별도의 메서드를 다음과 같이 구현해 주었습니다.

public void RedirectToFacebook()
{
    string thisUrl = Request.Url.GetLeftPart(UriPartial.Path);

    this.FacebookAppConfigManager.Initialize();

    string url = string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
        this.FacebookAppConfigManager.FacebookAppID, thisUrl, this.ExtendedPermissions);

    base.Response.Redirect(url, true);
}





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/5/2021]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13667정성태7/7/20246608닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247686Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247863Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247470닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247477닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247398Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247504오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247843개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248219개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247895닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248057Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247842닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247787오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247925닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249232닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248472닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248397개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247947오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248264오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249324개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247742오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248197개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248855닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248294오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248196스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248659Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...