-
Notifications
You must be signed in to change notification settings - Fork 1
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: application.yml profile 별 분리 및 인증 로직 기본 구현, JWT 관련 로직 구현 #30
Merged
Merged
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
14e90f0
feat: spring security 관련 의존성 추가
choidongkuen 968125f
feat: spring oauth 2.0 관련 의존성 추가
choidongkuen 0dc8115
refactor: User 엔티티 관련 리팩토링 및 관련 클래스 리팩토링
choidongkuen 6b0fd57
feat: UserAuthentication (인증 객체) 구현
choidongkuen 2f11420
feat: SecurityUtil 구현
choidongkuen 550e344
feat: redis 의존성 추가
choidongkuen 8db4cac
feat: profile 분리 ( 개발, 운영, 테스트, 인증, 데이터소스, 레디스 )
choidongkuen 11b6879
feat: io-netty-dns-native-macos 관련 의존성 추가
choidongkuen 2f26a0e
feat: JWT 관련 설정값 & Redis 관련 설정값 주입 구현
choidongkuen 35f1f4e
feat: application-redis.yml 구현
choidongkuen eb2f318
feat: jwt 의존성 추가 (#17)
choidongkuen 4e27f1a
feat: jwtAuthenticationFilter 구현 및 관련 Service 구현 (#17)
choidongkuen 9d19b7e
feat: 응답을 위한 TokenResponse 구현 및 기타 구현 (#17)
choidongkuen 993acbd
fix: IntegrationTest 수정 (#17)
choidongkuen 9f480f4
refactor: JwtAuthenticationFilter 불필요한 주석 제거 (#17)
choidongkuen dbb7adc
fix: ci 에러 수정 (#17)
choidongkuen d76ac8b
fix: ci 에러 수정 (#17)
choidongkuen 524cc04
fix: ci 에러 수정 (#17)
choidongkuen 7d3edf5
fix: PropertyTest 제거 (#17)
choidongkuen 54a0b86
fix: ci 에러 수정 (#17)
choidongkuen 4311b09
fix: ci 에러 수정 (#17)
choidongkuen 4f41c73
fix: ci 에러 수정 (#17)
choidongkuen 5da01b9
fix: ci 에러 수정 (#17)
choidongkuen c456395
fix: ci 에러 수정 (#17)
choidongkuen 78ef69b
fix: ci 에러 수정 (#17)
choidongkuen e8e27c8
feat: securityConfig JwtAuthenticationFilter 적용 (#17)
choidongkuen b68ca54
fix: ci 에러 수정 (#17)
choidongkuen 6477a2a
Merge branch 'develop' into iss-#7
choidongkuen e0f419b
fix: ci 에러 수정 (#17)
choidongkuen cc5c25b
Merge remote-tracking branch 'origin/iss-#7' into iss-#7
choidongkuen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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 |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package net.teumteum.core.config; | ||
|
||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; | ||
|
||
@Configuration | ||
@EnableJpaAuditing | ||
@ConfigurationPropertiesScan("net.teumteum.core.property") | ||
public class AppConfig { | ||
} |
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 |
---|---|---|
|
@@ -2,8 +2,8 @@ | |
|
||
public interface LoginContext { | ||
|
||
void setUserId(Long userId); | ||
|
||
Long getUserId(); | ||
|
||
void setUserId(Long userId); | ||
|
||
} |
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
38 changes: 16 additions & 22 deletions
38
src/main/java/net/teumteum/core/entity/TimeBaseEntity.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,35 +1,29 @@ | ||
package net.teumteum.core.entity; | ||
|
||
import jakarta.persistence.Column; | ||
import jakarta.persistence.EntityListeners; | ||
import jakarta.persistence.MappedSuperclass; | ||
import jakarta.persistence.PrePersist; | ||
import jakarta.persistence.PreUpdate; | ||
import java.time.Instant; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
import lombok.experimental.SuperBuilder; | ||
import org.springframework.data.annotation.CreatedDate; | ||
import org.springframework.data.annotation.LastModifiedDate; | ||
import org.springframework.data.jpa.domain.support.AuditingEntityListener; | ||
|
||
import java.time.Instant; | ||
|
||
@Getter | ||
@SuperBuilder | ||
@NoArgsConstructor | ||
@MappedSuperclass | ||
@EntityListeners(AuditingEntityListener.class) | ||
public abstract class TimeBaseEntity { | ||
@CreatedDate | ||
@Column(name = "created_at", nullable = false, updatable = false) | ||
private Instant createdAt; | ||
|
||
@Column(name = "created_at", columnDefinition = "TIMESTAMP(6)", nullable = false, updatable = false) | ||
protected Instant createdAt; | ||
|
||
@Column(name = "updated_at", columnDefinition = "TIMESTAMP(6)", nullable = false) | ||
protected Instant updatedAt; | ||
|
||
@PrePersist | ||
void prePersist() { | ||
var now = Instant.now(); | ||
|
||
createdAt = createdAt != null ? createdAt : now; | ||
updatedAt = updatedAt != null ? updatedAt : now; | ||
} | ||
|
||
@PreUpdate | ||
void preUpdate() { | ||
updatedAt = updatedAt != null ? updatedAt : Instant.now(); | ||
} | ||
|
||
@LastModifiedDate | ||
@Column(name = "updated_at", nullable = false) | ||
private Instant updatedAt; | ||
} | ||
|
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,32 @@ | ||
package net.teumteum.core.property; | ||
|
||
import lombok.Getter; | ||
import lombok.Setter; | ||
import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
||
@Getter | ||
@Setter | ||
@ConfigurationProperties(prefix = "jwt") | ||
public class JwtProperty { | ||
|
||
private String bearer; | ||
private String secret; | ||
private Access access; | ||
private Refresh refresh; | ||
|
||
|
||
@Getter | ||
@Setter | ||
public static class Access{ | ||
private long expiration; | ||
private String header; | ||
|
||
} | ||
|
||
@Getter | ||
@Setter | ||
public static class Refresh { | ||
private long expiration; | ||
private String header; | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/net/teumteum/core/property/RedisProperty.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,13 @@ | ||
package net.teumteum.core.property; | ||
|
||
import lombok.Getter; | ||
import lombok.Setter; | ||
import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
||
@Getter | ||
@Setter | ||
@ConfigurationProperties(prefix = "data.redis") | ||
public class RedisProperty { | ||
private String host; | ||
private int port; | ||
} |
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,6 @@ | ||
package net.teumteum.core.security; | ||
|
||
/* 소셜 OAuth 로그인 타입 */ | ||
public enum Authenticated { | ||
카카오,네이버; | ||
} |
60 changes: 60 additions & 0 deletions
60
src/main/java/net/teumteum/core/security/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 |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package net.teumteum.core.security; | ||
|
||
|
||
import lombok.RequiredArgsConstructor; | ||
import net.teumteum.core.security.filter.JwtAuthenticationFilter; | ||
import org.springframework.boot.autoconfigure.security.servlet.PathRequest; | ||
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.annotation.web.configurers.AbstractHttpConfigurer; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; | ||
import org.springframework.web.cors.CorsConfiguration; | ||
import org.springframework.web.cors.CorsConfigurationSource; | ||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; | ||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
@RequiredArgsConstructor | ||
public class SecurityConfig { | ||
|
||
private final JwtAuthenticationFilter jwtAuthenticationFilter; | ||
|
||
@Bean | ||
SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { | ||
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); | ||
http | ||
.csrf(AbstractHttpConfigurer::disable) | ||
.authorizeHttpRequests(request | ||
-> request.requestMatchers("/users").permitAll() | ||
.requestMatchers(PathRequest.toH2Console()).permitAll() | ||
.anyRequest().authenticated()) | ||
.httpBasic(AbstractHttpConfigurer::disable) | ||
.formLogin(AbstractHttpConfigurer::disable) | ||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) | ||
.sessionManagement(sessionManagement | ||
-> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
) | ||
.cors(cors -> cors.configurationSource(this.corsConfigurationSource())); | ||
|
||
return http.build(); | ||
} | ||
|
||
@Bean | ||
public CorsConfigurationSource corsConfigurationSource() { | ||
CorsConfiguration configuration = new CorsConfiguration(); | ||
configuration.addAllowedOrigin("*"); | ||
configuration.addAllowedMethod("*"); | ||
configuration.addAllowedHeader("*"); | ||
configuration.setMaxAge(3600L); | ||
|
||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | ||
source.registerCorsConfiguration("/**", configuration); | ||
return source; | ||
} | ||
} |
48 changes: 48 additions & 0 deletions
48
src/main/java/net/teumteum/core/security/UserAuthentication.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,48 @@ | ||
package net.teumteum.core.security; | ||
|
||
import lombok.Getter; | ||
import net.teumteum.user.domain.User; | ||
import org.springframework.security.authentication.AbstractAuthenticationToken; | ||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
@Getter | ||
public class UserAuthentication extends AbstractAuthenticationToken { | ||
|
||
private final String oauthId; | ||
private Long id; | ||
|
||
public UserAuthentication(User user) { | ||
super(authorities(user)); | ||
this.id = user.getId(); | ||
this.oauthId = user.getOauth().getOauthId(); | ||
} | ||
|
||
private static List<GrantedAuthority> authorities(User User) { | ||
List<GrantedAuthority> authorities = new ArrayList<>(); | ||
authorities.add(new SimpleGrantedAuthority(User.getRoleType().name())); | ||
return authorities; | ||
} | ||
|
||
@Override | ||
public Object getCredentials() { | ||
return null; | ||
} | ||
|
||
@Override | ||
public Object getPrincipal() { | ||
return id; | ||
} | ||
|
||
@Override | ||
public boolean isAuthenticated() { | ||
return true; | ||
} | ||
|
||
public void setUserId(Long userId) { | ||
id = userId; | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
src/main/java/net/teumteum/core/security/dto/TokenResponse.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,18 @@ | ||
package net.teumteum.core.security.dto; | ||
|
||
import lombok.Builder; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
|
||
@Getter | ||
@NoArgsConstructor | ||
public class TokenResponse { | ||
private String accessToken; | ||
private String refreshToken; | ||
|
||
@Builder | ||
public TokenResponse(String accessToken, String refreshToken) { | ||
this.accessToken = accessToken; | ||
this.refreshToken = refreshToken; | ||
} | ||
} |
64 changes: 64 additions & 0 deletions
64
src/main/java/net/teumteum/core/security/filter/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,64 @@ | ||
package net.teumteum.core.security.filter; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import net.teumteum.core.property.JwtProperty; | ||
import net.teumteum.core.security.UserAuthentication; | ||
import net.teumteum.core.security.service.AuthService; | ||
import net.teumteum.core.security.service.JwtService; | ||
import net.teumteum.user.domain.User; | ||
import org.springframework.security.authentication.InsufficientAuthenticationException; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.util.ObjectUtils; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
import java.io.IOException; | ||
|
||
@Slf4j | ||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
private final JwtService jwtService; | ||
private final AuthService authService; | ||
private final JwtProperty jwtProperty; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, | ||
HttpServletResponse response, | ||
FilterChain filterChain) throws ServletException, IOException { | ||
/* Cors Preflight Request */ | ||
if (request.getMethod().equals("OPTIONS")) { | ||
return; | ||
} | ||
|
||
try { | ||
String token = this.resolveTokenFromRequest(request); | ||
if (checkTokenExistenceAndValidation(token)) { | ||
User user = this.authService.findUserByToken(token).get(); | ||
UserAuthentication authentication = new UserAuthentication(user); | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
} catch (InsufficientAuthenticationException e) { | ||
log.info("JwtAuthentication UnauthorizedUserException!"); | ||
} | ||
filterChain.doFilter(request, response); | ||
} | ||
|
||
private boolean checkTokenExistenceAndValidation(String token) { | ||
return StringUtils.hasText(token) && this.jwtService.validateToken(token); | ||
} | ||
|
||
private String resolveTokenFromRequest(HttpServletRequest request) { | ||
String token = request.getHeader(jwtProperty.getAccess().getHeader()); | ||
if (!ObjectUtils.isEmpty(token) && token.toLowerCase().startsWith(jwtProperty.getBearer().toLowerCase())) { | ||
return token.substring(jwtProperty.getBearer().length()).trim(); | ||
} | ||
return null; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
마지막 띄워쓰기 추가해주세용
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://seongwon.dev/Git/20220303-%ED%8C%8C%EC%9D%BC%EC%9D%98_%EB%A7%88%EC%A7%80%EB%A7%89_%EA%B0%9C%ED%96%89/