-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a937cba
commit af1454b
Showing
13 changed files
with
410 additions
and
49 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
src/main/java/com/example/digger/config/SecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,44 @@ | ||
package com.example.digger.config; | ||
|
||
import com.example.digger.jwt.JwtAuthenticationFilter; | ||
import com.example.digger.jwt.JwtTokenProvider; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
public class SecurityConfig { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
public SecurityConfig(JwtTokenProvider jwtTokenProvider) { | ||
this.jwtTokenProvider = jwtTokenProvider; | ||
} | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return new BCryptPasswordEncoder(); | ||
} | ||
|
||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
http | ||
.securityContext(securityContext -> securityContext.requireExplicitSave(false)) // 보안 컨텍스트 관리 | ||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // JWT는 Stateless | ||
.authorizeHttpRequests(auth -> auth | ||
.requestMatchers("/api/user/join", "/api/user/login", "/api/home").permitAll() // 인증 없이 접근 가능 | ||
.anyRequest().authenticated() // 나머지는 인증 필요 | ||
) | ||
.csrf(csrf -> csrf.disable()) // CSRF 비활성화 | ||
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); // JWT 필터 추가 | ||
|
||
return http.build(); | ||
} | ||
} |
46 changes: 46 additions & 0 deletions
46
src/main/java/com/example/digger/jwt/JwtAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package com.example.digger.jwt; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
import java.io.IOException; | ||
import java.util.Collections; | ||
|
||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) { | ||
this.jwtTokenProvider = jwtTokenProvider; | ||
} | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) | ||
throws ServletException, IOException { | ||
String token = getTokenFromRequest(request); | ||
|
||
// Request로부터 전달된 토큰에 대한 유효성 검사를 진행한 후, 유효한 토큰일 경우 토큰에 있는 정보를 바탕으로 Authentication을 생성한다. | ||
if (token != null && jwtTokenProvider.validateToken(token)) { | ||
String email = jwtTokenProvider.getEmailFromToken(token); | ||
Authentication authentication = new UsernamePasswordAuthenticationToken(email, null, Collections.emptyList()); | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
|
||
filterChain.doFilter(request, response); | ||
} | ||
|
||
private String getTokenFromRequest(HttpServletRequest request) { | ||
// Request의 Authorization 헤더 값을 가져와 거기에서 토큰 값을 추출한다. | ||
String bearerToken = request.getHeader("Authorization"); | ||
if (bearerToken != null && bearerToken.startsWith("Bearer ")) { | ||
return bearerToken.substring(7); | ||
} | ||
return null; | ||
} | ||
} |
64 changes: 64 additions & 0 deletions
64
src/main/java/com/example/digger/jwt/JwtTokenProvider.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package com.example.digger.jwt; | ||
|
||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.SignatureAlgorithm; | ||
import io.jsonwebtoken.security.Keys; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.nio.charset.StandardCharsets; | ||
import java.security.Key; | ||
import java.util.Date; | ||
|
||
|
||
@Component | ||
public class JwtTokenProvider { | ||
|
||
private final Key signingKey; | ||
private final long accessTokenExpiration; | ||
private final long refreshTokenExpiration; | ||
|
||
public JwtTokenProvider(@Value("${jwt.secret}") String secretKey, | ||
@Value("${jwt.access-token-expiration}") long accessTokenExpiration, | ||
@Value("${jwt.refresh-token-expiration}") long refreshTokenExpiration) { | ||
this.signingKey = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)); | ||
this.accessTokenExpiration = accessTokenExpiration; | ||
this.refreshTokenExpiration = refreshTokenExpiration; | ||
} | ||
|
||
public String generateAccessToken(String email) { | ||
return Jwts.builder() | ||
.setSubject(email) | ||
.setIssuedAt(new Date()) | ||
.setExpiration(new Date(System.currentTimeMillis() + accessTokenExpiration)) | ||
.signWith(signingKey, SignatureAlgorithm.HS256) | ||
.compact(); | ||
} | ||
|
||
public String generateRefreshToken(String email) { | ||
return Jwts.builder() | ||
.setSubject(email) | ||
.setIssuedAt(new Date()) | ||
.setExpiration(new Date(System.currentTimeMillis() + refreshTokenExpiration)) | ||
.signWith(signingKey, SignatureAlgorithm.HS256) | ||
.compact(); | ||
} | ||
|
||
public boolean validateToken(String token) { | ||
try { | ||
Jwts.parserBuilder().setSigningKey(signingKey).build().parseClaimsJws(token); | ||
return true; | ||
} catch (Exception e) { | ||
return false; | ||
} | ||
} | ||
|
||
public String getEmailFromToken(String token) { | ||
return Jwts.parserBuilder() | ||
.setSigningKey(signingKey) | ||
.build() | ||
.parseClaimsJws(token) | ||
.getBody() | ||
.getSubject(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,72 @@ | ||
package com.example.digger.user; | ||
|
||
import com.example.digger.jwt.JwtTokenProvider; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.stereotype.Service; | ||
|
||
import java.util.Optional; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
|
||
@Service | ||
public class UserService { | ||
|
||
private final UserRepository userRepository; | ||
|
||
private final PasswordEncoder passwordEncoder; | ||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
// 리프레시 토큰 저장소 (데이터베이스 또는 메모리로 변경 가능) | ||
private final Map<String, String> refreshTokenStore = new ConcurrentHashMap<>(); | ||
|
||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { | ||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtTokenProvider jwtTokenProvider) { | ||
this.userRepository = userRepository; | ||
this.passwordEncoder = passwordEncoder; | ||
this.jwtTokenProvider = jwtTokenProvider; | ||
} | ||
|
||
public boolean registerUser(UserDTO userDTO) { | ||
public String joinUser(UserDTO userDTO) { | ||
if(userRepository.findByEmail(userDTO.getEmail()).isPresent()){ | ||
return false; | ||
throw new RuntimeException("이미 등록된 이메일입니다."); | ||
} | ||
|
||
User user = new User(); | ||
user.setEmail(userDTO.getEmail()); | ||
user.setName(userDTO.getName()); | ||
user.setPassword(passwordEncoder.encode(userDTO.getPassword())); | ||
|
||
userRepository.save(user); | ||
return true; | ||
|
||
return jwtTokenProvider.generateAccessToken(user.getEmail()); | ||
} | ||
|
||
public User login(String email, String password) { | ||
Optional<User> userOpt = userRepository.findByEmail(email); | ||
public Map<String, String> login(String email, String password) { | ||
User user = userRepository.findByEmail(email) | ||
.orElseThrow(() -> new RuntimeException("이메일 또는 비밀번호가 잘못되었습니다.")); | ||
|
||
if (userOpt.isEmpty() || !passwordEncoder.matches(password, userOpt.get().getPassword())) { | ||
if (!passwordEncoder.matches(password, user.getPassword())) { | ||
throw new RuntimeException("이메일 또는 비밀번호가 잘못되었습니다."); | ||
} | ||
|
||
return userOpt.get(); | ||
String accessToken = jwtTokenProvider.generateAccessToken(email); | ||
String refreshToken = jwtTokenProvider.generateRefreshToken(email); | ||
|
||
// 리프레시 토큰 저장 | ||
refreshTokenStore.put(email, refreshToken); | ||
|
||
Map<String, String> tokens = new HashMap<>(); | ||
tokens.put("accessToken", accessToken); | ||
tokens.put("refreshToken", refreshToken); | ||
|
||
return tokens; | ||
} | ||
|
||
public String refreshAccessToken(String email, String refreshToken) { | ||
String storedRefreshToken = refreshTokenStore.get(email); | ||
|
||
if (storedRefreshToken == null || !storedRefreshToken.equals(refreshToken)) { | ||
throw new RuntimeException("리프레시 토큰이 유효하지 않습니다."); | ||
} | ||
|
||
// 새 액세스 토큰 발급 | ||
return jwtTokenProvider.generateAccessToken(email); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.