✏️ 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 책을 보면서 스터디 한 내용을 정리하였습니다
https://www.yes24.com/product/goods/83849117
스프링 부트와 AWS로 혼자 구현하는 웹 서비스 - 예스24
가장 빠르고 쉽게 웹 서비스의 모든 과정을 경험한다. 경험이 실력이 되는 순간!이 책은 제목 그대로 스프링 부트와 AWS로 웹 서비스를 구현한다. JPA와 JUnit 테스트, 그레이들, 머스테치, 스프링
www.yes24.com
5장 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기
💜스프링 시큐리티와 스프링 시큐리티 Oauth2 클라이언트
💠스프링 시큐리티란?
- 막강한 인증과 인가 기능을 가진 프레임워크
- 스프링 기반의 애플리케이션에서는 보안을 위한 표준
- 스프링의 대부분 프로젝트들처럼 확장성을 고려한 프레임워크다 보니 다양한 요구사항을 손쉽게 추가하고 변경할 수 있다
많은 서비스에서 로그인 기능을 id/password 방식보다는 구글 페이스북 네이버 로그인과 같은 소셜 로그인 기능을 사용한다
- 로그인 시 보안
- 비밀번호 찾기
- 비밀번호 변경
- 회원정보 변경
- 회원가입 시 이메일 혹은 전화번호 인증
스프링 부트 2.0
- spring-security-oauth2-autoconfigure 라이브러리 사용
이 책에선 스프링 부트 2 방식인 Spring Security Oauth2 Client 라이브러리를 사용해서 진행
- 스프링 팀에서 기존 1.5에서 사용되던 spring-security-oauth 프로젝트는 유지 상태로 결정했으며 더는 신규 기능은 추가하지 않고 버그 수정 정도의 기능만 추가될 예정, 신규 기능은 새 ouath2 라이브러리에서만 지원하겠다고 선언
- 스프링 부트용 라이브러리 출시
- 기존에 사용되던 방식은 확장 포인트가 적절하게 오픈되어 있지 않아 직접 상속하거나 오버라이딩 해야 하고 신규 라이브러리의 경우 확장 포인트를 고려해서 설계된 상태
스프링 부트 1.5 방식에서는 url 주소 모두 명시 → 2.0 방식에서는 client 인증 정보만 입력하면 된다
1.5 버전에서 직접 입력했던 값들은 2.0 버전으로 오면서 모두 enum으로 대체 되었다
CommonOAuth2Provider라는 enum이 새롭게 추가되어 구글, 깃허브 등의 기본 설정값은 모두 여기서 제공된다
public enum CommonOAuth2Provider {
GOOGLE {
@Override
public ClientRegistration.BuildergetBuilder(String clientId, String clientSecret) {
return getBuilder(clientId, clientSecret, "https://accounts.google.com");
}
},
FACEBOOK {
@Override
public ClientRegistration.BuildergetBuilder(String clientId, String clientSecret) {
return getBuilder(clientId, clientSecret, "https://www.facebook.com");
}
},
GITHUB {
@Override
public ClientRegistration.BuildergetBuilder(String clientId, String clientSecret) {
return getBuilder(clientId, clientSecret, "https://github.com");
}
},
// Add more providers as needed
// This method is used by all providers to configure the OAuth2 ClientRegistration
privatestatic ClientRegistration.BuildergetBuilder(String clientId, String clientSecret, String providerUrl) {
return ClientRegistration.withRegistrationId(providerUrl)
.clientId(clientId)
.clientSecret(clientSecret)
.scope("user_info")
.authorizationUri(providerUrl + "/oauth/authorize")
.tokenUri(providerUrl + "/oauth/token")
.userInfoUri(providerUrl + "/oauth/userinfo")
.userNameAttributeName("name")
.clientName(providerUrl);
}
// Abstract method to be implemented by each provider
publicabstract ClientRegistration.BuildergetBuilder(String clientId, String clientSecret);
}
💜 구글 서비스 등록
먼저 구글 서비스에 신규 서비스 생성
발급된 인증 정보를 통해서 로그인 기능과 소셜 서비스 기능을 사용할 수 있으니 무조건 발급 받고 시작할 것
- 구글 클라우드 플랫폼 주소 이동 후 프로젝트 생성

2. api 및 서비스 카테고리에서 OAuthClientId 생성

OAuth 클라이언트를 만들기 전에는 먼저 OAuth 동의화면 탭에서 동의 화면을 구성해야한다!

승인된 리디렉션 아이디에 다음과 같이 적는다
http://localhost:8080/login/oauth2/code/google
승인된 리디렉션 url
- 서비스에서 파라미터로 인증 정보를 주었을 때 인증이 성공하면 구글에서 리다이렉트할 url
- 스프링부트 2 버전의 시큐리티에서는 기본적으로 {도메인}/login/oauth2/code/{소셜 서비스코드}로 리다이렉트 지원
- 사용자가 별도로 리다일렉트 url을 지원하는 컨트롤러를 만들 필요 x → 시큐리티에서 이미 구현
- 현재는 개발 단계이므로 위의 url 사용
- AWS 서버에 배포하게 되면 localhost외에 추가로 주소 추가해야함

여기서 발급받은 클라이언트 ID와 클라이언트 보안 비밀 코드를 프로젝트에서 설정
3. application-oauth 등록

- 많은 예제에서는 이 scope를 별도로 등록하지 않는다
- 기본값이 openid, profile,email이기 때문이다
- 강제로 profile, email를 등록한 이유는 openid라는 scope가 없으면 Open id Provider로 인식하기 때문
- 이렇게 되면 OpenId Provider인 서비스 (구글)와 그렇지 않은 서비스(네이버/카카오 등)로 나눠서 각각 OAuth2Service를 만들어야한다
- 하나의 OAuth2Service로 사용하기 위해 일부로 openid scope 를 빼고 등록한다
application.properties에 다음과 같이 코드를 추가한다
spring.profiles.include=oauth
4. gitignore 등록
구글 로그인을 위한 클라이언트 ID와 클라이언트 보안 비밀은 보안이 중요한 정보
외부에 노출될 경우 언제든 개인정보를 가져갈 수 있는 취약점이 될 수 있다
application-oauth.properites
💜구글 로그인 연동하기
사용자 정보를 담당할 도메인인 User 클래스를 생성
- 패키지는 domain 아래에 user 패키지를 생성

User
package com.jojoIdu.book.springboot.domain.user;
import com.jojoIdu.book.springboot.domain.posts.BaseTimeEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Getter
@NoArgsConstructor
@Entity
public class User extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String email;
@Column
private String picture;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role; // Role은 별도의 Enum으로 정의
@Builder
public User(String name, String email, String picture, Role role) {
this.name = name;
this.email = email;
this.picture = picture;
this.role = role;
}
public User update(String name, String picture) {
this.name = name;
this.picture = picture;
return this;
}
public String getRoleKey() {
return this.role.getKey();
} //사용자의 role 필드에 접근하여 **권한 키(ROLE_XXX)**를 반환한다.
}
정리
- User 클래스는 사용자 정보를 담는 JPA 엔티티
- Lombok 어노테이션을 통해 getter 메서드, 기본 생성자, 빌더 메서드를 자동 생성
- BaseTimeEntity 상속으로 생성 시간, 수정 시간 같은 공통 필드를 재사용
- update 메서드로 엔티티의 상태를 변경하고, getRoleKey 메서드로 Role 정보를 문자열 형태로 반환
@Enumerated(EnumTpe.STRING)
- JPA로 데이터베이스를 저장할 때 Enum 값을 어떤 형태로 저장할지 결정
- 기본적으로는 int로 된 숫자가 저장된다
- 숫자로 저장되면 데이터베이스로 확인할 때 그 값이 무슨 코드를 의미하는지 알 수 없어 문자열로 저장될 수 있도록 선언한다
3. 사용자의 권한을 관리할 Enum 클래스 Role을 생성한다
package com.jojoIdu.book.springboot.domain.user
import lombok.Getter
import lombok.RequiredArgsConstructor
@Getter
@RequiredArgsConstructor
enum class Role {
GUEST("ROLE_GUEST", "손님"),
USER("ROLE_USER", "일반 사용자");
private val key: String? = null
private val title: String? = null
}
- 스프링 시큐리티에서는 권한 코드에 항상 ROLE_이 앞에 있어야한다
2. User의 CRUD를 책임질 UserRepository도 생성
package com.jojoIdu.book.springboot.domain.user;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
findByEmail
- 소셜 로그인으로 반환되는 값 중 email을 통해 이미 생성된 사용자이지 처음 가입하는 사용자인지 판단하기 위한 메소드
💜스프링 시큐리티 설정
- 먼저 build.gradle에 스프링 시큐리티 관련 의존성 하나를 추가
implementation 'org.springframework.boot:spring-boot-starter-security'
spring-boot-starter-oauth2-client
- 소셜 로그인 등 클라이언트 입장에서 소셜 기능 구현 시 필요한 의존성
- spring-security-oauth2-client 와 spring -security-oauth2-jose를 기본으로 관리해준다
buildscript {
ext.kotlin_version = '1.9.22'
ext {
springBootVersion = '2.6.3'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'org.example'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2'
implementation 'org.projectlombok:lombok:1.18.30'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'junit:junit:4.13.2'
implementation 'org.springframework.boot:spring-boot-starter-mustache'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'org.springframework.boot:spring-boot-starter-security' //추가
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' //추가
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
kotlin {
jvmToolchain(11)
}
build.gradle 설정이 끝나으면 OAuth 라이브러리를 이용한 소셜 로그인 설정 코드를 작성
2. config.auth 패키지 생성

3. SecurityConfig 클래스를 생성
- @EnableWebSecurity
- csrf( ).disable( ).headers( ).frameOptions( ).disable( )
- authorizeRequests
- antMatchers
- anyRequest
- logout( ). logoutSuccessUrl(”/”)
- oauth2Login
- userInfoEndpoint
- userService
4. CustomOAuth2UserService 클래스 생성
클래스에서 구글 로그인 이후 가져온 사용자의 정보 (email,name,picture 등)들을 기반으로 가입 및 정보 수정, 세션 저장 등의 기능 제공
package com.jojoIdu.book.springboot.config.auth;
import com.jojoIdu.book.springboot.config.auth.dto.OAuthAttributes;
import com.jojoIdu.book.springboot.config.auth.dto.SessionUser;
import com.jojoIdu.book.springboot.domain.user.User;
import com.jojoIdu.book.springboot.domain.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Collections;
@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
private final UserRepository userRepository;
private final HttpSession httpSession;
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{
OAuth2UserService<OAuth2UserRequest, OAuth2User>
delegate = new DefaultOAuth2UserService();
OAuth2User oAuth2User = delegate.loadUser(userRequest);
String registrationId = userRequest.getClientRegistration().getRegistrationId();
String userNameAttributeName = userRequest.getClientRegistration()
.getProviderDetails().getUserInfoEndpoint()
.getUserNameAttributeName();
OAuthAttributes attributes = OAuthAttributes.of(registrationId,
userNameAttributeName, oAuth2User.getAttributes());
User user = saveOrUpdate(attributes);
httpSession.setAttribute("user", new SessionUser(user));
return new DefaultOAuth2User(Collections.singleton(
new SimpleGrantedAuthority(user.getRoleKey())),
attributes.getAttributes(),
attributes.getNameAttributeKey());
}
private User saveOrUpdate(OAuthAttributes attributes) {
User user = userRepository.findByEmail(attributes.getEmail())
.map(entity-> entity.update(attributes.getName(),
attributes.getPicture()))
.orElse(attributes.toEntity());
return userRepository.save(user);
}
}
- registrationId
- userNameAttributeName
- OAuthAttributes
- SessionUser
5. OAuthAttributes 클래스 생성

package com.jojoIdu.book.springboot.config.auth.dto;
import com.jojoIdu.book.springboot.domain.user.Role;
import lombok.Builder;
import lombok.Getter;
import com.jojoIdu.book.springboot.domain.user.User;
import java.util.Map;
import java.util.Objects;
@Getter
public class OAuthAttributes {
private Map<String, Object> attributes;
private String nameAttributeKey;
private String name;
private String email;
private String picture;
@Builder
public OAuthAttributes(Map<String, Object> attributes,
String nameAttributeKey, String name,
String email, String picture
){
this.attributes = attributes;
this.nameAttributeKey= nameAttributeKey;
this.name=name;
this.email = email;
this.picture = picture;
}
public static OAuthAttributes of(String registrationId, String userNameAttributeName,
Map<String, Object> attributes){
return ofGoogle(userNameAttributeName, attributes);
}
private static OAuthAttributes ofGoogle(String userNameAttributeName, Map<String, Object> attributes){
return OAuthAttributes.builder()
.name((String) attributes.get("name"))
.email((String) attributes.get("email"))
.picture((String) attributes.get("picture"))
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}
public User toEntity(){
return User.builder()
.name(name)
.email(email)
.picture(picture)
.role(Role.GUEST)
.build();
}
}
- of( )
- toEntity()
6. SessionUser 클래스 추가
package com.jojoIdu.book.springboot.config.auth.dto;
import com.jojoIdu.book.springboot.domain.user.User;
import lombok.Getter;
import java.io.Serializable;
@Getter
public class SessionUser implements Serializable {
private String name;
private String email;
private String picture;
public SessionUser(User user) {
this.name = user.getName();
this.email = user.getEmail();
this.picture = user.getPicture();
}
}
- SessionUser에는 인증된 사용자 정보만 필요로 한다
💡User 클래스를 그대로 사용하면 왜 에러가 발생할까?
Failed to convert from type [java.lang.Object] to type
[byte[]] for value 'com.jojoldu.book.springboot.domain.user.
User@4a43d6'
→ 세션에 저장하기 위한 User 클래스 세션에 저장하려고 하니, User 클래스에 직렬화를 구현하지 않았다는 의미의 에러
직렬화 대상에 자식들까지 포함되니 성능 이슈, 부수 효과가 발생할 확률이 높다
직렬화 기능을 가진 세션 Dto를 하나 추가로 만드는 것이 이후 운영 및 유지 보수 때 많음 도움이 된다
💜로그인 테스트
- index.mustache에 로그인 버튼과 로그인 성공 시 사용자 이름을 보여주는 코드
<!--로그인 기능 영역-->
<div class="row">
<div class="col-md-6">
<a href="/posts/save" role="button"
class="btn btn-primary">글 등록</a>
{{#userName}}
Logged in as: <span id ="user">{{userNmae}}</span>
<a href="/logout" class="btn btn-info active" role = "button">Logout</a>
{{/userName}}
{{^userName}}
<a href="/outh2/authorization/google" class="btn btn-success active" role ="button">Google Login</a>
{{/userName}}
</div>
</div>
2. index.mustache 에서 userNmae을 사용할 수 있게 IndexController에서 userNmae을 model에 저장하는 코드 추가
indexController
@RequiredArgsConstructor
@Controller
public class IndexController {
private final PostsService postsService;
private final HttpSession httpSession;
@GetMapping("/")
public String index(Model model) {
model.addAttribute("posts", postsService.findAllDesc());
SessionUser user = (SessionUser) httpSession.getAttribute("user");
if(user!= null){
model.addAttribute("userName",user.getName());
}
return "index";
}
(SessionUser) httpSession.getAttribute("user")
- 앞서 작성된 CustomOAuth2UserService에서 로그인 성공 시 세션에 SessionUser를 저장하도록 구성했다.
- 즉, 로그인 성공 시 httpSession.getAttribute("user")에서 값을 가져올 수 있다.
if (user != null)
- 세션에 저장된 값이 있을 때만 model에 userName으로 등록한다.
- 세션에 저장된 값이 없으면 model엔 아무런 값이 없는 상태이니 로그인 버튼이 보이게 된다.
3. 프로젝트 실행 후 로그인 결과 확인


- 현재 로그인된 사용자의 권환은 GUEST라서 POSTS의 기능을 사용할 수 없다 ‘

- 권한 변경 후 다시 시도 → h2-console에서 사용자의 role를 User로 변경


💜어노테이션 기반으로 개선하기
같은 코드가 반복되는 것 → 개선이 필요한 나쁜 코드
IndexController의 SessionUser user = (SessionUser) httpSession.getAttribute("user");
index 메소드 외에 다른 컨트롤러와 메소드에서 세션값이 필요할 때마다 직접 세션에서 값을 가져와야함
- config.auth 패키지에 @LoginUser 어노테이션 생성
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}
- @Target(ElementType.PARAMETER)
- @interface
- @Retention(RetentionPolicy.RUNTIME)
LoginUserArgumentResolver를 생성
HandlerMethodArgumentResolver 인터페이스를 구현한 클래스
→ 조건에 맞는 경우 메소드가 있다면 구현체가 지정한 값으로 해당 메소드의 파라미터로 넘길 수 있다
package com.jojoIdu.book.springboot.config.auth;
import com.jojoIdu.book.springboot.config.auth.dto.SessionUser;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpSession;
@RequiredArgsConstructor
@Component
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {
private final HttpSession httpSession;
@Override
public boolean supportsParameter(MethodParameter parameter) {
boolean isLoginUserAnnotation = parameter.getParameterAnnotation(LoginUser.class) != null;
boolean isUserClass = SessionUser.class.equals(parameter.getParameterType());
return isLoginUserAnnotation && isUserClass;
}
@Override
public Object resolveArgument(MethodParameter parameter
, ModelAndViewContainer mavContainer
, NativeWebRequest webRequest
,WebDataBinderFactory binderFactory)
throws Exception {
return httpSession.getAttribute("user");
}
}
- supportsParameter
- resolveArgument
2. LoginUserArgumentResolver가 스프링에서 인식될 수 있도록 WebMvcConfigurer에 추가

package com.jojoIdu.book.springboot.config;
import com.jojoIdu.book.springboot.config.auth.LoginUserArgumentResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final LoginUserArgumentResolver loginUserArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> arumentResolvers) {
arumentResolvers.add(loginUserArgumentResolver);
}
}
- HandlerMethodArgumentResolver는 항상 WebMvcConfigurerd의 addArgumentResolvers를 통해 추가해야한다
3. IndexController에서 반복되는 부분들 모두 @LoginUser로 개선
@RequiredArgsConstructor
@Controller
public class IndexController {
private final PostsService postsService;
@GetMapping("/")
public String index(Model model, @LoginUser SessionUser user) {
model.addAttribute("posts", postsService.findAllDesc());
if(user != null) {
model.addAttribute("userName", user.getName());
}
return "index";
}
- 이제 어느 컨트롤러든지 @LoginUser만 사용하면 세션 정보를 가져올 수 있게 된다
💜세션 저장소로 데이터베이스 사용하기
애플리케이션을 재실행하면 로그인이 풀린다
→ 이는 세션이 내장 톰캣의 메모리에 저장되기 때문이다
기본적으로 세션은 실행되는 WAS의 메모리에서 저장되고 호출된다
메모리에 저장되다 보니 내장 톰캣처럼 애플리케이션 실행 시 실행되는 구조에선 항상 초기화가 된다
→ 즉 배포할 때마다 톰캣이 재시작되는 것
2대 이상의 서버에서 서비스하고 있다면 톰캣마다 세션 동기화 설정을 해야한다
→ 실제 현업에선 세션 저장소에 대해 3가지 중 하나를 선택한다
- 톰캣 세션을 사용한다
- MYSQL과 같은 데이터베이스를 세션 저장소로 사용한다
- Redis, Memcached와 같은 메모리 db를 세션 저장소로 사용한다
책에서는 데이터베이스를 세션 저장소로 사용하는 방식 선택하여 실습!
- spring -session -jdbc 등록
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2'
implementation 'org.projectlombok:lombok:1.18.30'
annotationProcessor 'org.projectlombok:lombok:1.18.30'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'junit:junit:4.13.2'
implementation 'org.springframework.boot:spring-boot-starter-mustache'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'org.springframework.boot:spring-boot-starter-security' //추가
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' //추가
implementation 'org.springframework.session:spring-session-jdbc' //추가
}
application.properties
spring.jpa.show_sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
server.servlet.encoding.force-response=true
spring.profiles.include=oauth
spring.session.store-type=jdbc
2. h2-console로 접속
jpa로 인해 세션 테이블이 자동 생성

aws로 배포하게 되면 aws의 데이터베이스 서비스인 rds 를 사용하게 되어 세션이 풀리지 않는다
💜네이버 로그인
네이버 로그인 추가
네이버 API 등록
https://developers.naver.com/apps/#/register?api=nvlogin



spring.security.oauth2.client.registration.google.client-id=구글클라이언트ID
spring.security.oauth2.client.registration.google.client-secret=구글클라이언트시크릿
spring.security.oauth2.client.registration.google.scope=profile,email
# registration
spring.security.oauth2.client.registration.naver.client-id=네이버클라이언트ID
spring.security.oauth2.client.registration.naver.client-secret=네이버클라이언트시크릿
spring.security.oauth2.client.registration.naver.redirect-uri={baseUrl}/{action}/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.naver.scope=name,email,profile_image
spring.security.oauth2.client.registration.naver.client-name=Naver
# provider
spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize
spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token
spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me
spring.security.oauth2.client.provider.naver.user-name-attribute=response
스프링 시큐리티 설정 등록
package com.jojoIdu.book.springboot.config.auth.dto;
import com.jojoIdu.book.springboot.domain.user.Role;
import lombok.Builder;
import lombok.Getter;
import com.jojoIdu.book.springboot.domain.user.User;
import java.util.Map;
import java.util.Objects;
@Getter
public class OAuthAttributes {
private Map<String, Object> attributes;
private String nameAttributeKey;
private String name;
private String email;
private String picture;
@Builder
public OAuthAttributes(Map<String, Object> attributes,
String nameAttributeKey, String name,
String email, String picture
){
this.attributes = attributes;
this.nameAttributeKey= nameAttributeKey;
this.name=name;
this.email = email;
this.picture = picture;
}
public static OAuthAttributes of(String registrationId, String userNameAttributeName,
Map<String, Object> attributes){
if("naver".equals(registrationId)){ //추가
return ofNaver("id", attributes);
}
return ofGoogle(userNameAttributeName, attributes);
}
private static OAuthAttributes ofGoogle(String userNameAttributeName, Map<String, Object> attributes){
return OAuthAttributes.builder()
.name((String) attributes.get("name"))
.email((String) attributes.get("email"))
.picture((String) attributes.get("picture"))
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}
public User toEntity(){
return User.builder()
.name(name)
.email(email)
.picture(picture)
.role(Role.GUEST)
.build();
}
//추가
private static OAuthAttributes ofNaver(String userNameAttributeName, Map<String, Object> attributes) {
Map<String, Object> response = (Map<String, Object>) attributes.get("response");
return OAuthAttributes.builder()
.name((String) response.get("name"))
.email((String)response.get("email"))
.picture((String) response.get("profile_image"))
.attributes(response)
.nameAttributeKey(userNameAttributeName)
.build();
}
}
index.mustache
{{^userName}}
<a href="/oauth2/authorization/google" class="btn btn-success active" role="button">Google Login</a>
<a href="/oauth2/authorization/naver" class="btn btn-secondary active" role="button">Naver Login</a>
{{/userName}}

💜기존 테스트에 시큐리티 적용하기
기존 테스트에서 시큐리티 적용으로 문제되는 부분 해결
→ 기존에는 바로 api를 호출할 수 있어 테스트 코드 역시 바로 api를 호출하도록 구성
✅하지만 시큐리티 옵션이 활성화되면 인증된 사용자만 api를 호출할 수 있다
기존의 api 테스트 코드들이 모두 인증에 대한 권한을 받지 못하였으므로, 테스트 코드마다 인증한 사용자가 호출한 것처럼 작동하도록 수정
test 실행 후 발생하는 문제
- CustomOAuth2UserService을 찾을 수 없음
CustomOAuth2UserService를 생성하는데 필요한 소셜 로그인 관련설정값들이 없기 때문
→ src/main 환경과 src/test 환경의 차이 때문

테스트에 가짜 설정값을 등록
spring.jpa.show_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.session.store-type=jdbc
# Test OAuth
spring.security.oauth2.client.registration.google.client-id=test
spring.security.oauth2.client.registration.google.client-secret=test
spring.security.oauth2.client.registration.google.scope=profile,email
2. 302 Status Code
스프링 시큐리티 설정상 인증되지 않은 사용자의 요청은 이동시키기 때문에 발생한다
build.grade에 spring-security-test 설정을 추가
testImplementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'
PostsApiControllerTest
@Test
@WithMockUser(roles="USER")
public void testCreatePost() throws Exception{
}
@Test
@WithMockUser(roles = "USER")
public void testEditPost() throws Exception{
}
- @WithMockUser(roles = “USER”)
@WithMockUser는 MockMvc에서만 작동
@SpringBootTest에서 MockMvc를 사용
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PostsApiControllerTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private PostsRepository postsRepository;
//MockMvc 설정 추가
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@After
public void tearDown() throws Exception {
postsRepository.deleteAll();
}
@Test
@WithMockUser(roles="USER")
public void testCreatePost() throws Exception { //Posts등록
//given
String title = "title";
String content = "content";
PostsSaveRequestDto requestDto = PostsSaveRequestDto.builder()
.title(title)
.content(content)
.author("author")
.build();
String url = "http://localhost:" + port + "/api/v1/posts";
//when
mvc.perform(post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(new ObjectMapper().writeValueAsString(requestDto)))
.andExpect(status().isOk());
//then
List<Posts> all = postsRepository.findAll();
assertThat(all.get(0).getTitle()).isEqualTo(title);
assertThat(all.get(0).getContent()).isEqualTo(content);
}
@Test
@WithMockUser(roles="USER")
public void PostsEdited() throws Exception {
//given
Posts savedPosts = postsRepository.save(Posts.builder()
.title("title")
.content("content")
.author("author")
.build());
Long updateId = savedPosts.getId();
String expectedTitle = "title2";
String expectedContent = "content2";
PostsUpdateRequestDto requestDto = PostsUpdateRequestDto.builder()
.title(expectedTitle)
.content(expectedContent)
.build();
String url = "http://localhost:" + port + "/api/v1/posts/" + updateId;
//when
mvc.perform(put(url)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(new ObjectMapper().writeValueAsString(requestDto)))
.andExpect(status().isOk());
//then
List<Posts> all = postsRepository.findAll();
assertThat(all.get(0).getTitle()).isEqualTo(expectedTitle);
assertThat(all.get(0).getContent()).isEqualTo(expectedContent);
}
}
- @Before
- mvc.perform
3. WebMvcTest에서 CustomOAuth2UserSErvice를 찾을 수 없음
스캔 대상에서 SecurityConfig를 제거한다
package com.jojoIdu.book.springboot;
import com.jojoIdu.book.springboot.config.auth.SecurityConfig;
import com.jojoIdu.book.springboot.web.HelloController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class,
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
}
)
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@WithMockUser(roles="USER")
@Test
public void hello_return() throws Exception {
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
@WithMockUser(roles="USER")
@Test
public void helloDto_return() throws Exception {
String name = "hello";
int amount = 1000;
mvc.perform(
get("/hello/dto")
.param("name", name)
.param("amount", String.valueOf(amount)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(name)))
.andExpect(jsonPath("$.amount", is(amount)));
}
}
@EnableJpaAuditing으로 인해서 발생하는 추가에러
→Application.java에서 삭제해준다

package com.jojoIdu.book.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.
SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
'⚙️ Back-end > Spring' 카테고리의 다른 글
[Spring Boot] 3주차 스터디 : 7장 AWS에 데이터베이스 환경을 만들어보자 - AWS RDS (0) | 2025.02.04 |
---|---|
[Spring Boot] 3주차 스터디 : 6장 AWS 서버 환경을 만들어보자 - AWS EC2 (0) | 2025.01.24 |
[Spring Boot] 2주차 스터디 : 4장 머스테치로 화면 구성하기 (0) | 2025.01.15 |
[Spring Boot] 2주차 스터디 : 3장 스프링 부트에서 JPA로 데이터 베이스를 다뤄보자 (1) | 2025.01.14 |
[Spring Boot] 1주차 스터디 : 2장 스프링 부트에서 테스트 코드를 작성하자 (1) | 2025.01.14 |