-
Notifications
You must be signed in to change notification settings - Fork 78
[Spring Core] 안정현 미션제출합니다. #76
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
stableh
wants to merge
9
commits into
next-step:anhye0n
Choose a base branch
from
stableh:step3
base: anhye0n
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
9 commits
Select commit
Hold shift + click to select a range
672941e
feat: 1단계 완료
stableh 2626aa7
feat: 2단계 완료
stableh a7a9513
feat: 3단계 완료
stableh 6758db4
refactor: 주석 제거
stableh 6e5bed7
4단계 통과
stableh f02f80e
5단계 통과
stableh 64cf3a3
6단계 통과
stableh 898db85
7단계 통과
stableh 957b4ba
8단계 통과
stableh 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package roomescape.admin; | ||
|
|
||
| import jakarta.servlet.http.Cookie; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.servlet.HandlerInterceptor; | ||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.security.Keys; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Arrays; | ||
|
|
||
| @Component | ||
| public class AdminInterceptor implements HandlerInterceptor { | ||
|
|
||
| private static final String SECRET_KEY = "Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E="; | ||
|
|
||
| @Override | ||
| public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { | ||
| String token = Arrays.stream(request.getCookies()) | ||
| .filter(cookie -> "token".equals(cookie.getName())) | ||
| .findFirst() | ||
| .map(Cookie::getValue) | ||
| .orElse(null); | ||
|
|
||
| if (token == null || !isAdmin(token)) { | ||
| response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| private boolean isAdmin(String token) { | ||
| try { | ||
| Claims claims = Jwts.parserBuilder() | ||
| .setSigningKey(Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8))) | ||
| .build() | ||
| .parseClaimsJws(token) | ||
| .getBody(); | ||
| String role = claims.get("role", String.class); | ||
| return "ADMIN".equals(role); | ||
| } catch (Exception e) { | ||
| return false; | ||
| } | ||
| } | ||
| } |
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,20 @@ | ||
| package roomescape.auth; | ||
|
|
||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| @Configuration | ||
| public class JwtConfig { | ||
|
|
||
| @Value("${roomescape.auth.jwt.secret}") | ||
| private String secret; | ||
|
|
||
| @Value("${jwt.expiration}") | ||
| private Long expiration; | ||
|
|
||
| @Bean | ||
| public JwtUtil jwtUtil() { | ||
| return new JwtUtil(secret, expiration); | ||
| } | ||
| } | ||
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,53 @@ | ||
| package roomescape.auth; | ||
|
|
||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.SignatureAlgorithm; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| import javax.crypto.SecretKey; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Date; | ||
|
|
||
| public class JwtUtil { | ||
|
|
||
| private static SecretKey secretKey; | ||
| private final Long expiration; | ||
|
|
||
| public JwtUtil(String secret, Long expiration) { | ||
| secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); | ||
| this.expiration = expiration; | ||
| } | ||
|
|
||
| public String generateToken(String userId, String name, String role) { | ||
| Claims claims = Jwts.claims().setSubject(userId); | ||
| claims.put("name", name); | ||
| claims.put("role", role); | ||
| return Jwts.builder() | ||
| .setClaims(claims) | ||
| .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) | ||
| .signWith(secretKey, SignatureAlgorithm.HS512) | ||
| .compact(); | ||
| } | ||
|
|
||
| public static Claims parseToken(String token) { | ||
| return Jwts.parserBuilder() | ||
| .setSigningKey(secretKey) | ||
| .build() | ||
| .parseClaimsJws(token) | ||
| .getBody(); | ||
| } | ||
|
|
||
| public static Long getUserIdFromToken(String token) { | ||
| Claims claims = parseToken(token); | ||
| return Long.parseLong(claims.getSubject()); | ||
| } | ||
|
|
||
| public String getRoleFromToken(String token) { | ||
| Claims claims = parseToken(token); | ||
| return (String) claims.get("role"); | ||
| } | ||
| } |
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,20 @@ | ||
| package roomescape.config; | ||
|
|
||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.web.servlet.config.annotation.InterceptorRegistry; | ||
| import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | ||
| import roomescape.admin.AdminInterceptor; | ||
|
|
||
| @Configuration | ||
| public class InterceptorConfig implements WebMvcConfigurer { | ||
|
|
||
| @Autowired | ||
| private AdminInterceptor adminInterceptor; | ||
|
|
||
| @Override | ||
| public void addInterceptors(InterceptorRegistry registry) { | ||
| registry.addInterceptor(adminInterceptor) | ||
| .addPathPatterns("/admin/**"); | ||
| } | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. interceptor와 argumentResolver의 역할이 맥락적으로 같다고 생각해서 같은 config안에 등록해주는 건 어떨까요? |
||
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,31 @@ | ||
| package roomescape.member; | ||
|
|
||
| public class LoginMember { | ||
| private Long id; | ||
| private String name; | ||
| private String email; | ||
| private String role; | ||
|
|
||
| public LoginMember(Long id, String name, String email, String role) { | ||
| this.id = id; | ||
| this.name = name; | ||
| this.email = email; | ||
| this.role = role; | ||
| } | ||
|
|
||
| public Long getId() { | ||
| return id; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public String getEmail() { | ||
| return email; | ||
| } | ||
|
|
||
| public String getRole() { | ||
| return role; | ||
| } | ||
| } |
55 changes: 55 additions & 0 deletions
55
src/main/java/roomescape/member/LoginMemberArgumentResolver.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,55 @@ | ||
| package roomescape.member; | ||
|
|
||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import jakarta.servlet.http.Cookie; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import org.springframework.core.MethodParameter; | ||
| import org.springframework.web.context.request.NativeWebRequest; | ||
| import org.springframework.web.context.request.RequestAttributes; | ||
| import org.springframework.web.method.support.HandlerMethodArgumentResolver; | ||
| import org.springframework.web.method.support.ModelAndViewContainer; | ||
|
|
||
| public class LoginMemberArgumentResolver implements HandlerMethodArgumentResolver { | ||
| private final MemberService memberService; | ||
| private final String secretKey = "Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E="; | ||
|
|
||
| public LoginMemberArgumentResolver(MemberService memberService) { | ||
| this.memberService = memberService; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean supportsParameter(MethodParameter parameter) { | ||
| return parameter.getParameterType().equals(LoginMember.class); | ||
| } | ||
|
|
||
| @Override | ||
| public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, org.springframework.web.bind.support.WebDataBinderFactory binderFactory) throws Exception { | ||
| HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); | ||
| Cookie[] cookies = request.getCookies(); | ||
|
|
||
| String token = null; | ||
| if (cookies != null) { | ||
| for (Cookie cookie : cookies) { | ||
| if ("token".equals(cookie.getName())) { | ||
| token = cookie.getValue(); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (token == null) { | ||
| throw new IllegalArgumentException("No token found in cookies"); | ||
| } | ||
|
|
||
| Long memberId = Long.valueOf(Jwts.parserBuilder() | ||
| .setSigningKey(Keys.hmacShaKeyFor(secretKey.getBytes())) | ||
| .build() | ||
| .parseClaimsJws(token) | ||
| .getBody().getSubject()); | ||
|
|
||
| Member member = memberService.findById(memberId); | ||
|
|
||
| return new LoginMember(member.getId(), member.getName(), member.getEmail(), member.getRole()); | ||
| } | ||
| } |
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
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.
저도 이거를 고민했는데 roomescape내의 패키지로 auth를 만들 경우, 이게 맞는데 미션에서 동등한 계층이라는 말이 있어서 저는 java밑의 계층의 패키지로 만들어주었습니다. 그럴 경우 @import를 사용해서 외부 컴포넌트 스캔 범위를 벗어나는 경우를 스캔 할 수 있더라구요!