-
Notifications
You must be signed in to change notification settings - Fork 12
[9,10주차/밤하늘] 워크북 제출합니다. #62
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
Open
eclipse021
wants to merge
3
commits into
UMC-Inha:bamhaneul/main
Choose a base branch
from
eclipse021:feature/#3
base: bamhaneul/main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 hidden or 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 hidden or 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
9 changes: 9 additions & 0 deletions
9
src/main/java/umc/apiPayload/exception/handler/UserHandler.java
This file contains hidden or 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,9 @@ | ||
package umc.apiPayload.exception.handler; | ||
|
||
import umc.apiPayload.code.BaseErrorCode; | ||
import umc.apiPayload.exception.GeneralException; | ||
|
||
public class UserHandler extends GeneralException { | ||
|
||
public UserHandler(BaseErrorCode errorCode) {super(errorCode);} | ||
} |
This file contains hidden or 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 umc.config.properties; | ||
|
||
public final class Constants { | ||
public static final String AUTH_HEADER = "Authorization"; | ||
public static final String TOKEN_PREFIX = "Bearer "; | ||
} |
This file contains hidden or 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,22 @@ | ||
package umc.config.properties; | ||
|
||
import lombok.Getter; | ||
import lombok.Setter; | ||
import org.springframework.boot.context.properties.ConfigurationProperties; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
@Getter | ||
@Setter | ||
@ConfigurationProperties("jwt.token") | ||
public class JwtProperties { | ||
private String secretKey=""; | ||
private Expiration expiration; | ||
|
||
@Getter | ||
@Setter | ||
public static class Expiration{ | ||
private Long access; | ||
// TODO: refreshToken | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
src/main/java/umc/config/security/CustomUserDetailsService.java
This file contains hidden or 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,28 @@ | ||
package umc.config.security; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
import org.springframework.stereotype.Service; | ||
import umc.domain.User; | ||
import umc.repository.user.UserRepository; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
public class CustomUserDetailsService implements UserDetailsService { | ||
|
||
private final UserRepository userRepository; | ||
|
||
@Override | ||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | ||
User user = userRepository.findByEmail(username) | ||
.orElseThrow(() -> new UsernameNotFoundException("해당 이메일을 가진 유저가 존재하지 않습니다: " + username)); | ||
|
||
return org.springframework.security.core.userdetails.User | ||
.withUsername(user.getEmail()) | ||
.password(user.getPassword()) | ||
.roles(user.getRole().name()) | ||
.build(); | ||
} | ||
} |
This file contains hidden or 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,67 @@ | ||
package umc.config.security; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
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; | ||
import umc.config.security.jwt.JwtAuthenticationFilter; | ||
import umc.config.security.jwt.JwtTokenProvider; | ||
|
||
@EnableWebSecurity | ||
@Configuration | ||
@RequiredArgsConstructor | ||
public class SecurityConfig { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
/* @Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
|
||
http | ||
.sessionManagement(session -> | ||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
) | ||
.authorizeHttpRequests( | ||
(requests) -> requests | ||
.requestMatchers("/", "/users/join", "/users/login", "/swagger-ui/**", "/v3/api-docs/**").permitAll() | ||
.requestMatchers("/admin/**").hasRole("ADMIN") | ||
.anyRequest().authenticated() | ||
) | ||
.csrf(csrf -> csrf.disable()) | ||
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); | ||
|
||
return http.build(); | ||
}*/ | ||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
http | ||
.authorizeHttpRequests((requests) -> requests | ||
.requestMatchers("/", "/home", "/signup","/users/signup", "/css/**").permitAll() | ||
.requestMatchers("/admin/**").hasRole("ADMIN") | ||
.anyRequest().authenticated() | ||
) | ||
.formLogin((form) -> form | ||
.loginPage("/login") | ||
.defaultSuccessUrl("/home", true) | ||
.permitAll() | ||
) | ||
.logout((logout) -> logout | ||
.logoutUrl("/logout") | ||
.logoutSuccessUrl("/login?logout") | ||
.permitAll() | ||
); | ||
|
||
return http.build(); | ||
} | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return new BCryptPasswordEncoder(); | ||
} | ||
} |
44 changes: 44 additions & 0 deletions
44
src/main/java/umc/config/security/jwt/JwtAuthenticationFilter.java
This file contains hidden or 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,44 @@ | ||
package umc.config.security.jwt; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
import umc.config.properties.Constants; | ||
|
||
import java.io.IOException; | ||
|
||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, | ||
HttpServletResponse response, | ||
FilterChain filterChain) | ||
throws ServletException, IOException { | ||
|
||
String token = resolveToken(request); | ||
|
||
if(StringUtils.hasText(token) && jwtTokenProvider.validateToken(token)) { | ||
Authentication authentication = jwtTokenProvider.getAuthentication(token); | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
filterChain.doFilter(request, response); | ||
} | ||
|
||
private String resolveToken(HttpServletRequest request) { | ||
String bearerToken = request.getHeader(Constants.AUTH_HEADER); | ||
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith(Constants.TOKEN_PREFIX)) { | ||
return bearerToken.substring(Constants.TOKEN_PREFIX.length()); | ||
} | ||
return null; | ||
} | ||
} | ||
|
85 changes: 85 additions & 0 deletions
85
src/main/java/umc/config/security/jwt/JwtTokenProvider.java
This file contains hidden or 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,85 @@ | ||
package umc.config.security.jwt; | ||
|
||
import io.jsonwebtoken.*; | ||
import io.jsonwebtoken.security.Keys; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.userdetails.User; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.util.StringUtils; | ||
import umc.apiPayload.code.status.ErrorStatus; | ||
import umc.apiPayload.exception.handler.UserHandler; | ||
import umc.config.properties.Constants; | ||
import umc.config.properties.JwtProperties; | ||
|
||
import java.security.Key; | ||
import java.util.Date; | ||
import java.util.Collections; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtTokenProvider { | ||
|
||
private final JwtProperties jwtProperties; | ||
|
||
private Key getSigningKey() { | ||
return Keys.hmacShaKeyFor(jwtProperties.getSecretKey().getBytes()); | ||
} | ||
|
||
public String generateToken(Authentication authentication) { | ||
String email = authentication.getName(); | ||
|
||
return Jwts.builder() | ||
.setSubject(email) | ||
.claim("role", authentication.getAuthorities().iterator().next().getAuthority()) | ||
.setIssuedAt(new Date()) | ||
.setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getExpiration().getAccess())) | ||
.signWith(getSigningKey(), SignatureAlgorithm.HS256) | ||
.compact(); | ||
} | ||
|
||
public boolean validateToken(String token) { | ||
try { | ||
Jwts.parserBuilder() | ||
.setSigningKey(getSigningKey()) | ||
.build() | ||
.parseClaimsJws(token); | ||
return true; | ||
} catch (JwtException | IllegalArgumentException e) { | ||
return false; | ||
} | ||
} | ||
|
||
public Authentication getAuthentication(String token) { | ||
Claims claims = Jwts.parserBuilder() | ||
.setSigningKey(getSigningKey()) | ||
.build() | ||
.parseClaimsJws(token) | ||
.getBody(); | ||
|
||
String email = claims.getSubject(); | ||
String role = claims.get("role", String.class); | ||
|
||
User principal = new User(email, "", Collections.singleton(() -> role)); | ||
return new UsernamePasswordAuthenticationToken(principal, token, principal.getAuthorities()); | ||
} | ||
|
||
public static String resolveToken(HttpServletRequest request) { | ||
String bearerToken = request.getHeader(Constants.AUTH_HEADER); | ||
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith(Constants.TOKEN_PREFIX)) { | ||
return bearerToken.substring(Constants.TOKEN_PREFIX.length()); | ||
} | ||
return null; | ||
} | ||
|
||
public Authentication extractAuthentication(HttpServletRequest request){ | ||
String accessToken = resolveToken(request); | ||
if(accessToken == null || !validateToken(accessToken)) { | ||
throw new UserHandler(ErrorStatus.INVALID_TOKEN); | ||
} | ||
return getAuthentication(accessToken); | ||
} | ||
} | ||
|
This file contains hidden or 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.
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.
이거 리스트로 안 받고, Page로 받으면 밑에서 따로 Page 관련 값들 세팅 안 해도 돼서 더 효율적일 것 같아요 !
Page<MissionResponseDTO.MissionDTO> userMissionDTOPage = userMissionList.map(MissionConverter::toMissionDTO);