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)
12496정성태1/19/20218923.NET Framework: 1010. .NET Core 콘솔 프로젝트에서 Kestrel 호스팅 방법 [1]
12495정성태1/19/202111048웹: 40. IIS의 HTTP/2 지원 여부 - h2, h2c [1]
12494정성태1/19/202110206개발 환경 구성: 522. WSL2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 [2]
12493정성태1/18/20218602.NET Framework: 1009. .NET 5에서의 네트워크 라이브러리 개선 (1) - HTTP 관련 [1]파일 다운로드1
12492정성태1/17/20217992오류 유형: 695. ASP.NET 0x80131620 Failed to bind to address
12491정성태1/16/20219577.NET Framework: 1008. 배열을 반환하는 C# COM 개체의 메서드를 C++에서 사용 시 메모리 누수 현상 [1]파일 다운로드1
12490정성태1/15/20219159.NET Framework: 1007. C# - foreach에서 열거 변수의 타입을 var로 쓰면 object로 추론하는 문제 [1]파일 다운로드1
12489정성태1/13/202110140.NET Framework: 1006. C# - DB에 저장한 텍스트의 (이모티콘을 비롯해) 유니코드 문자가 '?'로 보인다면? [1]
12488정성태1/13/202110368.NET Framework: 1005. C# - string 타입은 shallow copy일까요? deep copy일까요? [2]파일 다운로드1
12487정성태1/13/20218896.NET Framework: 1004. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법파일 다운로드1
12486정성태1/12/20219817.NET Framework: 1003. x64 환경에서 참조형의 기본 메모리 소비는 얼마나 될까요? [1]
12485정성태1/11/202110532Graphics: 38. C# - OpenCvSharp.VideoWriter에 BMP 파일을 1초씩 출력하는 예제파일 다운로드1
12484정성태1/9/202111182.NET Framework: 1002. C# - ReadOnlySequence<T> 소개파일 다운로드1
12483정성태1/8/20218397개발 환경 구성: 521. dotPeek - 훌륭한 역어셈블 소스 코드 생성 도구
12482정성태1/8/20219807.NET Framework: 1001. C# - 제네릭 타입/메서드에서 사용 시 경우에 따라 CS8377 컴파일 에러
12481정성태1/7/20219545.NET Framework: 1000. C# - CS8344 컴파일 에러: ref struct 타입의 사용 제한 메서드파일 다운로드1
12480정성태1/6/202112126.NET Framework: 999. C# - ArrayPool<T>와 MemoryPool<T> 소개파일 다운로드1
12479정성태1/6/20219492.NET Framework: 998. C# - OWIN 예제 프로젝트 만들기
12478정성태1/5/202111115.NET Framework: 997. C# - ArrayPool<T> 소개파일 다운로드1
12477정성태1/5/202113516기타: 79. github 코드 검색 방법 [1]
12476정성태1/5/202110171.NET Framework: 996. C# - 닷넷 코어에서 다른 스레드의 callstack을 구하는 방법파일 다운로드1
12475정성태1/5/202112756.NET Framework: 995. C# - Span<T>와 Memory<T> [1]파일 다운로드1
12474정성태1/4/202110307.NET Framework: 994. C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신 [1]파일 다운로드1
12473정성태1/4/20219103.NET Framework: 993. .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무 [1]파일 다운로드1
12472정성태1/3/20219392디버깅 기술: 178. windbg - 디버그 시작 시 스크립트 실행
12471정성태1/1/20219862.NET Framework: 992. C# - .NET Core 3.0 이상부터 제공하는 runtimeOptions의 rollForward 옵션 [1]
... 31  32  33  34  35  36  37  38  39  40  41  42  43  44  [45]  ...