Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] JWT Access Token 적용 #25 #27

Merged
merged 2 commits into from
May 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,15 @@ protected void configure(HttpSecurity http) throws Exception {

.and()
.authorizeRequests()
.antMatchers("/email/**", "/verifyCode/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/calendar/**").hasRole("USER")
.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()
.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler())
Expand Down
19 changes: 17 additions & 2 deletions favor/src/main/java/com/favor/favor/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,7 +24,7 @@
@AllArgsConstructor
@Builder
@Transactional
public class User extends TimeStamped {
public class User extends TimeStamped implements UserDetails {

@Id

Expand Down Expand Up @@ -75,6 +78,18 @@ public void setFavorList(List<Favor> favorList) {
@OneToMany(mappedBy = "user", orphanRemoval = true)
private List<Friend> friendList = new ArrayList<>();


private Role role;

@Override
public Collection<? extends GrantedAuthority> 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;}
}
11 changes: 11 additions & 0 deletions favor/src/main/java/com/favor/favor/user/UserResponseDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -16,15 +17,25 @@
@AllArgsConstructor
@Builder
public class UserResponseDto {
@ApiModelProperty(value = "1")
private final Long userNo;
@ApiModelProperty(value = "[email protected]")
private String email;
@ApiModelProperty(value = "페이버")
private String name;
@ApiModelProperty(value = "favor")
private String userid;
@ApiModelProperty(value = "USER")
private Role role;
@ApiModelProperty(value = "")
private List<ReminderResponseDto> reminderList;
@ApiModelProperty(value = "")
private List<GiftResponseDto> giftList;
@ApiModelProperty(value = "")
private List<FriendResponseDto> friendList;
@ApiModelProperty(value = "")
private List<AnniversaryResponseDto> anniversaryList;
@ApiModelProperty(value = "")
private List<Favor> favorList;

@Builder
Expand Down
36 changes: 18 additions & 18 deletions favor/src/main/java/com/favor/favor/user/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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);
}
Expand Down