React로 블로그 만들기 #4
- 로그인 구현(1) Google -
1. 소셜로그인 구현
- TodoApp을 통해 로컬로그인을 구현해봤으므로 소셜로그인으로 구현
- 회원가입 절차가 따로 없음 => 사용자가 번거롭게 새로 가입하지 않아도 됨 : OAuth 인증으로 Access Token 발급
- 처음 로그인한 경우에는 회원가입 처리, 그 후에는 로그인 처리
- 구글 로그인과 카카오 로그인 구현
1) Google
- API 발급 받기 : https://console.cloud.google.com/apis/
- 패키지 설치 : yarn add react-google-login (https://www.npmjs.com/package/react-google-login)
- src/Components/Login.js에 구글 로그인을 구현
- react-google-login에서 GoogleLogin 객체를 import함
- 백엔드에 정보를 저장하기 위해 state에 id, name, provider를 저장함
- id: 로그인하는 유저가 갖고 있는 고유번호
- name: 로그인 유저의 이름
- provider: 구글 로그인인지 카카오 로그인인지 확인 => 지금은 구글 로그인이므로 'google'로 저장
- GoogleLogin 객체는 clientId, buttonText, onSuccess, onFailure 등으로 구성
- clientId : 구글에서 발급받은 API KEY 값
- buttonText : 버튼에 보여질 텍스트
- onSuccess : 로그인 인증에 성공한 경우 실행할 함수 정의
- onFailure : 로그인 인증에 실패한 경우 실행할 함수 정의
import React, { Component } from 'react';
import { GoogleLogin } from 'react-google-login';
import styled from 'styled-components';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
id: '',
name: '',
provider: '',
}
}
// Google Login
responseGoogle = (res) => {
console.log(res)
}
// Login Fail
responseFail = (err) => {
console.error(err);
}
render() {
return (
<Container>
<GoogleLogin
clientId={process.env.REACT_APP_Google}
buttonText="Google"
onSuccess={this.responseGoogle}
onFailure={this.responseFail}
/>
</Container>
);
}
}
const Container = styled.div`
display: flex;
flex-flow: column wrap;
`
export default Login;

- 로그인/회원가입을 누르면 로그인 페이지로 이동하고 구글 로그인 버튼을 볼 수 있음

- 버튼을 누르면 구글 계정 로그인 창이 뜨고 구글 계정을 통해 로그인을 진행할 수 있음
- 로그인에 성공하면 Json을 반환해줌 => responseGoogle함수에서 state에 id, name을 저장
- 로그인에 실패한 경우에는 에러를 넘겨줌 => responseFail함수에서 error 출력
import React, { Component } from 'react';
import { GoogleLogin } from 'react-google-login';
import styled from 'styled-components';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
id: '',
name: '',
provider: '',
}
}
// Google Login
responseGoogle = (res) => {
this.setState({
id: res.googleId,
name: res.profileObj.name,
provider: 'google'
});
}
// Login Fail
responseFail = (err) => {
console.error(err);
}
render() {
return (
<Container>
<GoogleLogin
clientId={process.env.REACT_APP_Google}
buttonText="Google"
onSuccess={this.responseGoogle}
onFailure={this.responseFail}
/>
</Container>
);
}
}
const Container = styled.div`
display: flex;
flex-flow: column wrap;
`
export default Login;