
이번에는 spring boot에서 설정을 할 차례이다.
설정을 하기 전에 OAuth가 무엇인지를 알고 넘어가야 하는데
간단하게 설명하면
SNS 플랫폼을 통해 사용자는 로그인을 하고, 해당 플랫폼에서 우리 서비스로 접근 권한을 주는 것이다.
이러한 OAuth에서 보안적인 문제점들을 보완해서 만든 것이 OAuth2이다.
현재의 SNS 연동 로그인들은 Oauth2를 사용하고 있다.
이 부분은 spring security와도 연동이 되는 부분이니 개념적인 부분과 작동 방식을 알고 있으면 도움이 된다.
먼저 사용전에 dependency를 설정해주어야 한다.
gradle을 기준으로 oauth2 를 아래와 같이 추가해주면 된다.
// oauth2
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
// security
implementation 'org.springframework.boot:spring-boot-starter-security'
// jwt
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'
전에 React에서는 백엔드로 네이버 로그인을 요청 보낼 URI만을 입력했기 때문에, 해당 URL로 요청이 왔을 때, 어디로 로그인을 보내고, 어떤 것들을 어떻게 받아올지를 설정해주어야 하는데 그 부분을 yml에 설정해주면 된다.
spring:
security:
oauth2:
client:
registration:
naver:
client-id: ${NAVER_CLIENT_ID}
client-secret: ${NAVER_CLIENT_SECRET}
authorization-grant-type: authorization_code
scope:
- name
- email
- profile_image
- nickname
client-name: Naver
provider:
naver:
authorization-uri: https://nid.naver.com/oauth2.0/authorize
token-uri: https://nid.naver.com/oauth2.0/token
user-info-uri: https://openapi.naver.com/v1/nid/me
user-name-attribute: response
registration : 발급받았던 네이버 관련 정보들을 id와 secret에 입력해주면 된다.
provider : 요청들을 보낼 URL들을 정의해놓는 부분이다. GOOGLE과 같은 해외 기업들은 spring 자체에 등록이 되어 있기 때문에 이 부분을 작성하지 않는다.
(+ 2023.11.07 변경 사항 kakao 및 google 추가)
# 공통 설정
spring:
security:
oauth2:
client:
registration:
google:
client-id: ${GOOGLE_CLIENT_ID}
client-secret: ${GOOGLE_CLIENT_SECRET}
scope:
- email
- profile
naver:
client-name: Naver
client-id: ${NAVER_CLIENT_ID}
client-secret: ${NAVER_CLIENT_SECRET}
authorization-grant-type: authorization_code
scope:
- email
- nickname
kakao:
client-name: Kakao
client-id: ${KAKAO_CLIENT_ID}
client-secret: ${KAKAO_CLIENT_SECRET}
client-authentication-method: client_secret_post
authorization-grant-type: authorization_code
scope:
- profile_nickname
- account_email
# 구글은 provider를 지정하지 않아도 됨. 알아서 자동으로 등록 됨
provider:
naver:
authorization-uri: https://nid.naver.com/oauth2.0/authorize
token-uri: https://nid.naver.com/oauth2.0/token
user-info-uri: https://openapi.naver.com/v1/nid/me
user-name-attribute: response
kakao:
authorization-uri: https://kauth.kakao.com/oauth/authorize
token-uri: https://kauth.kakao.com/oauth/token
user-info-uri: https://kapi.kakao.com/v2/user/me
user-name-attribute: id
# 로걸 및 dev환경을 나누어서 registration을 따로 관리
spring:
config:
activate:
on-profile: "oauth2-local"
security:
oauth2:
client:
registration: # 각 Oauth2 콜백 URI
naver:
redirect-uri: http://localhost:8081/api/oauth2/callback/naver
google:
redirect-uri: http://localhost:8081/api/oauth2/callback/google
kakao:
redirect-uri: http://localhost:8081/api/oauth2/callback/kakao
authorized-redirect-uris: http://localhost:3000/user/redirect # 추가로 설정한 oauth2 로그인 후 토큰 redirect할 front URI