From 1eb43f4296c0a296b9ae43469a95b16e50c7fff3 Mon Sep 17 00:00:00 2001 From: Eungi Jeong Date: Thu, 11 May 2023 20:06:09 +0900 Subject: [PATCH 1/2] =?UTF-8?q?[Feat]=20JWT=20Refresh=20Token=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9=20#25?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit πŸ“‹ 이슈 λ‚΄μš© JWT Refresh Token κΈ°λŠ₯을 μ μš©ν•©λ‹ˆλ‹€. βœ… 체크리슀트 - user.User -> UserDetails implements λ°›μŒ πŸ“š 레퍼런슀 --- .../favor/auth/CustomUserDetailService.java | 6 ++-- .../favor/favor/auth/JwtTokenProvider.java | 8 ++--- .../configuration/SecurityConfiguration.java | 5 ++- .../main/java/com/favor/favor/user/User.java | 19 ++++++++-- .../com/favor/favor/user/UserService.java | 36 +++++++++---------- favor/src/main/resources/application.yml | 2 +- 6 files changed, 45 insertions(+), 31 deletions(-) diff --git a/favor/src/main/java/com/favor/favor/auth/CustomUserDetailService.java b/favor/src/main/java/com/favor/favor/auth/CustomUserDetailService.java index 29e9e97..2d2cb49 100644 --- a/favor/src/main/java/com/favor/favor/auth/CustomUserDetailService.java +++ b/favor/src/main/java/com/favor/favor/auth/CustomUserDetailService.java @@ -13,12 +13,12 @@ @RequiredArgsConstructor @Slf4j public class CustomUserDetailService implements UserDetailsService { - private final UserRepository memberRepository; + private final UserRepository userRepository; @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { - User foundUser = memberRepository.findById(Long.parseLong(username)) + User foundUser = userRepository.findByEmail(email) .orElseThrow(() -> new UsernameNotFoundException("μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")); return (UserDetails) foundUser; } diff --git a/favor/src/main/java/com/favor/favor/auth/JwtTokenProvider.java b/favor/src/main/java/com/favor/favor/auth/JwtTokenProvider.java index e256dcd..ea2fa61 100644 --- a/favor/src/main/java/com/favor/favor/auth/JwtTokenProvider.java +++ b/favor/src/main/java/com/favor/favor/auth/JwtTokenProvider.java @@ -38,8 +38,8 @@ protected void init() { } // JWT 토큰 생성 - public String createToken(String userId, Role role) { - Claims claims = Jwts.claims().setSubject(userId); // JWT payload 에 μ €μž₯λ˜λŠ” μ •λ³΄λ‹¨μœ„ + public String createToken(String email, Role role) { + Claims claims = Jwts.claims().setSubject(email); // JWT payload 에 μ €μž₯λ˜λŠ” μ •λ³΄λ‹¨μœ„ claims.put("roles", role); // μ •λ³΄λŠ” key / value 쌍으둜 μ €μž₯λœλ‹€. Date now = new Date(); @@ -55,13 +55,13 @@ public String createToken(String userId, Role role) { // JWT ν† ν°μ—μ„œ 인증 정보 쑰회 public Authentication getAuthentication(String token) { - UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUsername(token)); + UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserEmail(token)); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } // ν† ν°μ—μ„œ νšŒμ› 정보 μΆ”μΆœ - public String getUsername(String token) { + public String getUserEmail(String token) { String info = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); return info; } diff --git a/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java b/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java index 050363e..14f6546 100644 --- a/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java +++ b/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java @@ -47,10 +47,9 @@ protected void configure(HttpSecurity http) throws Exception { .and() .authorizeRequests() - .antMatchers("/email/**", "/verifyCode/**").permitAll() + .antMatchers("/verifyCode/**").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") - .antMatchers("/user/**").hasRole("USER") - .antMatchers("/calendar/**").hasRole("USER") + .and() .exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()) diff --git a/favor/src/main/java/com/favor/favor/user/User.java b/favor/src/main/java/com/favor/favor/user/User.java index e3f7f7c..90865b6 100644 --- a/favor/src/main/java/com/favor/favor/user/User.java +++ b/favor/src/main/java/com/favor/favor/user/User.java @@ -9,10 +9,13 @@ import com.favor.favor.gift.Gift; import com.favor.favor.reminder.Reminder; import lombok.*; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import javax.transaction.Transactional; import java.util.ArrayList; +import java.util.Collection; import java.util.List; @Entity @@ -21,7 +24,7 @@ @AllArgsConstructor @Builder @Transactional -public class User extends TimeStamped { +public class User extends TimeStamped implements UserDetails { @Id @@ -75,6 +78,18 @@ public void setFavorList(List favorList) { @OneToMany(mappedBy = "user", orphanRemoval = true) private List friendList = new ArrayList<>(); - private Role role; + + @Override + public Collection getAuthorities() {return null;} + @Override + public String getUsername() {return name;} + @Override + public boolean isAccountNonExpired() {return false;} + @Override + public boolean isAccountNonLocked() {return false;} + @Override + public boolean isCredentialsNonExpired() {return false;} + @Override + public boolean isEnabled() {return false;} } diff --git a/favor/src/main/java/com/favor/favor/user/UserService.java b/favor/src/main/java/com/favor/favor/user/UserService.java index 88beb24..af0dab2 100644 --- a/favor/src/main/java/com/favor/favor/user/UserService.java +++ b/favor/src/main/java/com/favor/favor/user/UserService.java @@ -45,26 +45,26 @@ public class UserService { @Transactional public User signUp(SignDto signDto) { - final String CHARACTERS = "_abcdefghijklmnopqrstuvwxyz0123456789"; - Random random = new Random(); - StringBuilder tempUserId = new StringBuilder(20); - - boolean flag = true; - while(flag){ - for (int i = 0; i < 20; i++) { - tempUserId.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length()))); - } - if(userRepository.existsByUserId(tempUserId.toString())){ - tempUserId.delete(0, tempUserId.length()); - } - else { - flag =false; - } - } +// final String CHARACTERS = "_abcdefghijklmnopqrstuvwxyz0123456789"; +// Random random = new Random(); +// StringBuilder tempUserId = new StringBuilder(20); + +// boolean flag = true; +// while(flag){ +// for (int i = 0; i < 20; i++) { +// tempUserId.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length()))); +// } +// if(userRepository.existsByUserId(tempUserId.toString())){ +// tempUserId.delete(0, tempUserId.length()); +// } +// else { +// flag =false; +// } +// } User user = User.builder() .name("Favor00") - .userId(tempUserId.toString()) + .userId("Favor00") .email(signDto.getEmail()) .password(passwordEncoder.encode(signDto.getPassword())) .role(Role.USER) @@ -95,7 +95,7 @@ public SignInResponseDto signIn(SignDto dto){ isRightPassword(password, user); - String token = jwtTokenProvider.createToken(user.getUserId(), user.getRole()); + String token = jwtTokenProvider.createToken(user.getEmail(), user.getRole()); return new SignInResponseDto(token); } diff --git a/favor/src/main/resources/application.yml b/favor/src/main/resources/application.yml index fee9e9d..ad46adc 100644 --- a/favor/src/main/resources/application.yml +++ b/favor/src/main/resources/application.yml @@ -9,7 +9,7 @@ spring: jpa: show-sql: 'true' hibernate: - ddl-auto: update + ddl-auto: create open-in-view: 'false' properties: hibernate: From ec3f0253d67ffa5b7293652750a8a61a547313d7 Mon Sep 17 00:00:00 2001 From: Eungi Jeong Date: Fri, 12 May 2023 16:37:50 +0900 Subject: [PATCH 2/2] =?UTF-8?q?[Feat]=20JWT=20Access=20Token=20=EA=B6=8C?= =?UTF-8?q?=ED=95=9C=20=EC=84=A4=EC=A0=95=20#27?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Swagger UI 첫 νŽ˜μ΄μ§€, νšŒμ›κ°€μž…/ν”„λ‘œν•„μƒμ„±/둜그인 νŽ˜μ΄μ§€λŠ” λͺ¨λ‘ μ ‘κ·Ό κ°€λŠ₯ν•©λ‹ˆλ‹€. - κ·Έ μ™Έ νŽ˜μ΄μ§€λŠ” 인가 λ°›μ•„μ•Ό μ ‘κ·Ό κ°€λŠ₯ν•©λ‹ˆλ‹€. - ν•΄κ²°ν•΄μ•Ό ν•  점 : UNAUTHORIZED_USER 일 λ•Œ CustomResponseDto μ„€μ • ν•œλŒ€λ‘œ λ°˜ν™˜λ˜μ§€ μ•Šμ•„μ„œ 이 λΆ€λΆ„ 고쳐야 ν•©λ‹ˆλ‹€. --- .../favor/configuration/SecurityConfiguration.java | 10 ++++++++-- .../java/com/favor/favor/user/UserResponseDto.java | 11 +++++++++++ favor/src/main/resources/application.yml | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java b/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java index 14f6546..650dcf9 100644 --- a/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java +++ b/favor/src/main/java/com/favor/favor/configuration/SecurityConfiguration.java @@ -47,8 +47,14 @@ protected void configure(HttpSecurity http) throws Exception { .and() .authorizeRequests() - .antMatchers("/verifyCode/**").permitAll() - .antMatchers("/admin/**").hasRole("ADMIN") + .antMatchers("/api/v1/auth/**","/", + "/v2/api-docs", "/swagger-resources/**", "/swagger-ui/index.html", "/swagger-ui.html","/webjars/**", "/swagger/**", // swagger + "/h2-console/**", + "/favicon.ico", + "/users/sign-in", + "/users/sign-up", + "/users/profile/**").permitAll() + .anyRequest().authenticated() .and() diff --git a/favor/src/main/java/com/favor/favor/user/UserResponseDto.java b/favor/src/main/java/com/favor/favor/user/UserResponseDto.java index 405d6ca..a2c6285 100644 --- a/favor/src/main/java/com/favor/favor/user/UserResponseDto.java +++ b/favor/src/main/java/com/favor/favor/user/UserResponseDto.java @@ -6,6 +6,7 @@ import com.favor.favor.friend.FriendResponseDto; import com.favor.favor.gift.GiftResponseDto; import com.favor.favor.reminder.ReminderResponseDto; +import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -16,15 +17,25 @@ @AllArgsConstructor @Builder public class UserResponseDto { + @ApiModelProperty(value = "1") private final Long userNo; + @ApiModelProperty(value = "favor@gmail.com") private String email; + @ApiModelProperty(value = "νŽ˜μ΄λ²„") private String name; + @ApiModelProperty(value = "favor") private String userid; + @ApiModelProperty(value = "USER") private Role role; + @ApiModelProperty(value = "") private List reminderList; + @ApiModelProperty(value = "") private List giftList; + @ApiModelProperty(value = "") private List friendList; + @ApiModelProperty(value = "") private List anniversaryList; + @ApiModelProperty(value = "") private List favorList; @Builder diff --git a/favor/src/main/resources/application.yml b/favor/src/main/resources/application.yml index ad46adc..fee9e9d 100644 --- a/favor/src/main/resources/application.yml +++ b/favor/src/main/resources/application.yml @@ -9,7 +9,7 @@ spring: jpa: show-sql: 'true' hibernate: - ddl-auto: create + ddl-auto: update open-in-view: 'false' properties: hibernate: