Microsoft MVP성태의 닷넷 이야기
닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제) [링크 복사], [링크+제목 복사],
조회: 9206
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - Google 로그인 연동 (ASP.NET 예제)

이에 대해서는 구글 측에서 자세한 문서를 제공하고 있습니다.

API Client Libraries - .NET
; https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth?hl=ko

다른 OAuth 연동과 마찬가지로 사이트를 위한 인증 키를 발급받아야 하는데요, 아래의 Google Cloud 콘솔 페이지에서,

Google API 콘솔
; https://console.cloud.google.com/?hl=ko

"API 및 서비스" / "사용자 인증 정보"와 "OAuth 동의 화면"을 거쳐 진행할 수 있습니다. 관련해서 다음의 글에서 자세하게 소개하고 있으니 따라 하시면 됩니다.

구글로그인 쉽게 구현하기 1편 - Google Developers 설정
; https://notspoon.tistory.com/45

이후 코드는 아래의 글에서 예제까지 제공하고 있는데요,

OAuth 2.0
; https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth?hl=ko

2개의 예제 코드는 각각 Console Application과 ASP.NET Core를 기준으로 작성돼 있습니다. 만약 그 2가지 유형이라면 해당 예제를 적용해 쉽게 구현할 수 있는데요, 만약 기존의 ASP.NET (.NET Framework) 환경이라면 조금 손을 봐야 합니다.

이대로 끝내면 아쉬우니 ^^ ASP.NET용으로 직접 작성해 볼까요?

우선, ASP.NET (.NET Framework) WebForms 프로젝트를 만들어 nuget 참조를 추가하고,

Install-Package Google.Apis.Auth 

임의의 페이지에 다음과 같이 (독립 실행형 응용 프로그램을 위한 용도의) GoogleWebAuthorizationBroker.AuthorizeAsync 호출을 하면,

/* client_secrets.json 파일의 내용
{
    "web": {
        "client_id": "...[여러분이 받은 ID]...",
        "client_secret": "...[여러분이 받은 Client Secret]...",
    }
}
*/

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string path = Server.MapPath("~");
            string jsonPath = Path.Combine(path, "bin", "client_secrets.json");
            string[] scopes = new string[] { "https://www.googleapis.com/auth/userinfo.email" };

            using (var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
            {
                var secrets = GoogleClientSecrets.FromStream(stream).Secrets;

                // async 메서드 내에서는 await 호출을 하겠지만, 이 예제에서는 Result 호출로 동기 처리
                var results = GoogleWebAuthorizationBroker.AuthorizeAsync(
                                secrets, scopes, "user", CancellationToken.None, null).Result;
            }
        }
    }
}

이런 오류 화면으로 redirect 됩니다.

Access blocked: This app's request is invalid

testuser@gmail.com

You can't sign in because this app sent an invalid request. You can try again later, or contact the developer about this issue. Learn more about this error
If you are a developer of this app, see error details.
Error 400: redirect_uri_mismatch

위의 메시지 중 "error details" 링크를 누르면 좀 더 자세한 내용이 나오지만,

Error 400: redirect_uri_mismatch

You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.

If you're the app developer, register the redirect URI in the Google Cloud Console.
Request details: redirect_uri=http://localhost:58434/authorize/
Related developer documentation

딱히 도움이 되지는 않습니다. redirect_uri_mismatch 오류 상황은 사용자가 (Google Cloud 콘솔 페이지에서) 설정한 redirect 링크와 맞지 않아서 발생할 수 있습니다. 하지만, 그 링크를 설정했는데도 불구하고 (ASP.NET의 경우라면) 저 오류는 여전히 해결이 안 될 텐데요, 왜냐하면 GoogleWebAuthorizationBroker.AuthorizeAsync API 자체가 인증을 위한 요청 URL에 redirect_uri 파트를 json 파일의 내용으로부터 가져오지 않기 때문입니다. (위의 오류 메시지에 "http://localhost:58434/authorize/"로 설정했다고 나옵니다.)

실제로 AuthorizeAsync의 첫 번째 인자에 들어가는 secrets는 ClientSecrets 타입으로,

namespace Google.Apis.Auth.OAuth2
{
    public sealed class ClientSecrets
    {
        [Newtonsoft.Json.JsonProperty("client_id")]
        public string ClientId { get; set; }

        [Newtonsoft.Json.JsonProperty("client_secret")]
        public string ClientSecret { get; set; }
    }
}

redirect uri 정보가 없는 client_id, client_secret만 조합해서 인증 요청을 시도할 뿐입니다.

따라서, .NET Framework 환경의 ASP.NET 환경에서는 인증 요청에 대한 URL을 직접 작성해야 하는데요, 다행히 이미 Google.Apis.Auth
패키지에는 GoogleAuthorizationCodeFlow 타입이 이런 과정을 자동화합니다. 아래의 코드를 보면, redirect URI 정보까지 모두 포함시켜 GoogleAuthorizationCodeFlow.CreateAuthorizationCodeRequest 메서드를 호출해 인증 요청을 위한 URL을 구하는 것을 보여줍니다.

protected void Page_Load(object sender, EventArgs e)
{
    string path = Server.MapPath("~");
    string jsonPath = Path.Combine(path, "bin", "client_secrets.json");
    string[] scopes = new string[] { "https://www.googleapis.com/auth/userinfo.email" };

    using (var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
    {
        var clientSecrets = GoogleClientSecrets.FromStream(stream).Secrets;
        var initializer = new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = clientSecrets,
            Scopes = scopes
        };
        var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
        var request = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(
            "http://localhost:53745/loginProcess.aspx"); // redirect uri 설정
        Uri uri = request.Build();

        string authRequestUrl = uri.ToString();
        Response.Redirect(authRequestUrl);
    }
}

authRequestUrl에 들어가는 값은 대충 이런 구조입니다.

https://accounts.google.com/o/oauth2/v2/auth?
    access_type=offline&
    response_type=code&
    client_id=...[oauth client id]...&
    redirect_uri=http%3A%2F%2F127.0.0.1%3A53745%2FloginProcess.aspx&
    scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile

원하는 값들이 잘 들어가 있습니다. 마지막의 Response.Redirect는 그렇게 작성한 URL로 사용자 웹 브라우저 화면을 전환시켜 Google 인증 페이지로 넘어갈 수 있게 합니다.

이후, 사용자가 구글 인증을 마치면 CreateAuthorizationCodeRequest 메서드로 넘겨준 redirect URL, 위의 경우 "http://127.0.0.1:53745/loginProcess.aspx"로 다시 rediect가 발생합니다.

그럼 loginProcess.aspx에는 대충 다음과 같은 식으로 요청이 들어오고, 이 정보로부터 Token을 가져오는 작업을 진행하면 되는데요,

/loginProcess?
    code=...[access token을 구하기 위한 값]...&
    scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&
    authuser=0&
    prompt=consent

여기서 쓸모 있는 것은 code 하나입니다. 이 값을 이용해 GoogleAuthorizationCodeFlow.ExchangeCodeForTokenAsync API를 다시 호출하면 TokenResponse를 구할 수 있습니다.

public partial class loginProcess : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string code = Request.QueryString["code"];
        string path = Server.MapPath("~");
        string jsonPath = Path.Combine(path, "bin", "client_secrets.json");

        using (var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
        {
            var clientSecrets = GoogleClientSecrets.FromStream(stream).Secrets;
            var initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
            };

            var flow = new GoogleAuthorizationCodeFlow(initializer);
            
            string rediect_uri = "http://localhost:53745/loginProcess.aspx";
            var tokenResponse = flow.ExchangeCodeForTokenAsync(null, code,
                rediect_uri, CancellationToken.None).Result;

            string accessToken = tokenResponse.AccessToken;
        }
    }
}

TokenResponse에는 access_token, token_type,... 등의 값이 있지만 이전에 CreateAuthorizationCodeRequest를 요청했을 시 지정했던 "Scope"에 해당하는 정보까지 포함한 IdToken 값을 JWT(Json Web Token) 인코딩된 유형으로 가지고 있습니다.

따라서, IdToken을 JWT 디코딩하면 되는데요, 이런 목적으로 GoogleJsonWebSignature.ValidateAsync 메서드를 호출할 수 있습니다.

var idToken = GoogleJsonWebSignature.ValidateAsync(tokenResponse.IdToken).Result;

string email = idToken.Email;
string name = idToken.Name;
string first_name = idToken.FamilyName;
string last_name = idToken.GivenName;
string id = idToken.Subject;

제가 운영하는 sysnet 개인 블로그처럼 단순히 로그인 처리만 하는 경우라면 accessToken을 보관할 필요는 없습니다. 필요한 것은, 사용자를 구분하기 위한 idToken.Subject 값 정도인데요, 따라서 이것을 FormsAuthentication.SetAuthCookie로 지정해 로그인했다는 기록만을 남기면 됩니다.

FormsAuthentication.SetAuthCookie(id, true);




부가적으로, 인증을 위한 redirect 중에 유지할 필요가 있는 정보가 있다면 (Facebook 인증에서도 동일했던) state를 설정할 수 있습니다.

RFC 6749 - The OAuth 2.0 Authorization Framework
 - 4.1.1.  Authorization Request
; https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1

예를 들어, 위의 예제에서 loginProcess.aspx 내부의 코드를 거친 후, (로그인을 시도하기 전에) 사용자가 방문했던 그 페이지를 보여주는 것이 더 자연스러울 것입니다.

따라서 이런 경우에는 그 페이지 주소, 또는 그 페이지로 갈 수 있는 정보를 state 쿼리 인자로 넘겨주면 되는데요,

var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
var request = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(
    "http://localhost:53745/loginProcess.aspx" // redirect_uri에는 부가적인 매개 변수를 넘길 수 없으므로,
    );
Uri uri = request.Build();

string authRequestUrl = uri.ToString();
Response.Redirect(authRequestUrl + "&state=test1 test2"); // 별도의 state 매개 변수로 넘겨줍니다.

또는, Google.Apis.Auth를 사용하는 위의 예제에서는 GoogleAuthorizationCodeFlow.Initializer에서 UserDefinedQueryParams를 통해 전달하는 것도 가능합니다.

var clientSecrets = GoogleClientSecrets.FromStream(stream).Secrets;
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = clientSecrets,
    Scopes = scopes,
    UserDefinedQueryParams = new Dictionary<string, string>
    {
        ["state"] = "test1 test2",
    }
};

var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
var request = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(
    "http://localhost:53745/loginProcess.aspx"
    );
Uri uri = request.Build(); // 이 시점에 "state=test1 test2"가 함께 URL에 포함됨

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




그런데 이상하군요, 위의 예제를 다른 컴퓨터에서, 동일하게 Windows 11 + Edge + Visual Studio로 실행했는데, 한 컴퓨터에서만 구글 로그인 이후 다음과 같은 오류가 발생합니다.

Couldn't sign you in

This browser or app may not be secure. Learn more
Try using a different browser. If you're already using a supported browser, you can try again to sign in.

반면 Chrome 브라우저를 띄워 "localhost:53745"로 접속해 테스트를 했더니 정상적으로 로그인이 됩니다. 이유는, "Enable JavaScript debugging for ASP.NET (Chrome, Edge and IE)" 설정이 켜져 있었던 탓에,

Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
; https://www.sysnet.pe.kr/2/0/13620

제약이 많은 edge 브라우저가 실행돼 "This browser or app may not be secure"라는 오류가 발생한 것입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/11/2024]

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

비밀번호

댓글 작성자
 




... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13516정성태1/7/20249684닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20249631닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20249526개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20249623닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20249874개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20249618닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20249363닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/202410549오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/202410038오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/202411123닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/202310269닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/202312103닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/202311215닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/202310391Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/202310931닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/202310270개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/202310786디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/202312455닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/202310626오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/202310558Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/202310791Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/202310896Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/202310990닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/202310378개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20239380Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/202310105개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...