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

[refactor] : jwt 발급, Kakao API 연동 #8

Merged
merged 8 commits into from
Jul 19, 2022
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
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

runtimeOnly 'com.h2database:h2'
// implementation 'mysql:mysql-connector-java'
implementation 'mysql:mysql-connector-java'

implementation 'io.jsonwebtoken:jjwt:0.9.0'
implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16'
Expand All @@ -50,7 +51,6 @@ dependencies {
implementation 'org.jcodec:jcodec-javase:0.2.3'

implementation 'org.springframework.boot:spring-boot-starter-websocket'
implementation 'org.springframework.boot:spring-boot-starter-security'
// providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@SpringBootApplication
//@ServletComponentScan
public class HometoogetherApplication {

Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,61 +1,84 @@
package hometoogether.hometoogether.config.jwt;

import hometoogether.hometoogether.domain.user.domain.UserPrincipal;
import hometoogether.hometoogether.domain.user.domain.User;
import hometoogether.hometoogether.domain.user.repository.UserRepository;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class JwtTokenProvider {

private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);

@Value("${app.jwtSecret}")
private String jwtSecret;

@Value("${app.jwtExpirationInMs}")
private int jwtExpirationInMs;
private String secretKey;
private long accessTokenValidTime = 1000L * 60 * 60;
private long refreshTokenValidTime = 1000L * 60 * 60 * 24;

public String generateToken(Authentication authentication) {

UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
private final UserRepository userRepository;

public String generateToken(Long userId) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

logger.debug("user : " + userPrincipal.getUsername(), userPrincipal.getId());
String jwt = Jwts.builder().setSubject(Long.toString(userPrincipal.getId())).setIssuedAt(new Date())
.setExpiration(expiryDate).signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
logger.debug("jwt : " + jwt);
return jwt;
return Jwts.builder()
.setIssuedAt(now) // 토큰 발급시간
.setExpiration(new Date(System.currentTimeMillis() + accessTokenValidTime)) // 토큰 유효시간
.claim("userId", userId) // 토큰에 담을 데이터
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes()) // secretKey를 사용하여 해싱 암호화 알고리즘 처리
.compact(); // 직렬화, 문자열로 변경
}

public Long getUserIdFromJWT(String token) {
Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
public String createRefreshToken() {
Date now = new Date();
return Jwts.builder()
.setIssuedAt(now) // 토큰 발급시간
.setExpiration(new Date(System.currentTimeMillis() + refreshTokenValidTime)) // 토큰 유효시간
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes()) // secretKey를 사용하여 해싱 암호화 알고리즘 처리
.compact(); // 직렬화, 문자열로 변경
}

return Long.parseLong(claims.getSubject());
public boolean isValid(String token) {
try {
Jwts.parser().setSigningKey(secretKey.getBytes()).parseClaimsJws(token);
return true;
} catch (Exception e) {
throw new RuntimeException("토큰이 유효하지 않습니다.");
}
}

public boolean validateToken(String authToken) {
public boolean isValidExceptExp(String token) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey.getBytes()).parseClaimsJws(token);
return claims.getBody().getExpiration().before(new Date());
} catch (ExpiredJwtException e) {
return true;
} catch (SignatureException ex) {
logger.error("Invalid JWT signature");
} catch (MalformedJwtException ex) {
logger.error("Invalid JWT token");
} catch (ExpiredJwtException ex) {
logger.error("Expired JWT token");
} catch (UnsupportedJwtException ex) {
logger.error("Unsupported JWT token");
} catch (IllegalArgumentException ex) {
logger.error("JWT claims string is empty.");
} catch (Exception e) {
return false;
}
return false;
}

public Long getTokenInfo() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String jwt = request.getHeader("Authorization");
Jws<Claims> claims = null;
try {
claims = Jwts.parser().setSigningKey(secretKey.getBytes()).parseClaimsJws(jwt); // secretKey를 사용하여 복호화
} catch (Exception e) {
throw new RuntimeException("토큰 정보를 불러올 수 없습니다.");
}
Object userId = claims.getBody().get("userId");
return Long.valueOf(userId.toString());
}

public User getUserFromJwt() {
Long userId = this.getTokenInfo();
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("존재하지 않는 유저입니다."));
return user;
}
}

This file was deleted.

Loading