본문 바로가기

Angular.js

구글 OAuth2로그인 간단한 절차

구글 인가 서버입니다.  주소창 보이시나요 우리가 적어 넣었던 redirect_url  , response_type,  clent_id 등 과 함께 구글 인가서버로 접속 되는것입니다.  여기에 우리가 인증(로그인) 하게되면 클라이언트가 요청한 정보 허용 동의가 나오게 됩니다.

                                                                                                                                                       

HTTPS 등의 문제로 이런 창이 뜨네요 . 안전하지 않음 클릭~!  안전하지 않음 클릭이 안되는 분은 ssl 설정을 해주어야합니다. 다음 게시글에서 확인하시고 설정하신후 다시해보시면 보이실겁니다.

                                                                                                                                                       

클라이언트가 구글에 요청하게될 정보등의 권한을 허락해줍니다.

                                                                                                                                                        

 

다음과 같이 access_token 과함께 내가있던곳으로 되돌아 오게 됩니다. #뒤에 있는것을 hash라고 하는데, window.location.hash.substr(1)으로 access_toen을 받아와서 session Stroage등에 저장해서 사용하시면 됩니다.

더보기

전체 코드 

 

const CLIENT_ID =

  '~~~~~~~~~~~~~~~~~~~~~~~~~~~9s.apps.googleusercontent.com';

const AUTHORIZE_URI = 'https://accounts.google.com/o/oauth2/v2/auth';

 

@Component({

  selector: 'app-nav',

  templateUrl: './nav.component.html',

  styleUrls: ['./nav.component.css'],

})

 

 

export class NavComponent implements OnInit {

  loggedinboolean = false;

 

  queryStr;

  loginUrl;

 

  initQueryStr() {

    this.queryStr = stringify({

      response_type: 'token',

      client_id: CLIENT_ID,

      redirect_uri: window.location.href,

      scope: 'https://www.googleapis.com/auth/contacts.readonly',

    });

    this.loginUrl = AUTHORIZE_URI + '?' + this.queryStr;

  }

 

  initLoggedin() {

    if (window.sessionStorage.getItem('access_token')) {

      this.loggedin = true;

    } else {

      this.loggedin = false;

    }

  }

  constructor(

    private locationLocation,

    private routerRouter,

    private authServiceAuthService

  ) {}

  goForward() {

    this.location.forward();

  }

  postWrite() {

    this.router.navigateByUrl('/postWrite');

  }

 

  logOut() {

    window.sessionStorage.removeItem('access_token');

    this.loggedin = false;

    window.location.hash = '';

    window.location.reload;

 

    this.initQueryStr();

 

  }

 

  ngOnInit(): void {

    this.initQueryStr();

    this.initLoggedin();

 

    const { access_token } = parse(window.location.hash.substr(1));

 

    if (window.location.hash.substr(1).length > 5) {

      window.sessionStorage.setItem(

        'access_token',

        window.location.hash.substr(1)

      );

      this.loggedin = true;

      window.location.hash = '';

    }

  }

}