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)
12626정성태5/3/202110266.NET Framework: 1056. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상 (2)파일 다운로드1
12625정성태5/3/20219234오류 유형: 714. error CS5001: Program does not contain a static 'Main' method suitable for an entry point
12624정성태5/2/202112994.NET Framework: 1055. C# - struct/class가 스택/힙에 할당되는 사례 정리 [10]파일 다운로드1
12623정성태5/2/20219640.NET Framework: 1054. C# 9 최상위 문에 STAThread 사용 [1]파일 다운로드1
12622정성태5/2/20216435오류 유형: 713. XSD 파일을 포함한 프로젝트 - The type or namespace name 'TypedTableBase<>' does not exist in the namespace 'System.Data'
12621정성태5/1/202110043.NET Framework: 1053. C# - 특정 레지스트리 변경 시 알림을 받는 방법 [1]파일 다운로드1
12620정성태4/29/202111994.NET Framework: 1052. C# - 왜 구조체는 16 바이트의 크기가 적합한가? [1]파일 다운로드1
12619정성태4/28/202112498.NET Framework: 1051. C# - 구조체의 크기가 16바이트가 넘어가면 힙에 할당된다? [2]파일 다운로드1
12618정성태4/27/202111042사물인터넷: 58. NodeMCU v1 ESP8266 CP2102 Module을 이용한 WiFi UDP 통신 [1]파일 다운로드1
12617정성태4/26/20218725.NET Framework: 1050. C# - ETW EventListener의 Keywords별 EventId에 따른 필터링 방법파일 다운로드1
12616정성태4/26/20218709.NET Framework: 1049. C# - ETW EventListener를 상속받았을 때 초기화 순서파일 다운로드1
12615정성태4/26/20216887오류 유형: 712. Microsoft Live 로그인 - 계정을 선택하는(Pick an account) 화면에서 진행이 안 되는 문제
12614정성태4/24/20219550개발 환경 구성: 570. C# - Azure AD 인증을 지원하는 ASP.NET Core/5+ 웹 애플리케이션 예제 구성 [4]파일 다운로드1
12613정성태4/23/20218594.NET Framework: 1048. C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (2) 관리 코드파일 다운로드1
12612정성태4/23/20218738.NET Framework: 1047. C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (1) PInvoke파일 다운로드1
12611정성태4/22/20217991오류 유형: 711. 닷넷 EXE 실행 오류 - Mixed mode assembly is build against version 'v2.0.50727' of the runtime
12610정성태4/22/20217802.NET Framework: 1046. C# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법파일 다운로드1
12609정성태4/22/20219094.NET Framework: 1045. C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법파일 다운로드1
12608정성태4/21/202110124.NET Framework: 1044. C# - Generic Host를 이용해 .NET 5로 리눅스 daemon 프로그램 만드는 방법 [9]파일 다운로드1
12607정성태4/21/20218645.NET Framework: 1043. C# - 실행 시점에 동적으로 Delegate 타입을 만드는 방법파일 다운로드1
12606정성태4/21/202112599.NET Framework: 1042. C# - enum 값을 int로 암시적(implicit) 형변환하는 방법? [2]파일 다운로드1
12605정성태4/18/20218617.NET Framework: 1041. C# - AssemblyID, ModuleID를 관리 코드에서 구하는 방법파일 다운로드1
12604정성태4/18/20217351VS.NET IDE: 163. 비주얼 스튜디오 속성 창의 "Build(빌드)" / "Configuration(구성)"에서의 "활성" 의미
12603정성태4/16/20218242VS.NET IDE: 162. 비주얼 스튜디오 - 상속받은 컨트롤이 디자인 창에서 지원되지 않는 문제
12602정성태4/16/20219445VS.NET IDE: 161. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 [1]
12601정성태4/15/20218538.NET Framework: 1040. C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
... 31  32  33  34  35  36  37  38  39  [40]  41  42  43  44  45  ...