Skip to content

Commit

Permalink
Merge pull request #8 from HealthMer/feat/#7-jwt_refactoring
Browse files Browse the repository at this point in the history
Feat/#7 jwt refactoring
  • Loading branch information
Dylan-yoon authored Nov 25, 2024
2 parents 2528372 + 958af5d commit 4ae500e
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// 인증 비활성화

@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

// 인증 비활성화
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // CSRF 비활성화
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll() // 모든 요청을 인증 없이 허용
);
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors() // CORS 설정을 Spring Security에서도 허용
.and()
.csrf(csrf -> csrf.disable()) // CSRF 비활성화
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());

return http.build();
}
return http.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.minijean.healthmer.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

Expand All @@ -20,4 +21,19 @@ public void addInterceptors(InterceptorRegistry registry) {
.addPathPatterns("/api/v1/**") // 토큰 검증이 필요한 경로 설정
.excludePathPatterns("/api/v1/auth/login/email", "/api/v1/auth/register/email"); // 인증 관련 경로 제외 (로그인, 회원가입 등)
}

// CORS 전역 설정
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,13 @@

@RestController
@RequestMapping("/api/v1/auth")
@CrossOrigin("http://localhost:5173")
public class AuthController {

// @Autowired
private final AuthService authService;
private final JwtUtil jwtUtil;

public AuthController(AuthService authService, JwtUtil jwtUtil) {
public AuthController(AuthService authService) {
this.authService = authService;
this.jwtUtil = jwtUtil;
}

@PostMapping("/register/email")
Expand All @@ -47,39 +44,20 @@ public ResponseEntity<?> register(@RequestBody User user) {
}

// 로그인
// @PostMapping("/login/email")
// public ResponseEntity<?> login(@RequestBody User user) {
// HttpStatus status = null;
// Map<String, Object> result = new HashMap<>();
// String loginUserToken = authService.login(user);
//
// if (loginUserToken != null) {
// result.put("message", "Login Successfully");
// result.put("access-token", jwtUtil.createToken(loginUserToken));
// status = HttpStatus.ACCEPTED;
// } else {
// status = HttpStatus.INTERNAL_SERVER_ERROR;
// }
//
// ResponseEntity<?> entity = new ResponseEntity<>(result, status);
// return new ResponseEntity<>(result, status);
// }

@PostMapping("/login/email")
public ResponseEntity<?> login(@RequestBody User user) {
HttpStatus status;
Map<String, Object> result = new HashMap<>();
String loginUserToken = authService.login(user);
if (loginUserToken != null) {
// 로그인 성공 시 메시지와 토큰 추가
String token = jwtUtil.createToken(loginUserToken);
result.put("message", "Login Successfully");
result.put("access-token", token);
status = HttpStatus.ACCEPTED;
result.put("access_token", loginUserToken);

status = HttpStatus.ACCEPTED;
// ResponseEntity에 헤더 추가
return ResponseEntity.status(status)
.header("Authorization", "Bearer " + token)
.header("Authorization", "Bearer " + loginUserToken)
.body(result);
} else {
// 로그인 실패 시 처리
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

@RestController
@RequestMapping("/api/v1/timer")
@CrossOrigin("http://localhost:5173")
public class TimerController {

private final TimerService timerService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

// Bearer 이후의 토큰 추출
String token = authorizationHeader.substring(7);

// 토큰 유효성 검사 (예: JWT 검증)
if (!isValidToken(token)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
public class AuthServiceImpl implements AuthService {

private final AuthDao authDao;
private final JwtUtil jwtUtil;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
private final PasswordEncoder passwordEncoder;

public AuthServiceImpl(AuthDao authDao, JwtUtil jwtUtil, PasswordEncoder passwordEncoder) {
this.authDao = authDao;
Expand All @@ -26,16 +26,16 @@ public AuthServiceImpl(AuthDao authDao, JwtUtil jwtUtil, PasswordEncoder passwor
public boolean register(User user) {
User findUserForEmail = authDao.findByEmail(user.getEmail());
User findUserForNickname = authDao.findByNickname(user.getNickname());

if (findUserForEmail == null && findUserForNickname == null) {
user.setUserTypeId((byte) 2);
user.setSignUpRouteId((byte) 5);
user.setPassword(passwordEncoder.encode(user.getPassword()));

authDao.registUser(user);

User data = authDao.findByEmail(user.getEmail());

if (data == null) {
return false;
} else {
Expand All @@ -44,14 +44,17 @@ public boolean register(User user) {
}
return false;
}

@Override
public String login(User user) {
User findedUser = authDao.findByEmail(user.getEmail());
if (user == null || !passwordEncoder.matches(user.getPassword(), findedUser.getPassword())) {
throw new IllegalArgumentException("Invalid email or password");
}
return jwtUtil.createToken(findedUser.getEmail());
User findedUser = authDao.findByEmail(user.getEmail());
if (user == null || !passwordEncoder.matches(user.getPassword(), findedUser.getPassword())) {
throw new IllegalArgumentException("Invalid email or password");
}

String token = jwtUtil.createTokenBy(findedUser);

return token;
}

@Override
Expand Down
30 changes: 22 additions & 8 deletions HealthMer/src/main/java/com/minijean/healthmer/util/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import org.springframework.stereotype.Component;

import com.minijean.healthmer.model.dto.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
Expand All @@ -16,15 +18,27 @@
public class JwtUtil {
private String key = "SSAFY_NonMajor_JavaTrack_SecretKey";
private SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));

public String createToken(String name) {
Date exp = new Date(System.currentTimeMillis()+ 1000*60*60*6);
return Jwts.builder().header().add("typ", "JWT").and()
.claim("name", name).expiration(exp)
.signWith(secretKey).compact();

public String createTokenBy(User user) {
Date exp = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 6);
return Jwts.builder().header().add("typ", "JWT").and().claim("id", user.getId()).claim("email", user.getEmail())
.expiration(exp).signWith(secretKey).compact();
}

public Jws<Claims> vaildate(String token){

// public String createLoginToken(String name) {
// Date exp = new Date(System.currentTimeMillis()+ 1000*60*60*6);
// return Jwts.builder().header().add("typ", "JWT").and()
// .claim("name", name).expiration(exp)
// .signWith(secretKey).compact();
// }

public Jws<Claims> validate(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token);
}

public String extractUserId(String token) {
// getBody() 메서드가 deprecated된 경우 대안은 라이브러리의 최신 문서를 참조하여 새로운 API로 업데이트된 방식에 맞게 코드를 작성하는 것입니다. 하지만, 현재의 최신 JJWT 라이브러리에서는 위의 방식이 유효하고 권장되는 패턴입니다.
Claims claims = validate(token).getBody(); // 클레임을 추출하는 권장되는 방법 사용
return claims.get("id", String.class); // "id" 클레임에서 사용자 ID 추출
}
}

0 comments on commit 4ae500e

Please sign in to comment.