Spring Security OAuth2 설정 방법 - 단계별 가이드
Spring Boot & Spring Security 기반 프로젝트에서 OAuth2 인증을 쉽게 적용할 수 있는 방법에 대해 알아보겠습니다.
해당 방법을 통해 구글, 깃허브, 네이버 같은 소셜 로그인 연동도 가능합니다!
1. OAuth2란 무엇일까?
OAuth2는 인증(Authentication)과 인가(Authorization)를 처리하기 위한 표준 프로토콜이에요.
쉽게 말해, 사용자가 직접 아이디/비밀번호를 입력하지 않고도 구글, 깃허브, 네이버 같은 서비스 계정을 통해 로그인할 수 있게 해줍니다. 요즘 대부분의 웹서비스에서 "구글로 로그인", "카카오로 로그인" 같은 버튼을 보셨을 텐데, 그게 바로 OAuth2 인증이에요.
2. 프로젝트 환경 준비하기
Spring Security OAuth2를 적용하려면 먼저 프로젝트에 필요한 의존성을 추가해야 합니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
만약 Gradle을 사용한다면 implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
를 추가하면 됩니다.
3. application.yml 설정하기
OAuth2는 클라이언트 ID, 클라이언트 시크릿, 리다이렉트 URL 같은 값이 필요합니다.
예를 들어 구글 로그인을 연동한다고 가정하면 다음과 같이 application.yml
을 설정합니다.
spring:
security:
oauth2:
client:
registration:
google:
client-id: 구글에서_발급받은_ID
client-secret: 구글에서_발급받은_SECRET
scope:
- email
- profile
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
여기서 중요한 건 Redirect URI를 구글 개발자 콘솔에 등록해야 한다는 점이에요. 기본적으로는 http://localhost:8080/login/oauth2/code/google
형태로 들어옵니다.
4. Security Config 클래스 작성하기
이제 SecurityConfig
를 만들어서 OAuth2 로그인을 활성화해봅시다.
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/css/**", "/js/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/login")
.defaultSuccessUrl("/", true)
);
return http.build();
}
}
위 설정은 루트("/")와 정적 리소스에 대해서는 누구나 접근할 수 있고, 그 외 모든 요청은 인증된 사용자만 접근할 수 있도록 설정합니다.
5. 사용자 정보 가져오기
로그인 성공 후 구글에서 제공하는 사용자 정보를 가져올 수 있습니다.
OAuth2User
객체를 주입받아 사용자 이메일, 이름 등을 조회할 수 있어요.
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/user")
public String user(@AuthenticationPrincipal OAuth2User oAuth2User) {
return "Hello, " + oAuth2User.getAttribute("name");
}
}
이제 로그인한 사용자의 이름이 화면에 출력될 거예요. 여기서 이메일이나 프로필 사진 같은 값도 불러올 수 있습니다.
6. 확장하기 - 다른 Provider 연동
구글뿐만 아니라 깃허브, 네이버, 카카오 같은 서비스도 비슷한 방식으로 연동할 수 있습니다.
application.yml
에 provider 정보를 추가하고 client-id, secret을 넣으면 돼요.
예를 들어 깃허브 로그인을 연동한다면 provider는 https://github.com/login/oauth/authorize
, token-uri는 https://github.com/login/oauth/access_token
으로 설정합니다.
7. 마무리하며
오늘은 Spring Security를 활용해 OAuth2 인증을 설정하는 방법을 알아봤습니다.
정리하면 다음 순서로 진행되었죠:
많은 도움이 되었길 바랍니다.
- 의존성 추가
- application.yml 설정
- SecurityConfig 작성
- 사용자 정보 확인
- 여러 Provider 연동