개발/front-end

SPA기반 Front 구글 로그인 api 연동

희운1205 2023. 2. 24. 09:59
반응형

Front(SPA)  구글 로그인 API 연동 하기(Angular)

구글 로그인 API 연동

: 기본 gapi auth2 방식의 로그인은 2023년 3월 31일 이후 지원이 중단되며, 새로운 클라이언트 아이디를 생성해서 작업하려면 반드시 아래의 gsi 로그인 방식을 이용해야 합니다. 

* api 문서 : https://developers.google.com/identity/gsi/web/guides/overview?hl=ko

import { Component, NgZone, OnInit, OnDestroy } from '@angular/core';

declare const google: any;
declare const $: any;


export const google_key = {
	apiKey: 'AbcdEfghi2Lm4VGd35-AkL808080808080D0185',
	clientId: 'gjgjgjgjgj2343243240934455666667777gfsdgfsdgs.apps.googleusercontent.com'
};

@Component({
    selector: 'app-google-login',
    template: ` <a href="javascript:;" (click)="Login()">구글 로그인</a>
    <div id="googlelogin" style="visibility:hidden; width:0; height:0;"></div>`
})

export class GoogleGsiLoginComponent implements OnInit, OnDestroy {
    constructor(
        public ngZone: NgZone,
    ) {
    }

    public ngOnInit(): void {
        // 구글 sdk 호출
        try {
            setTimeout(() => {
                this.load();
            }, 10);
        } catch (err) {
            console.log(err);
        }
    }

    public load(): void {
        const gc = document.createElement('script');
        gc.id = 'google';
        gc.src = `//accounts.google.com/gsi/client`;
        gc.async = true;
        gc.defer = true;
        document.head.appendChild(gc);

        const self = this;
        const GoogleLogin = () => {
            if (google) {
                const handleCredentialResponse = (res: any) => {
                    const token = res.credential;
                    const data = token.split('.')[1];
                    const result = JSON.parse(window.atob(data).toString()); // base64 디코더( window.btoa 는 반대로 base64 인코더)
                    self.ngZone.run(() => {
                        console.log(result);
                        // 원하는 프로세서 처리
                    });
                };

                google.accounts.id.initialize({
                    client_id: google_key.clientId,
                    callback: handleCredentialResponse,
                    auto_select: false
                });
                
                // 이전 버전과 다르게 아래의 버튼을 반드시 생성해야함
                google.accounts.id.renderButton(
                    document.getElementById('googlelogin'),
                    {
                        type: 'icon',
                        text: 'signup_with',
                        width: '10',
                        shape: 'circle'
                    }
                );
            }
        };
        gc.addEventListener('load', GoogleLogin);
    }

    public Login(): void {
        // 커스텀하게 만든 버튼을 만들어도 아래와 같이 구글에서 제공하는 
        // 버튼을 반드시 클릭하도록 해야함
        const buttonElement= '[aria-labelledby="button-label"]';
        if (buttonElement && document.querySelector(buttonElement)) {
            (document.querySelector(buttonElement) as HTMLElement).click();
        }
    }
}

 

반응형