Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04a317d582 | ||
|
|
d50b40527d | ||
|
|
301ac29c98 | ||
|
|
6fd9e57bfc | ||
|
|
24d40aa46e | ||
|
|
a845fe1b63 | ||
|
|
a31df05aa4 | ||
|
|
07b7107b2a | ||
|
|
3feab69ec4 | ||
|
|
f5ac7e8de5 | ||
|
|
38b8ec824b | ||
|
|
943b8bc7ff | ||
|
|
07f66e3c34 | ||
|
|
9f13dc78b7 | ||
|
|
4ac6e75311 | ||
|
|
fc26a2a1cc | ||
|
|
02228ed615 | ||
|
|
fe53bc9ef0 | ||
|
|
cb9d35afd9 | ||
|
|
1eee369124 | ||
|
|
b033747ec3 | ||
|
|
baa59f24a5 | ||
|
|
c5827d07fa | ||
|
|
f307710223 | ||
|
|
c51cf8b525 | ||
|
|
26b0dad1ab | ||
|
|
b54514acab | ||
|
|
06a5352fb9 | ||
|
|
e28750154e |
31
README.md
31
README.md
@@ -2,5 +2,34 @@
|
||||
|
||||
Spring Boot를 이용한 간단한 JWT 예시 레포지토리
|
||||
|
||||
# Getting Started
|
||||
|
||||
# How to use authenticationManager Bean in 5.7.1
|
||||
|
||||
> 참고 : https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
|
||||
|
||||
### Question
|
||||
Is there any example how can I expose the AuthenticationManager bean? Previously I could do this by extending WebSecurityConfigurerAdapter and then creating the following method in my security config:
|
||||
```
|
||||
@Override
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
```
|
||||
|
||||
### Answer
|
||||
The following solution solved the issue for me.
|
||||
```
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
```
|
||||
|
||||
# TODO
|
||||
|
||||
|
||||
### Done ✓
|
||||
|
||||
- [x] Post on Blog
|
||||
- [x] Implement regenerate refresh token test code
|
||||
12
build.gradle
12
build.gradle
@@ -49,12 +49,22 @@ dependencies {
|
||||
/*
|
||||
Security
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security:2.7.0'
|
||||
|
||||
/*
|
||||
Validation
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
|
||||
/*
|
||||
Jwt (JSON Web Token Support For The JVM)
|
||||
*/
|
||||
implementation 'io.jsonwebtoken:jjwt:0.9.1'
|
||||
|
||||
/*
|
||||
Redis
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
|
||||
@@ -8,27 +8,27 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class AppConfig {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder bCryptPasswordEncoder;
|
||||
|
||||
public AppConfig(UserRepository userRepository, PasswordEncoder bCryptPasswordEncoder) {
|
||||
System.out.println("AppConfig");
|
||||
System.out.println("userRepository = " + userRepository);
|
||||
this.userRepository = userRepository;
|
||||
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UserService userService() {
|
||||
System.out.println("userService");
|
||||
return new UserServiceImpl(userRepository, bCryptPasswordEncoder);
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public BCryptPasswordEncoder passwordEncoder() {
|
||||
// System.out.println("passwordEncoder");
|
||||
// return new BCryptPasswordEncoder();
|
||||
//@Configuration
|
||||
//public class AppConfig {
|
||||
// private final UserRepository userRepository;
|
||||
// private final PasswordEncoder bCryptPasswordEncoder;
|
||||
//
|
||||
// public AppConfig(UserRepository userRepository, PasswordEncoder bCryptPasswordEncoder) {
|
||||
// System.out.println("AppConfig");
|
||||
// System.out.println("userRepository = " + userRepository);
|
||||
// this.userRepository = userRepository;
|
||||
// this.bCryptPasswordEncoder = bCryptPasswordEncoder;
|
||||
// }
|
||||
}
|
||||
//
|
||||
// @Bean
|
||||
// public UserService userService() {
|
||||
// System.out.println("userService");
|
||||
// return new UserServiceImpl(userRepository, bCryptPasswordEncoder);
|
||||
// }
|
||||
//
|
||||
//// @Bean
|
||||
//// public BCryptPasswordEncoder passwordEncoder() {
|
||||
//// System.out.println("passwordEncoder");
|
||||
//// return new BCryptPasswordEncoder();
|
||||
//// }
|
||||
//}
|
||||
|
||||
37
src/main/java/demo/api/auth/AuthController.java
Normal file
37
src/main/java/demo/api/auth/AuthController.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package demo.api.auth;
|
||||
|
||||
import demo.api.auth.dtos.SignUpRes;
|
||||
import demo.api.jwt.dtos.RegenerateTokenDto;
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.auth.dtos.SignInReq;
|
||||
import demo.api.auth.dtos.SignUpReq;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/signUp")
|
||||
public SignUpRes signUp(@Validated SignUpReq signUpReq) {
|
||||
return authService.signUp(signUpReq);
|
||||
}
|
||||
|
||||
@PostMapping("/signIn")
|
||||
public ResponseEntity<TokenDto> signIn(@Validated SignInReq signInReq) {
|
||||
return authService.signIn(signInReq);
|
||||
}
|
||||
|
||||
@PostMapping("/regenerateToken")
|
||||
public ResponseEntity<TokenDto> regenerateToken(@Validated RegenerateTokenDto refreshTokenDto) {
|
||||
return authService.regenerateToken(refreshTokenDto);
|
||||
}
|
||||
}
|
||||
26
src/main/java/demo/api/auth/AuthService.java
Normal file
26
src/main/java/demo/api/auth/AuthService.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package demo.api.auth;
|
||||
|
||||
import demo.api.auth.dtos.SignUpRes;
|
||||
import demo.api.jwt.dtos.RegenerateTokenDto;
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.auth.dtos.SignInReq;
|
||||
import demo.api.auth.dtos.SignUpReq;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
public interface AuthService {
|
||||
/**
|
||||
* 유저의 정보로 회원가입
|
||||
* @param signUpReq 가입할 유저의 정보 Dto
|
||||
* @return 가입된 유저 정보
|
||||
*/
|
||||
SignUpRes signUp(SignUpReq signUpReq);
|
||||
|
||||
/**
|
||||
* 유저 정보로 로그인
|
||||
* @param signInReq 유저의 이메일과 비밀번호
|
||||
* @return json web token
|
||||
*/
|
||||
ResponseEntity<TokenDto> signIn(SignInReq signInReq);
|
||||
|
||||
ResponseEntity<TokenDto> regenerateToken(RegenerateTokenDto refreshTokenDto);
|
||||
}
|
||||
132
src/main/java/demo/api/auth/AuthServiceImpl.java
Normal file
132
src/main/java/demo/api/auth/AuthServiceImpl.java
Normal file
@@ -0,0 +1,132 @@
|
||||
package demo.api.auth;
|
||||
|
||||
import demo.api.auth.dtos.SignUpRes;
|
||||
import demo.api.exception.CustomException;
|
||||
import demo.api.jwt.JwtTokenProvider;
|
||||
import demo.api.jwt.dtos.RegenerateTokenDto;
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.auth.dtos.SignInReq;
|
||||
import demo.api.auth.dtos.SignUpReq;
|
||||
import demo.api.user.repository.UserRepository;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthServiceImpl implements AuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder bCryptPasswordEncoder;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final RedisTemplate<String, String> redisTemplate;
|
||||
|
||||
@Value("${jwt.token.refresh-token-expire-length}")
|
||||
private long refresh_token_expire_time;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public SignUpRes signUp(SignUpReq signUpReq){
|
||||
System.out.println("signUpReq = " + signUpReq.toString());
|
||||
|
||||
if(userRepository.existsByEmail(signUpReq.getEmail())) {
|
||||
return new SignUpRes(false, "Your Mail already Exist.");
|
||||
}
|
||||
User newUser = signUpReq.toUserEntity();
|
||||
newUser.hashPassword(bCryptPasswordEncoder);
|
||||
|
||||
User user = userRepository.save(newUser);
|
||||
if(!Objects.isNull(user)) {
|
||||
return new SignUpRes(true, null);
|
||||
}
|
||||
return new SignUpRes(false, "Fail to Sign Up");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<TokenDto> signIn(SignInReq signInReq) {
|
||||
try {
|
||||
Authentication authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
signInReq.getEmail(),
|
||||
signInReq.getPassword()
|
||||
)
|
||||
);
|
||||
|
||||
String refresh_token = jwtTokenProvider.generateRefreshToken(authentication);
|
||||
|
||||
TokenDto tokenDto = new TokenDto(
|
||||
jwtTokenProvider.generateAccessToken(authentication),
|
||||
refresh_token
|
||||
);
|
||||
|
||||
// Redis에 저장 - 만료 시간 설정을 통해 자동 삭제 처리
|
||||
redisTemplate.opsForValue().set(
|
||||
authentication.getName(),
|
||||
refresh_token,
|
||||
refresh_token_expire_time,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.add("Authorization", "Bearer " + tokenDto.getAccess_token());
|
||||
|
||||
return new ResponseEntity<>(tokenDto, httpHeaders, HttpStatus.OK);
|
||||
} catch (AuthenticationException e) {
|
||||
throw new CustomException("Invalid credentials supplied", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<TokenDto> regenerateToken(RegenerateTokenDto refreshTokenDto) {
|
||||
String refresh_token = refreshTokenDto.getRefresh_token();
|
||||
try {
|
||||
// Refresh Token 검증
|
||||
if (!jwtTokenProvider.validateRefreshToken(refresh_token)) {
|
||||
throw new CustomException("Invalid refresh token supplied", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Access Token 에서 User email를 가져온다.
|
||||
Authentication authentication = jwtTokenProvider.getAuthenticationByRefreshToken(refresh_token);
|
||||
|
||||
// Redis에서 저장된 Refresh Token 값을 가져온다.
|
||||
String refreshToken = redisTemplate.opsForValue().get(authentication.getName());
|
||||
if(!refreshToken.equals(refresh_token)) {
|
||||
throw new CustomException("Refresh Token doesn't match.", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// 토큰 재발행
|
||||
String new_refresh_token = jwtTokenProvider.generateRefreshToken(authentication);
|
||||
TokenDto tokenDto = new TokenDto(
|
||||
jwtTokenProvider.generateAccessToken(authentication),
|
||||
new_refresh_token
|
||||
);
|
||||
|
||||
// RefreshToken Redis에 업데이트
|
||||
redisTemplate.opsForValue().set(
|
||||
authentication.getName(),
|
||||
new_refresh_token,
|
||||
refresh_token_expire_time,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
|
||||
return new ResponseEntity<>(tokenDto, httpHeaders, HttpStatus.OK);
|
||||
} catch (AuthenticationException e) {
|
||||
throw new CustomException("Invalid refresh token supplied", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
24
src/main/java/demo/api/auth/dtos/SignInReq.java
Normal file
24
src/main/java/demo/api/auth/dtos/SignInReq.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package demo.api.auth.dtos;
|
||||
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.ToString;
|
||||
|
||||
@Getter
|
||||
@ToString
|
||||
public class SignInReq {
|
||||
@NotEmpty(message = "Please enter your Email")
|
||||
@Email
|
||||
private String email;
|
||||
@NotEmpty(message = "Please enter your Password")
|
||||
private String password;
|
||||
|
||||
@Builder
|
||||
public SignInReq(String email, String password) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
package demo.api.user.dtos;
|
||||
package demo.api.auth.dtos;
|
||||
|
||||
import demo.api.user.domain.User;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
|
||||
@Getter
|
||||
@ToString
|
||||
public class UserSignUpRequest {
|
||||
public class SignUpReq {
|
||||
@NotEmpty(message = "Please enter your Email")
|
||||
@Email
|
||||
private String email;
|
||||
@@ -20,7 +19,7 @@ public class UserSignUpRequest {
|
||||
private String name;
|
||||
|
||||
@Builder
|
||||
public UserSignUpRequest(String email, String password, String name) {
|
||||
public SignUpReq(String email, String password, String name) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
17
src/main/java/demo/api/auth/dtos/SignUpRes.java
Normal file
17
src/main/java/demo/api/auth/dtos/SignUpRes.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package demo.api.auth.dtos;
|
||||
|
||||
import demo.api.common.dtos.CoreRes;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.ToString;
|
||||
|
||||
|
||||
@Getter
|
||||
public class SignUpRes extends CoreRes {
|
||||
public SignUpRes(boolean ok, String error) {
|
||||
super(ok, error);
|
||||
}
|
||||
}
|
||||
11
src/main/java/demo/api/common/dtos/CoreRes.java
Normal file
11
src/main/java/demo/api/common/dtos/CoreRes.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package demo.api.common.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class CoreRes {
|
||||
private boolean ok;
|
||||
private String error;
|
||||
}
|
||||
26
src/main/java/demo/api/config/JwtSecurityConfig.java
Normal file
26
src/main/java/demo/api/config/JwtSecurityConfig.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package demo.api.config;
|
||||
|
||||
import demo.api.jwt.JwtTokenFilter;
|
||||
import demo.api.jwt.JwtTokenProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* SecurityConfigurerAdapter를 확장.
|
||||
* JwtTokenProvider를 주입받음.
|
||||
* JwtFilter를 통해 Security filterchain에 filter를 추가 등록
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class JwtSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) throws Exception {
|
||||
JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider);
|
||||
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
}
|
||||
|
||||
}
|
||||
42
src/main/java/demo/api/config/RedisConfig.java
Normal file
42
src/main/java/demo/api/config/RedisConfig.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package demo.api.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
@Value("${redis.host}")
|
||||
private String redisHost;
|
||||
|
||||
@Value("${redis.port}")
|
||||
private int redisPort;
|
||||
|
||||
/*
|
||||
RedisTemplate을 이용한 방식
|
||||
|
||||
RedisConnectionFactory 인터페이스를 통해
|
||||
LettuceConnectionFactory를 생성하여 반환
|
||||
*/
|
||||
@Bean
|
||||
public RedisConnectionFactory redisConnectionFactory() {
|
||||
return new LettuceConnectionFactory(redisHost, redisPort);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, String> redisTemplate() {
|
||||
// redisTemplate를 받아와서 set, get, delete를 사용
|
||||
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
|
||||
// setKeySerializer, setValueSerializer 설정
|
||||
// redis-cli을 통해 직접 데이터를 조회 시 알아볼 수 없는 형태로 출력되는 것을 방지
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new StringRedisSerializer());
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory());
|
||||
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
@@ -1,67 +1,74 @@
|
||||
package demo.api.config;
|
||||
|
||||
import demo.api.jwt.JwtAccessDeniedHandler;
|
||||
import demo.api.jwt.JwtAuthenticationEntryPoint;
|
||||
import demo.api.jwt.JwtTokenFilter;
|
||||
import demo.api.jwt.JwtTokenProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
|
||||
/**
|
||||
* Spring Security 사용을 위한 Configuration Class를 작성하기 위해서
|
||||
* WebSecurityConfigurerAdapter를 상속하여 클래스를 생성하고
|
||||
* @Configuration 애노테이션 대신 @EnableWebSecurity 애노테이션을 추가한다.
|
||||
*/
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
private final UserDetailsService userDetailsService;
|
||||
public class SecurityConfig {
|
||||
// 추가된 jwt 관련 친구들을 security config에 추가
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
|
||||
/**
|
||||
* PasswordEncoder를 Bean으로 등록
|
||||
*/
|
||||
@Bean
|
||||
public BCryptPasswordEncoder bCryptPasswordEncoder() {
|
||||
public BCryptPasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 인증 or 인가가 필요 없는 경로를 설정
|
||||
// */
|
||||
// @Override
|
||||
// public void configure(WebSecurity web) throws Exception {
|
||||
// web.ignoring().antMatchers("/?/**");
|
||||
// }
|
||||
|
||||
/**
|
||||
* 인증에 대한 지원
|
||||
*/
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(
|
||||
AuthenticationConfiguration authenticationConfiguration
|
||||
) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 or 인가에 대한 설정
|
||||
*/
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
// Disable csrf to use token
|
||||
http
|
||||
.csrf().disable()
|
||||
.formLogin()
|
||||
.loginPage("/user/signIn")
|
||||
.loginProcessingUrl("/user/signInProc")
|
||||
.usernameParameter("email")
|
||||
.passwordParameter("password")
|
||||
.defaultSuccessUrl("/")
|
||||
.failureUrl("/user/signIn?fail=true");
|
||||
.csrf().disable();
|
||||
|
||||
//
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/", "/user/signUp", "/user/userList", "/user/signIn*").permitAll()
|
||||
.antMatchers(
|
||||
"/",
|
||||
"/auth/signUp",
|
||||
"/user/userList",
|
||||
"/auth/signIn*",
|
||||
"/user/profile/view/**",
|
||||
"/auth/regenerateToken",
|
||||
"/favicon.ico"
|
||||
).permitAll()
|
||||
.anyRequest().authenticated();
|
||||
|
||||
// No session will be created or used by spring security
|
||||
http
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
|
||||
|
||||
// exception handling for jwt
|
||||
http
|
||||
.exceptionHandling()
|
||||
.accessDeniedHandler(jwtAccessDeniedHandler)
|
||||
.authenticationEntryPoint(jwtAuthenticationEntryPoint);
|
||||
|
||||
// Apply JWT
|
||||
http.apply(new JwtSecurityConfig(jwtTokenProvider));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,26 @@
|
||||
package demo.api.config;
|
||||
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.exception.UserNotFoundException;
|
||||
import demo.api.exception.UserNotFoundException;
|
||||
import demo.api.user.repository.UserRepository;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||
private final UserRepository userRepository;
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String email) throws UserNotFoundException {
|
||||
|
||||
System.out.println("email in loadUserByUsername = " + email);
|
||||
User user = userRepository.findByEmail(email)
|
||||
.orElseThrow(() -> new UserNotFoundException());
|
||||
.orElseThrow(UserNotFoundException::new);
|
||||
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
|
||||
|
||||
return new org
|
||||
|
||||
26
src/main/java/demo/api/exception/CustomException.java
Normal file
26
src/main/java/demo/api/exception/CustomException.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package demo.api.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String message;
|
||||
private final HttpStatus httpStatus;
|
||||
|
||||
public CustomException(String message, HttpStatus httpStatus) {
|
||||
this.message = message;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public HttpStatus getHttpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package demo.api.user.exception;
|
||||
package demo.api.exception;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException() {
|
||||
24
src/main/java/demo/api/jwt/JwtAccessDeniedHandler.java
Normal file
24
src/main/java/demo/api/jwt/JwtAccessDeniedHandler.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package demo.api.jwt;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* AccessDeniedHandler
|
||||
*
|
||||
* AuthenticationEntryPoint와 달리 AccessDeniedHandler는
|
||||
* 유저 정보는 있으나, 엑세스 권한이 없는 경우 동작하는 친구이다.
|
||||
*/
|
||||
@Component
|
||||
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
}
|
||||
34
src/main/java/demo/api/jwt/JwtAuthenticationEntryPoint.java
Normal file
34
src/main/java/demo/api/jwt/JwtAuthenticationEntryPoint.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package demo.api.jwt;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* AuthenticationEntryPoint
|
||||
*
|
||||
* 인증 과정에서 실패하거나 인증을 위한 헤더정보를 보내지 않은 경우
|
||||
* 401(UnAuthorized) 에러가 발생하게 된다.
|
||||
*
|
||||
* Spring Security에서 인증되지 않은 사용자에 대한 접근 처리는 AuthenticationEntryPoint가 담당하는데,
|
||||
* commence 메소드가 실행되어 처리된다.
|
||||
*/
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
@Override
|
||||
public void commence(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
AuthenticationException e
|
||||
) throws IOException {
|
||||
System.out.println(request.getRequestURI());
|
||||
log.error("UnAuthorized -- message : " + e.getMessage()); // 로그를 남기고
|
||||
response.sendRedirect("/auth/signIn"); // 로그인 페이지로 리다이렉트되도록 하였다.
|
||||
}
|
||||
}
|
||||
41
src/main/java/demo/api/jwt/JwtTokenFilter.java
Normal file
41
src/main/java/demo/api/jwt/JwtTokenFilter.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package demo.api.jwt;
|
||||
|
||||
import demo.api.exception.CustomException;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
// Request 이전에 1회 작동할 필터
|
||||
public class JwtTokenFilter extends OncePerRequestFilter {
|
||||
private JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
String token = jwtTokenProvider.resolveToken(request);
|
||||
try {
|
||||
if (token != null && jwtTokenProvider.validateAccessToken(token)) {
|
||||
Authentication auth = jwtTokenProvider.getAuthenticationByAccessToken(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth); // 정상 토큰이면 SecurityContext에 저장
|
||||
}
|
||||
} catch (CustomException e) {
|
||||
SecurityContextHolder.clearContext();
|
||||
response.sendError(e.getHttpStatus().value(), e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
142
src/main/java/demo/api/jwt/JwtTokenProvider.java
Normal file
142
src/main/java/demo/api/jwt/JwtTokenProvider.java
Normal file
@@ -0,0 +1,142 @@
|
||||
package demo.api.jwt;
|
||||
|
||||
import demo.api.exception.CustomException;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import java.util.Date;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
// 유저 정보로 JWT 토큰을 만들거나 토큰을 바탕으로 유저 정보를 가져옴
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
@Value("${jwt.token.access-token-secret-key}")
|
||||
private String access_token_secret_key;
|
||||
|
||||
@Value("${jwt.token.refresh-token-secret-key}")
|
||||
private String refresh_token_secret_key;
|
||||
|
||||
@Value("${jwt.token.access-token-expire-length}")
|
||||
private long access_token_expire_time;
|
||||
|
||||
@Value("${jwt.token.refresh-token-expire-length}")
|
||||
private long refresh_token_expire_time;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
/**
|
||||
* 적절한 설정을 통해 Access 토큰을 생성하여 반환
|
||||
* @param authentication
|
||||
* @return access token
|
||||
*/
|
||||
public String generateAccessToken(Authentication authentication) {
|
||||
Claims claims = Jwts.claims().setSubject(authentication.getName());
|
||||
// claims.put("auth", appUserRoles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
|
||||
|
||||
Date now = new Date();
|
||||
Date expiresIn = new Date(now.getTime() + access_token_expire_time);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiresIn)
|
||||
.signWith(SignatureAlgorithm.HS256, access_token_secret_key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 적절한 설정을 통해 Refresh 토큰을 생성하여 반환
|
||||
* @param authentication
|
||||
* @return refresh token
|
||||
*/
|
||||
public String generateRefreshToken(Authentication authentication) {
|
||||
Claims claims = Jwts.claims().setSubject(authentication.getName());
|
||||
|
||||
Date now = new Date();
|
||||
Date expiresIn = new Date(now.getTime() + refresh_token_expire_time);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiresIn)
|
||||
.signWith(SignatureAlgorithm.HS256, refresh_token_secret_key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* Access 토큰으로부터 클레임을 만들고, 이를 통해 User 객체를 생성하여 Authentication 객체를 반환
|
||||
* @param access_token
|
||||
* @return
|
||||
*/
|
||||
public Authentication getAuthenticationByAccessToken(String access_token) {
|
||||
String userPrincipal = Jwts.parser().setSigningKey(access_token_secret_key).parseClaimsJws(access_token).getBody().getSubject();
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(userPrincipal);
|
||||
|
||||
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh 토큰으로부터 클레임을 만들고, 이를 통해 User 객체를 생성하여 Authentication 객체를 반환
|
||||
* @param refresh_token
|
||||
* @return
|
||||
*/
|
||||
public Authentication getAuthenticationByRefreshToken(String refresh_token) {
|
||||
String userPrincipal = Jwts.parser().setSigningKey(refresh_token_secret_key).parseClaimsJws(refresh_token).getBody().getSubject();
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(userPrincipal);
|
||||
|
||||
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
|
||||
}
|
||||
|
||||
/**
|
||||
* http 헤더로부터 bearer 토큰을 가져옴.
|
||||
* @param req
|
||||
* @return
|
||||
*/
|
||||
public String resolveToken(HttpServletRequest req) {
|
||||
String bearerToken = req.getHeader("Authorization");
|
||||
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access 토큰을 검증
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public boolean validateAccessToken(String token) {
|
||||
try {
|
||||
Jwts.parser().setSigningKey(access_token_secret_key).parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
// MalformedJwtException | ExpiredJwtException | IllegalArgumentException
|
||||
throw new CustomException("Error on Access Token", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh 토큰을 검증
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public boolean validateRefreshToken(String token) {
|
||||
try {
|
||||
Jwts.parser().setSigningKey(refresh_token_secret_key).parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
// MalformedJwtException | ExpiredJwtException | IllegalArgumentException
|
||||
throw new CustomException("Error on Refresh Token", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/main/java/demo/api/jwt/dtos/RegenerateTokenDto.java
Normal file
10
src/main/java/demo/api/jwt/dtos/RegenerateTokenDto.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package demo.api.jwt.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public class RegenerateTokenDto {
|
||||
private String refresh_token;
|
||||
}
|
||||
11
src/main/java/demo/api/jwt/dtos/TokenDto.java
Normal file
11
src/main/java/demo/api/jwt/dtos/TokenDto.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package demo.api.jwt.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public class TokenDto {
|
||||
private String access_token;
|
||||
private String refresh_token;
|
||||
}
|
||||
@@ -1,71 +1,51 @@
|
||||
package demo.api.user;
|
||||
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import demo.api.user.exception.UserNotFoundException;
|
||||
import demo.api.user.dtos.ProfileDto.ProfileRes;
|
||||
import demo.api.exception.UserNotFoundException;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* User 관련 HTTP 요청 처리
|
||||
*/
|
||||
@Controller
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
@RequiredArgsConstructor
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping("/signUp")
|
||||
public String signUp() {
|
||||
return "user/signUp";
|
||||
}
|
||||
|
||||
@PostMapping("/signUp")
|
||||
public String signUp(@Validated UserSignUpRequest signUpReq) throws Exception {
|
||||
User user = userService.signUp(signUpReq);
|
||||
|
||||
return "redirect:/user/signIn";
|
||||
}
|
||||
|
||||
@GetMapping("/signIn")
|
||||
public String signIn(@RequestParam(value = "fail", required = false) String flag, Model model) {
|
||||
model.addAttribute("failed", flag != null);
|
||||
|
||||
return "user/signIn";
|
||||
}
|
||||
// @Autowired
|
||||
// private UserDetailsService userDetailsService;
|
||||
@GetMapping("/profile")
|
||||
public String profile(Model model, @AuthenticationPrincipal UserDetails userDetails) {
|
||||
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
// System.out.println("principal : " + authentication.getPrincipal());
|
||||
// System.out.println("Implementing class of UserDetails: " + authentication.getPrincipal().getClass());
|
||||
// System.out.println("Implementing class of UserDetailsService: " + userDetailsService.getClass());
|
||||
if (userDetails != null) {
|
||||
User userDetail = userService.findByEmail(userDetails.getUsername())
|
||||
.orElseThrow(() -> new UserNotFoundException());
|
||||
public ProfileRes profile(@AuthenticationPrincipal UserDetails userDetails) throws UserNotFoundException {
|
||||
System.out.println("userDetails = " + userDetails);
|
||||
User userDetail = userService.findByEmail(userDetails.getUsername())
|
||||
.orElseThrow(() -> new UserNotFoundException());
|
||||
|
||||
model.addAttribute("userDetail", userDetail);
|
||||
}
|
||||
|
||||
return "user/profile";
|
||||
return ProfileRes.builder()
|
||||
.email(userDetail.getEmail())
|
||||
.name(userDetail.getName())
|
||||
.build();
|
||||
}
|
||||
|
||||
@GetMapping("/user/userList")
|
||||
public String showUserList(Model model) {
|
||||
List<User> userList = userService.findAll();
|
||||
@GetMapping("/profile/view/{username}")
|
||||
public ProfileRes userProfile(@PathVariable String username) throws UserNotFoundException {
|
||||
User user = userService.findByName(username)
|
||||
.orElseThrow(UserNotFoundException::new);
|
||||
|
||||
model.addAttribute("userList", userList);
|
||||
return ProfileRes.builder()
|
||||
.email(user.getEmail())
|
||||
.name(user.getName())
|
||||
.build();
|
||||
}
|
||||
|
||||
return "user/userList";
|
||||
@GetMapping("/userList")
|
||||
public List<User> showUserList() {
|
||||
return userService.findAll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
package demo.api.user;
|
||||
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserService {
|
||||
/**
|
||||
* 유저의 정보로 회원가입
|
||||
* @param signUpReq 가입할 유저의 정보 Dto
|
||||
* @return 가입된 유저 정보
|
||||
*/
|
||||
User signUp(UserSignUpRequest signUpReq) throws Exception;
|
||||
|
||||
/**
|
||||
* 모든 유저 리스트를 반환
|
||||
* @return 유저 리스트
|
||||
@@ -26,6 +18,19 @@ public interface UserService {
|
||||
*/
|
||||
Optional<User> findByEmail(String email);
|
||||
|
||||
/**
|
||||
* 이름을 통해 유저 조회
|
||||
* @param name
|
||||
* @return 조회된 유저
|
||||
*/
|
||||
Optional<User> findByName(String name);
|
||||
|
||||
// /**
|
||||
// * Security Context에 존재하는 인증 정보를 통해 유저 정보 조회
|
||||
// * @return 조회된 유저
|
||||
// */
|
||||
// Optional<User> getMyInfo();
|
||||
|
||||
/**
|
||||
* 유저 정보 수정
|
||||
* @param user 수정활 User Entity
|
||||
|
||||
@@ -1,32 +1,18 @@
|
||||
package demo.api.user;
|
||||
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import demo.api.user.repository.UserRepository;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional
|
||||
public class UserServiceImpl implements UserService {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder bCryptPasswordEncoder;
|
||||
|
||||
@Override
|
||||
public User signUp(UserSignUpRequest signUpReq) throws Exception {
|
||||
System.out.println("signUpReq = " + signUpReq.toString());
|
||||
if(this.isEmailExist(signUpReq.getEmail())) {
|
||||
throw new Exception("Your Mail already Exist.");
|
||||
}
|
||||
User newUser = signUpReq.toUserEntity();
|
||||
newUser.hashPassword(bCryptPasswordEncoder);
|
||||
return userRepository.save(newUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findAll() {
|
||||
@@ -38,19 +24,13 @@ public class UserServiceImpl implements UserService {
|
||||
return userRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByName(String name) {
|
||||
return userRepository.findByName(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User updateUser(User user, String newInfo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 이메일 중복 여부를 확인
|
||||
*
|
||||
* @param email
|
||||
* @return true | false
|
||||
*/
|
||||
private boolean isEmailExist(String email) {
|
||||
Optional<User> byEmail = userRepository.findByEmail(email);
|
||||
return !byEmail.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ public class User extends CoreEntity {
|
||||
private String email;
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
@Column(length = 10, nullable = false)
|
||||
@Column(length = 10, nullable = false, unique = true)
|
||||
private String name;
|
||||
|
||||
// @Enumerated(EnumType.STRING)
|
||||
@@ -47,14 +47,4 @@ public class User extends CoreEntity {
|
||||
this.password = passwordEncoder.encode(this.password);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 비밀번호 확인
|
||||
* @param plainPassword 암호화 이전의 비밀번호
|
||||
* @param passwordEncoder 암호화에 사용된 클래스
|
||||
* @return true | false
|
||||
*/
|
||||
public boolean checkPassword(String plainPassword, PasswordEncoder passwordEncoder) {
|
||||
return passwordEncoder.matches(plainPassword, this.password);
|
||||
}
|
||||
}
|
||||
|
||||
19
src/main/java/demo/api/user/dtos/ProfileDto.java
Normal file
19
src/main/java/demo/api/user/dtos/ProfileDto.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package demo.api.user.dtos;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
public class ProfileDto {
|
||||
@Data
|
||||
@Builder
|
||||
public static class ProfileReq {
|
||||
private String name;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class ProfileRes {
|
||||
private String email;
|
||||
private String name;
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,18 @@ import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
// @Repository
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
Optional<User> findByEmail(String email);
|
||||
|
||||
Optional<User> findByName(String name);
|
||||
|
||||
/**
|
||||
* 이메일 중복 여부를 확인
|
||||
*
|
||||
* @param email
|
||||
* @return true | false
|
||||
*/
|
||||
boolean existsByEmail(String email);
|
||||
}
|
||||
|
||||
@@ -8,4 +8,14 @@ spring:
|
||||
jpa:
|
||||
show-sql: true
|
||||
hibernate:
|
||||
ddl-auto: none
|
||||
format_sql: true
|
||||
ddl-auto: none
|
||||
jwt:
|
||||
token:
|
||||
access-token-secret-key: aG91Mjctc2ltcGxlLXNwcmluZy1ib290LWFwaS1qd3QK
|
||||
access-token-expire-length: 300000
|
||||
refresh-token-secret-key: cmVmcmVzaHRva2Vuc2VjcmV0a2V5Cg==
|
||||
refresh-token-expire-length: 6000000
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
@@ -1,17 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<div class="container">
|
||||
<div>
|
||||
<h1>Test Page</h1>
|
||||
<p>User</p>
|
||||
<p>
|
||||
<a href="/user/signUp">Sign Up</a>
|
||||
<a href="/user/signIn">Sign In</a>
|
||||
<br>
|
||||
<a href="/user/profile">Profile</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,24 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<div class="container">
|
||||
<div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>My Profile</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:if="${userDetail}">
|
||||
<td th:text="${userDetail.getEmail()}"></td>
|
||||
<td th:text="${userDetail.getName()}"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<a href="/">Home</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,26 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div>
|
||||
<h2>로그인</h2>
|
||||
</div>
|
||||
<h3 th:if="${failed}">Fail to login</h3>
|
||||
<form action="/user/signInProc" method="post">
|
||||
<div class="form-group">
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" name="email" placeholder="Enter your email">
|
||||
<br/>
|
||||
<label for="password">PW</label>
|
||||
<input type="password" id="password" name="password" placeholder="Enter your password">
|
||||
</div>
|
||||
<button type="submit">Sign In</button>
|
||||
</form>
|
||||
</div>
|
||||
<a href="/">Home</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,24 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<div class="container">
|
||||
<div>
|
||||
<h2>회원가입</h2>
|
||||
</div>
|
||||
<form action="/user/signUp" method="post">
|
||||
<div class="form-group">
|
||||
<label for="email">Email</label>
|
||||
<input type="text" id="email" name="email" placeholder="Enter your email">
|
||||
<br/>
|
||||
<label for="password">PW</label>
|
||||
<input type="text" id="password" name="password" placeholder="Enter your password">
|
||||
<br/>
|
||||
<label for="name">Name</label>
|
||||
<input type="text" id="name" name="name" placeholder="Enter your name">
|
||||
</div>
|
||||
<button type="submit">Sign Up</button>
|
||||
</form>
|
||||
</div>
|
||||
<a href="/">Home</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,24 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<body>
|
||||
<div class="container">
|
||||
<div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>User List</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="user : ${userList}">
|
||||
<td th:text="${user.id}"></td>
|
||||
<td th:text="${user.name}"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<a href="/">Home</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
118
src/test/java/demo/api/auth/service/AuthServiceTest.java
Normal file
118
src/test/java/demo/api/auth/service/AuthServiceTest.java
Normal file
@@ -0,0 +1,118 @@
|
||||
package demo.api.auth.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import demo.api.auth.AuthService;
|
||||
import demo.api.auth.dtos.SignInReq;
|
||||
import demo.api.auth.dtos.SignUpReq;
|
||||
import demo.api.auth.dtos.SignUpRes;
|
||||
import demo.api.exception.UserNotFoundException;
|
||||
import demo.api.jwt.dtos.RegenerateTokenDto;
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.user.UserService;
|
||||
import demo.api.user.domain.User;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@DisplayName("Auth Service Test")
|
||||
class AuthServiceTest {
|
||||
private static final String EMAIL = "test@email.com";
|
||||
private static final String PASSWORD = "12345";
|
||||
private static final String NAME = "김정호";
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 회원가입")
|
||||
void signUp() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
|
||||
// when
|
||||
SignUpRes signUpRes = authService.signUp(user);
|
||||
|
||||
// then
|
||||
assertThat(signUpRes.isOk()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 로그인")
|
||||
void signIn() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
authService.signUp(user);
|
||||
|
||||
// when
|
||||
ResponseEntity<TokenDto> response = authService.signIn(createSignInRequest());
|
||||
|
||||
// then
|
||||
assertThat(response.getBody().getAccess_token()).isNotEmpty();
|
||||
assertThat(response.getBody().getRefresh_token()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("비밀번호는 암호화되어야 한다.")
|
||||
void hashPassword() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
|
||||
// when
|
||||
authService.signUp(user);
|
||||
|
||||
// then
|
||||
User createdUser = userService.findByEmail(EMAIL)
|
||||
.orElseThrow(UserNotFoundException::new);
|
||||
System.out.println("newUser pw = " + createdUser.getPassword());
|
||||
|
||||
assertThat(createdUser.getPassword()).isNotEqualTo(PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("토큰 재발행")
|
||||
void regenerateToken() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
authService.signUp(user);
|
||||
|
||||
// when
|
||||
ResponseEntity<TokenDto> response = authService.signIn(createSignInRequest());
|
||||
String prevAccessToken = response.getBody().getAccess_token();
|
||||
|
||||
RegenerateTokenDto regenerateTokenDto = new RegenerateTokenDto(
|
||||
response.getBody().getRefresh_token()
|
||||
);
|
||||
|
||||
ResponseEntity<TokenDto> regeneratedToken = authService.regenerateToken(regenerateTokenDto);
|
||||
|
||||
// then
|
||||
assertThat(regeneratedToken.getBody().getAccess_token()).isNotEqualTo(prevAccessToken);
|
||||
}
|
||||
|
||||
private SignUpReq createSignUpRequest() {
|
||||
return SignUpReq.builder()
|
||||
.email(EMAIL)
|
||||
.password(PASSWORD)
|
||||
.name(NAME)
|
||||
.build();
|
||||
}
|
||||
|
||||
private SignInReq createSignInRequest() {
|
||||
return SignInReq.builder()
|
||||
.email(EMAIL)
|
||||
.password(PASSWORD)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,20 @@
|
||||
package demo.api.user.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.InstanceOfAssertFactories.completableFuture;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import demo.api.AppConfig;
|
||||
import demo.api.auth.AuthService;
|
||||
import demo.api.auth.dtos.SignUpRes;
|
||||
import demo.api.user.UserService;
|
||||
import demo.api.user.UserServiceImpl;
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import demo.api.user.repository.UserRepository;
|
||||
import demo.api.auth.dtos.SignUpReq;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -31,70 +25,22 @@ class UserServiceTest {
|
||||
private static final String EMAIL = "test@email.com";
|
||||
private static final String PASSWORD = "12345";
|
||||
private static final String NAME = "김정호";
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder bCryptPasswordEncoder;
|
||||
|
||||
@BeforeEach
|
||||
public void beforeEach() {
|
||||
AppConfig appConfig = new AppConfig(userRepository, bCryptPasswordEncoder);
|
||||
userService = appConfig.userService();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 회원가입")
|
||||
void signUp() throws Exception {
|
||||
// given
|
||||
UserSignUpRequest user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
|
||||
// when
|
||||
User newUser = userService.signUp(user);
|
||||
|
||||
// then
|
||||
System.out.println("newUser = " + newUser.toString());
|
||||
assertThat(newUser.getEmail()).isEqualTo(EMAIL);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("비밀번호는 암호화되어야 한다.")
|
||||
void hashPassword() throws Exception {
|
||||
// given
|
||||
UserSignUpRequest user = createSignUpRequest();
|
||||
|
||||
// when
|
||||
User newUser = userService.signUp(user);
|
||||
|
||||
// then
|
||||
System.out.println("newUser pw = " + newUser.getPassword());
|
||||
assertThat(newUser.getPassword()).isNotEqualTo(PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 로그인")
|
||||
void signIn() throws Exception {
|
||||
// given
|
||||
UserSignUpRequest user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
User newUser = userService.signUp(user);
|
||||
|
||||
// when
|
||||
Boolean flag = newUser.checkPassword(PASSWORD, bCryptPasswordEncoder);
|
||||
System.out.println("flag = " + flag);
|
||||
|
||||
// then
|
||||
}
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
@Test
|
||||
@DisplayName("모든 유저 리스트를 반환")
|
||||
void findAll() throws Exception {
|
||||
void findAll() {
|
||||
// given
|
||||
List<User> prevUserList = userService.findAll();
|
||||
int prevLen = prevUserList.size();
|
||||
UserSignUpRequest user1 = createSignUpRequest();
|
||||
userService.signUp(user1);
|
||||
SignUpReq user1 = createSignUpRequest();
|
||||
authService.signUp(user1);
|
||||
|
||||
// when
|
||||
List<User> userList = userService.findAll();
|
||||
@@ -105,10 +51,10 @@ class UserServiceTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("이메일로 유저 찾기")
|
||||
void findByEmail() throws Exception {
|
||||
void findByEmail() {
|
||||
// given
|
||||
UserSignUpRequest user1 = createSignUpRequest();
|
||||
userService.signUp(user1);
|
||||
SignUpReq user1 = createSignUpRequest();
|
||||
authService.signUp(user1);
|
||||
|
||||
// when
|
||||
Optional<User> byEmail = userService.findByEmail(EMAIL);
|
||||
@@ -121,8 +67,8 @@ class UserServiceTest {
|
||||
void updateUser() {
|
||||
}
|
||||
|
||||
private UserSignUpRequest createSignUpRequest() {
|
||||
return UserSignUpRequest.builder()
|
||||
private SignUpReq createSignUpRequest() {
|
||||
return SignUpReq.builder()
|
||||
.email(EMAIL)
|
||||
.password(PASSWORD)
|
||||
.name(NAME)
|
||||
|
||||
Reference in New Issue
Block a user