Compare commits
12 Commits
security/5
...
jwt
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ac6e75311 | ||
|
|
fc26a2a1cc | ||
|
|
02228ed615 | ||
|
|
fe53bc9ef0 | ||
|
|
cb9d35afd9 | ||
|
|
1eee369124 | ||
|
|
b033747ec3 | ||
|
|
baa59f24a5 | ||
|
|
c5827d07fa | ||
|
|
f307710223 | ||
|
|
c51cf8b525 | ||
|
|
26b0dad1ab |
32
README.md
32
README.md
@@ -2,5 +2,35 @@
|
||||
|
||||
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
|
||||
|
||||
- [ ] Implement Refresh Token
|
||||
- [ ] Control Response Entity
|
||||
|
||||
### Done ✓
|
||||
|
||||
- [x] Post on Blog
|
||||
@@ -49,13 +49,17 @@ dependencies {
|
||||
/*
|
||||
Security
|
||||
*/
|
||||
// implementation 'org.springframework.boot:spring-boot-starter-security:2.6.7'
|
||||
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'
|
||||
}
|
||||
|
||||
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();
|
||||
//// }
|
||||
//}
|
||||
|
||||
63
src/main/java/demo/api/auth/AuthController.java
Normal file
63
src/main/java/demo/api/auth/AuthController.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package demo.api.auth;
|
||||
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignInRequest;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import java.util.Objects;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
private final AuthService authService;
|
||||
|
||||
@GetMapping("/signUp")
|
||||
public String signUp() {
|
||||
return "user/signUp";
|
||||
}
|
||||
|
||||
@PostMapping("/signUp")
|
||||
public String signUp(@Validated UserSignUpRequest signUpReq) throws Exception {
|
||||
User user = authService.signUp(signUpReq);
|
||||
|
||||
if(!Objects.isNull(user)) {
|
||||
return "redirect:/user/signIn";
|
||||
}
|
||||
|
||||
return "redirect:/user/signUp";
|
||||
}
|
||||
|
||||
@GetMapping("/signIn")
|
||||
public String signIn(@RequestParam(value = "fail", required = false) String flag, Model model) {
|
||||
model.addAttribute("failed", flag != null);
|
||||
|
||||
return "user/signIn";
|
||||
}
|
||||
|
||||
@PostMapping("/signIn")
|
||||
public String signIn(@Validated UserSignInRequest signInReq, HttpServletResponse res) {
|
||||
ResponseEntity<TokenDto> tokenDtoResponseEntity = authService.signIn(signInReq);
|
||||
Cookie cookie = new Cookie(
|
||||
"access_token",
|
||||
tokenDtoResponseEntity.getBody().getAccess_token()
|
||||
);
|
||||
|
||||
cookie.setPath("/");
|
||||
cookie.setMaxAge(Integer.MAX_VALUE);
|
||||
|
||||
res.addCookie(cookie);
|
||||
return "redirect:/user/profile";
|
||||
}
|
||||
}
|
||||
23
src/main/java/demo/api/auth/AuthService.java
Normal file
23
src/main/java/demo/api/auth/AuthService.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package demo.api.auth;
|
||||
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignInRequest;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
public interface AuthService {
|
||||
/**
|
||||
* 유저의 정보로 회원가입
|
||||
* @param signUpReq 가입할 유저의 정보 Dto
|
||||
* @return 가입된 유저 정보
|
||||
*/
|
||||
User signUp(UserSignUpRequest signUpReq) throws Exception;
|
||||
|
||||
/**
|
||||
* 유저 정보로 로그인
|
||||
* @param signInReq 유저의 이메일과 비밀번호
|
||||
* @return json web token
|
||||
*/
|
||||
ResponseEntity<TokenDto> signIn(UserSignInRequest signInReq);
|
||||
}
|
||||
64
src/main/java/demo/api/auth/AuthServiceImpl.java
Normal file
64
src/main/java/demo/api/auth/AuthServiceImpl.java
Normal file
@@ -0,0 +1,64 @@
|
||||
package demo.api.auth;
|
||||
|
||||
import demo.api.exception.CustomException;
|
||||
import demo.api.jwt.JwtTokenFilter;
|
||||
import demo.api.jwt.JwtTokenProvider;
|
||||
import demo.api.jwt.dtos.TokenDto;
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.dtos.UserSignInRequest;
|
||||
import demo.api.user.dtos.UserSignUpRequest;
|
||||
import demo.api.user.repository.UserRepository;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public User signUp(UserSignUpRequest signUpReq) throws Exception {
|
||||
System.out.println("signUpReq = " + signUpReq.toString());
|
||||
|
||||
if(userRepository.existsByEmail(signUpReq.getEmail())) {
|
||||
throw new Exception("Your Mail already Exist.");
|
||||
}
|
||||
User newUser = signUpReq.toUserEntity();
|
||||
newUser.hashPassword(bCryptPasswordEncoder);
|
||||
return userRepository.save(newUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<TokenDto> signIn(UserSignInRequest signInReq) {
|
||||
try {
|
||||
Authentication authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
signInReq.getEmail(),
|
||||
signInReq.getPassword()
|
||||
)
|
||||
);
|
||||
TokenDto tokenDto = new TokenDto(jwtTokenProvider.generateToken(authentication));
|
||||
|
||||
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.UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
package demo.api.config;
|
||||
|
||||
import demo.api.user.repository.UserRepository;
|
||||
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;
|
||||
|
||||
@@ -17,30 +18,55 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
return new UserDetailsServiceImpl();
|
||||
}
|
||||
// 추가된 jwt 관련 친구들을 security config에 추가
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(
|
||||
AuthenticationConfiguration authenticationConfiguration
|
||||
) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@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*",
|
||||
"/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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,25 +3,22 @@ package demo.api.config;
|
||||
import demo.api.user.domain.User;
|
||||
import demo.api.user.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
|
||||
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||
@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(UserNotFoundException::new);
|
||||
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
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.validateToken(token)) {
|
||||
Authentication auth = jwtTokenProvider.getAuthentication(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth); // 정상 토큰이면 SecurityContext에 저장
|
||||
}
|
||||
} catch (CustomException e) {
|
||||
SecurityContextHolder.clearContext();
|
||||
response.sendError(e.getHttpStatus().value(), e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
91
src/main/java/demo/api/jwt/JwtTokenProvider.java
Normal file
91
src/main/java/demo/api/jwt/JwtTokenProvider.java
Normal file
@@ -0,0 +1,91 @@
|
||||
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.secret-key}")
|
||||
private String secret_key;
|
||||
|
||||
@Value("${jwt.token.expire-length}")
|
||||
private long expire_time;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
/**
|
||||
* 적절한 설정을 통해 토큰을 생성하여 반환
|
||||
* @param authentication
|
||||
* @return
|
||||
*/
|
||||
public String generateToken(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() + expire_time);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiresIn)
|
||||
.signWith(SignatureAlgorithm.HS256, secret_key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰으로부터 클레임을 만들고, 이를 통해 User 객체를 생성하여 Authentication 객체를 반환
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public Authentication getAuthentication(String token) {
|
||||
String username = Jwts.parser().setSigningKey(secret_key).parseClaimsJws(token).getBody().getSubject();
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰을 검증
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public boolean validateToken(String token) {
|
||||
try {
|
||||
Jwts.parser().setSigningKey(secret_key).parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
// MalformedJwtException | ExpiredJwtException | IllegalArgumentException
|
||||
throw new CustomException("Error on Token", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/main/java/demo/api/jwt/dtos/TokenDto.java
Normal file
10
src/main/java/demo/api/jwt/dtos/TokenDto.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package demo.api.jwt.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public class TokenDto {
|
||||
private String access_token;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ 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.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@@ -24,32 +25,9 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
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());
|
||||
System.out.println("userDetails = " + userDetails);
|
||||
if (userDetails != null) {
|
||||
User userDetail = userService.findByEmail(userDetails.getUsername())
|
||||
.orElseThrow(() -> new UserNotFoundException());
|
||||
@@ -60,10 +38,18 @@ public class UserController {
|
||||
return "user/profile";
|
||||
}
|
||||
|
||||
@GetMapping("/user/userList")
|
||||
@GetMapping("/profile/{username}")
|
||||
public String userProfile(Model model, @PathVariable String username) {
|
||||
User user = userService.findByName(username)
|
||||
.orElseThrow(() -> new UserNotFoundException());
|
||||
model.addAttribute("userDetail", user);
|
||||
|
||||
return "user/profile";
|
||||
}
|
||||
|
||||
@GetMapping("/userList")
|
||||
public String showUserList(Model model) {
|
||||
List<User> userList = userService.findAll();
|
||||
|
||||
model.addAttribute("userList", userList);
|
||||
|
||||
return "user/userList";
|
||||
|
||||
@@ -6,13 +6,6 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserService {
|
||||
/**
|
||||
* 유저의 정보로 회원가입
|
||||
* @param signUpReq 가입할 유저의 정보 Dto
|
||||
* @return 가입된 유저 정보
|
||||
*/
|
||||
User signUp(UserSignUpRequest signUpReq) throws Exception;
|
||||
|
||||
/**
|
||||
* 모든 유저 리스트를 반환
|
||||
* @return 유저 리스트
|
||||
@@ -26,6 +19,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,33 @@ public class UserServiceImpl implements UserService {
|
||||
return userRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByName(String name) {
|
||||
return userRepository.findByName(name);
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public Optional<User> getMyInfo() {
|
||||
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
// String username = null;
|
||||
//
|
||||
// if (authentication == null) {
|
||||
// log.debug("Security Context에 인증 정보가 없습니다.");
|
||||
// return Optional.empty();
|
||||
// }
|
||||
//
|
||||
// if (authentication.getPrincipal() instanceof UserDetails) {
|
||||
// UserDetails springSecurityUserInfo = (UserDetails) authentication.getPrincipal();
|
||||
// username = springSecurityUserInfo.getUsername();
|
||||
// } else if (authentication.getPrincipal() instanceof String) {
|
||||
// username = (String) authentication.getPrincipal();
|
||||
// }
|
||||
//
|
||||
// return Optional.ofNullable(userRepository.findByName(username).orElse(null));
|
||||
// }
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
|
||||
26
src/main/java/demo/api/user/dtos/UserSignInRequest.java
Normal file
26
src/main/java/demo/api/user/dtos/UserSignInRequest.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package demo.api.user.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 UserSignInRequest {
|
||||
@NotEmpty(message = "Please enter your Email")
|
||||
@Email
|
||||
private String email;
|
||||
@NotEmpty(message = "Please enter your Password")
|
||||
private String password;
|
||||
|
||||
@Builder
|
||||
public UserSignInRequest(String email, String password) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,9 @@ spring:
|
||||
jpa:
|
||||
show-sql: true
|
||||
hibernate:
|
||||
ddl-auto: none
|
||||
format_sql: true
|
||||
ddl-auto: none
|
||||
jwt:
|
||||
token:
|
||||
secret-key: aG91Mjctc2ltcGxlLXNwcmluZy1ib290LWFwaS1qd3QK
|
||||
expire-length: 300000
|
||||
@@ -6,8 +6,8 @@
|
||||
<h1>Test Page</h1>
|
||||
<p>User</p>
|
||||
<p>
|
||||
<a href="/user/signUp">Sign Up</a>
|
||||
<a href="/user/signIn">Sign In</a>
|
||||
<a href="/auth/signUp">Sign Up</a>
|
||||
<a href="/auth/signIn">Sign In</a>
|
||||
<br>
|
||||
<a href="/user/profile">Profile</a>
|
||||
</p>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<h2>로그인</h2>
|
||||
</div>
|
||||
<h3 th:if="${failed}">Fail to login</h3>
|
||||
<form action="/user/signInProc" method="post">
|
||||
<form action="/auth/signIn" method="post">
|
||||
<div class="form-group">
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" name="email" placeholder="Enter your email">
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<div>
|
||||
<h2>회원가입</h2>
|
||||
</div>
|
||||
<form action="/user/signUp" method="post">
|
||||
<form action="/auth/signUp" method="post">
|
||||
<div class="form-group">
|
||||
<label for="email">Email</label>
|
||||
<input type="text" id="email" name="email" placeholder="Enter your email">
|
||||
|
||||
@@ -3,24 +3,17 @@ package demo.api.user.service;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import demo.api.AppConfig;
|
||||
import demo.api.auth.AuthService;
|
||||
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 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,17 +24,13 @@ 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();
|
||||
}
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 회원가입")
|
||||
@@ -51,7 +40,7 @@ class UserServiceTest {
|
||||
System.out.println("user = " + user.toString());
|
||||
|
||||
// when
|
||||
User newUser = userService.signUp(user);
|
||||
User newUser = authService.signUp(user);
|
||||
|
||||
// then
|
||||
System.out.println("newUser = " + newUser.toString());
|
||||
@@ -65,7 +54,7 @@ class UserServiceTest {
|
||||
UserSignUpRequest user = createSignUpRequest();
|
||||
|
||||
// when
|
||||
User newUser = userService.signUp(user);
|
||||
User newUser = authService.signUp(user);
|
||||
|
||||
// then
|
||||
System.out.println("newUser pw = " + newUser.getPassword());
|
||||
@@ -78,10 +67,10 @@ class UserServiceTest {
|
||||
// given
|
||||
UserSignUpRequest user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
User newUser = userService.signUp(user);
|
||||
User newUser = authService.signUp(user);
|
||||
|
||||
// when
|
||||
Boolean flag = newUser.checkPassword(PASSWORD, bCryptPasswordEncoder);
|
||||
boolean flag = newUser.checkPassword(PASSWORD, bCryptPasswordEncoder);
|
||||
System.out.println("flag = " + flag);
|
||||
|
||||
// then
|
||||
@@ -94,7 +83,7 @@ class UserServiceTest {
|
||||
List<User> prevUserList = userService.findAll();
|
||||
int prevLen = prevUserList.size();
|
||||
UserSignUpRequest user1 = createSignUpRequest();
|
||||
userService.signUp(user1);
|
||||
authService.signUp(user1);
|
||||
|
||||
// when
|
||||
List<User> userList = userService.findAll();
|
||||
@@ -108,7 +97,7 @@ class UserServiceTest {
|
||||
void findByEmail() throws Exception {
|
||||
// given
|
||||
UserSignUpRequest user1 = createSignUpRequest();
|
||||
userService.signUp(user1);
|
||||
authService.signUp(user1);
|
||||
|
||||
// when
|
||||
Optional<User> byEmail = userService.findByEmail(EMAIL);
|
||||
|
||||
Reference in New Issue
Block a user