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)
12570정성태3/19/202112671개발 환경 구성: 555. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법
12569정성태3/18/202111544개발 환경 구성: 554. WSL 인스턴스 export/import 방법 및 단축 아이콘 설정 방법
12568정성태3/18/20217253오류 유형: 705. C# 빌드 - Couldn't process file ... due to its being in the Internet or Restricted zone or having the mark of the web on the file.
12567정성태3/17/20218581개발 환경 구성: 553. Docker Desktop for Windows를 위한 k8s 대시보드 활성화 [1]
12566정성태3/17/20218919개발 환경 구성: 552. Kubernetes - kube-apiserver와 REST API 통신하는 방법 (Docker Desktop for Windows 환경)
12565정성태3/17/20216433오류 유형: 704. curl.exe 실행 시 dll not found 오류
12564정성태3/16/20216932VS.NET IDE: 160. 새 프로젝트 창에 C++/CLI 프로젝트 템플릿이 없는 경우
12563정성태3/16/20218882개발 환경 구성: 551. C# - JIRA REST API 사용 정리 (3) jira-oauth-cli 도구를 이용한 키 관리
12562정성태3/15/20219970개발 환경 구성: 550. C# - JIRA REST API 사용 정리 (2) JIRA OAuth 토큰으로 API 사용하는 방법파일 다운로드1
12561정성태3/12/20218597VS.NET IDE: 159. Visual Studio에서 개행(\n, \r) 등의 제어 문자를 치환하는 방법 - 정규 표현식 사용
12560정성태3/11/20219947개발 환경 구성: 549. ssh-keygen으로 생성한 개인키/공개키 파일을 각각 PKCS8/PEM 형식으로 변환하는 방법
12559정성태3/11/20219333.NET Framework: 1028. 닷넷 5 환경의 Web API에 OpenAPI 적용을 위한 NSwag 또는 Swashbuckle 패키지 사용 [2]파일 다운로드1
12558정성태3/10/20218856Windows: 192. Power Automate Desktop (Preview) 소개 - Bitvise SSH Client 제어 [1]
12557정성태3/10/20217489Windows: 191. 탐색기의 보안 탭에 있는 "Object name" 경로에 LEFT-TO-RIGHT EMBEDDING 제어 문자가 포함되는 문제
12556정성태3/9/20216783오류 유형: 703. PowerShell ISE의 Debug / Toggle Breakpoint 메뉴가 비활성 상태인 경우
12555정성태3/8/20218779Windows: 190. C# - 레지스트리에 등록된 DigitalProductId로부터 라이선스 키(Product Key)를 알아내는 방법파일 다운로드2
12554정성태3/8/20218615.NET Framework: 1027. 닷넷 응용 프로그램을 위한 PDB 옵션 - full, pdbonly, portable, embedded
12553정성태3/5/20219090개발 환경 구성: 548. 기존 .NET Framework 프로젝트를 .NET Core/5+ 용으로 변환해 주는 upgrade-assistant, try-convert 도구 소개 [4]
12552정성태3/5/20218348개발 환경 구성: 547. github workflow/actions에서 Visual Studio Marketplace 패키지 등록하는 방법
12551정성태3/5/20217248오류 유형: 702. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly. (2)
12550정성태3/5/20216970오류 유형: 701. Live Share 1.0.3713.0 버전을 1.0.3884.0으로 업데이트 이후 ContactServiceModelPackage 오류 발생하는 문제
12549정성태3/4/20217416오류 유형: 700. VsixPublisher를 이용한 등록 시 다양한 오류 유형 해결책
12548정성태3/4/20218170개발 환경 구성: 546. github workflow/actions에서 nuget 패키지 등록하는 방법
12547정성태3/3/20218640오류 유형: 699. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly.
12546정성태3/3/20218304개발 환경 구성: 545. github workflow/actions에서 빌드시 snk 파일 다루는 방법 - Encrypted secrets
12545정성태3/2/202111033.NET Framework: 1026. 닷넷 5에 추가된 POH (Pinned Object Heap) [10]
... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...