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)
12769정성태8/11/20216404오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main 두 번째 이야기
12768정성태8/10/20217422.NET Framework: 1085. .NET 6에 포함된 신규 BCL API [1]파일 다운로드1
12767정성태8/10/20218472오류 유형: 752. Python - ImportError: No module named pip._internal.cli.main
12766정성태8/9/20217009Java: 32. closing inbound before receiving peer's close_notify
12765정성태8/9/20216325Java: 31. Cannot load JDBC driver class 'org.mysql.jdbc.Driver'
12764정성태8/9/202144786Java: 30. XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid
12763정성태8/9/20217781Java: 29. java.lang.NullPointerException - com.mysql.jdbc.ConnectionImpl.getServerCharset
12762정성태8/8/202111281Java: 28. IntelliJ - Unable to open debugger port 오류
12761정성태8/8/20218523Java: 27. IntelliJ - java: package javax.inject does not exist [2]
12760정성태8/8/20215939개발 환경 구성: 594. 전용 "Command Prompt for ..." 단축 아이콘 만들기
12759정성태8/8/20219067Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [2]파일 다운로드1
12758정성태8/7/20218409오류 유형: 751. Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
12757정성태8/7/20219091Java: 25. IntelliJ + Spring Framework 프로젝트 생성
12756정성태8/6/20217910.NET Framework: 1084. C# - .NET Core Web API 단위 테스트 방법 [1]파일 다운로드1
12755정성태8/5/20217051개발 환경 구성: 593. MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법파일 다운로드1
12754정성태8/5/20217985오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/20218191오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/20216309개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/20219343개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/20216147디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/20215568개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/20216182개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/20216783오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
12746정성태7/31/20218761개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
12745정성태7/31/20216616개발 환경 구성: 587. Azure Active Directory - tenant의 관리자 계정 로그인 방법
12744정성태7/30/20217226개발 환경 구성: 586. Azure Active Directory에 연결된 App 목록을 확인하는 방법?
... 31  32  33  [34]  35  36  37  38  39  40  41  42  43  44  45  ...