배운 것들
- github Oauth
- sass
더 알아볼 것
- 다른 서비스의 Oauth 해보기
github Oauth를 직접 사용해보았다. 지금까지 배웠던 것들을 사용하여 api문서를 읽으며 해결했는데 정말 간편하고 보안면에서도 정말 좋을 것 같다는 생각을 했다. 프로젝트에서 꼭 다른 서비스의 Oauth도 사용해보아야겠다는 생각을 했다. 먼저 github에서 Oauth를 등록하면 redirect url로 authorization code를 보내주는데 이를 이용하여 서버에 token을 요청한다.
async getAccessToken(authorizationCode) {
let resp = await axios.post('http://localhost:8080/callback', { authorizationCode: authorizationCode })
console.log(resp.data)
this.setState({
isLogin: true,
accessToken: resp.data.accessToken
})
}
componentDidMount() {
const url = new URL(window.location.href)
const authorizationCode = url.searchParams.get('code')
if (authorizationCode) {
this.getAccessToken(authorizationCode)
}
}
이때 서버는 코드를 받아 resource server 인 github에 token 요청을 보낸다.
axios({
method: 'post',
url: `https://github.com/login/oauth/access_token`,
headers: {
accept: 'application/json',
},
data: {
client_id: clientID,
client_secret: clientSecret,
code: req.body.authorizationCode
}
}).then((response) => {
accessToken = response.data.access_token;
console.log(response.data)
res.status(200).json({ accessToken: accessToken })
}).catch(e => {
res.status(404)
})
이렇게 받아온 토큰을 state에 저장해 두었다가 필요한 요청 시 토큰을 같이 보내면 원하는 정보를 받아 올 수 있다.
async getGitHubUserInfo() {
const { accessToken } = this.props
let response = await axios.get('https://api.github.com/user', {
headers: {
authorization: `token ${accessToken}`,
}
})
const { name, login, html_url, public_repos } = response.data
this.setState({
name,
login,
html_url,
public_repos
})
}
오늘 Oauth까지 인증 스프린트가 끝이 났다. 처음 cookie와 session을 하면서 많이 헤매고 시간도 정말 많이 걸렸지만 이해를 하고 나니 뒤의 스프린트들을 진행할 때에 큰 도움이 되었다. 인증에 대하여 프로젝트에서 적용하는 시간을 가지며 익숙해져야겠다. 어느덧 벌써 스프린트가 다 끝나간다. 돌아보니 시간이 정말 빨리 지나간 것 같다. 하지만 배운 것도 많은 것 같아 뿌듯한 한 해가 될 것 같다.
'TIL' 카테고리의 다른 글
20210318 first project #2 (0) | 2021.03.19 |
---|---|
20210317 first project #1 (2) | 2021.03.18 |
20210305 TIL (0) | 2021.03.07 |
20210304 TIL (0) | 2021.03.04 |
20210303 TIL (0) | 2021.03.03 |
댓글