-
Notifications
You must be signed in to change notification settings - Fork 10
[9주차/레오] 워크북 제출합니다 #64
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
yongyong213
wants to merge
3
commits into
UMC-Inha:leo/main
Choose a base branch
from
yongyong213:main
base: leo/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
73 changes: 73 additions & 0 deletions
73
src/main/java/umc/global/security/filter/JwtAuthFilter.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,73 @@ | ||
| package umc.global.security.filter; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.NonNull; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
| import umc.global.apiPayload.ApiResponse; | ||
| import umc.global.apiPayload.code.BaseErrorCode; | ||
| import umc.global.apiPayload.code.GeneralErrorCode; | ||
| import umc.global.security.service.CustomUserDetailService; | ||
| import umc.global.security.util.JwtUtil; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @RequiredArgsConstructor | ||
| public class JwtAuthFilter extends OncePerRequestFilter { | ||
|
|
||
| private final JwtUtil jwtUtil; | ||
| private final CustomUserDetailService customUserDetailsService; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal( | ||
| @NonNull HttpServletRequest request, | ||
| @NonNull HttpServletResponse response, | ||
| @NonNull FilterChain filterChain | ||
| ) throws ServletException, IOException { | ||
|
|
||
| try { | ||
| // 토큰 가져오기 | ||
| String token = request.getHeader("Authorization"); | ||
| // token이 없거나 Bearer가 아니면 넘기기 | ||
| if (token == null || !token.startsWith("Bearer ")) { | ||
| filterChain.doFilter(request, response); | ||
| return; | ||
| } | ||
| // Bearer이면 추출 | ||
| token = token.replace("Bearer ", ""); | ||
| // AccessToken 검증하기: 올바른 토큰이면 | ||
| if (jwtUtil.isValid(token)) { | ||
| // 토큰에서 이메일 추출 | ||
| String email = jwtUtil.getEmail(token); | ||
| // 인증 객체 생성: 이메일로 찾아온 뒤, 인증 객체 생성 | ||
| UserDetails user = customUserDetailsService.loadUserByUsername(email); | ||
| Authentication auth = new UsernamePasswordAuthenticationToken( | ||
| user, | ||
| null, | ||
| user.getAuthorities() | ||
| ); | ||
| // 인증 완료 후 SecurityContextHolder에 넣기 | ||
| SecurityContextHolder.getContext().setAuthentication(auth); | ||
| } | ||
| filterChain.doFilter(request, response); | ||
| } catch (Exception e) { | ||
| ObjectMapper mapper = new ObjectMapper(); | ||
| BaseErrorCode code = GeneralErrorCode.UNAUTHORIZED; | ||
|
|
||
| response.setContentType("application/json;charset=UTF-8"); | ||
| response.setStatus(code.getStatus().value()); | ||
|
|
||
| ApiResponse<Void> errorResponse = ApiResponse.onFailure(code,null); | ||
|
|
||
| mapper.writeValue(response.getOutputStream(), errorResponse); | ||
| } | ||
| } | ||
| } |
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,83 @@ | ||
| package umc.global.security.util; | ||
|
|
||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.Jws; | ||
| import io.jsonwebtoken.JwtException; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.security.Keys; | ||
|
|
||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.stereotype.Component; | ||
| import umc.global.security.entity.AuthMember; | ||
|
|
||
| import javax.crypto.SecretKey; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.Date; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @Component | ||
| public class JwtUtil { | ||
| private final SecretKey secretKey; | ||
| private final Duration accessExpiration; | ||
|
|
||
| public JwtUtil( | ||
| @Value("${jwt.token.secretKey}") String secret, | ||
| @Value("${jwt.token.expiration.access}") Long accessExpiration | ||
| ) { | ||
| this.secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); | ||
| this.accessExpiration = Duration.ofMillis(accessExpiration); | ||
| } | ||
|
|
||
| // AccessToken 생성 | ||
| public String createAccessToken(AuthMember member) { | ||
| return createToken(member, accessExpiration); | ||
| } | ||
|
|
||
| public String getEmail(String token) { | ||
| try { | ||
| return getClaims(token).getPayload().getSubject(); // Parsing해서 Subject 가져오기 | ||
| } catch (JwtException e) { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| public boolean isValid(String token) { | ||
| try { | ||
| getClaims(token); | ||
| return true; | ||
| } catch (JwtException e) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| // 토큰 생성 | ||
| private String createToken(AuthMember member, Duration expiration) { | ||
| Instant now = Instant.now(); | ||
|
|
||
| // 인가 정보 | ||
| String authorities = member.getAuthorities().stream() | ||
| .map(GrantedAuthority::getAuthority) | ||
| .collect(Collectors.joining(",")); | ||
|
|
||
| return Jwts.builder() | ||
| .subject(member.getUsername()) // User 이메일을 Subject로 | ||
| .claim("role", authorities) | ||
| .claim("email", member.getUsername()) | ||
| .issuedAt(Date.from(now)) // 언제 발급한지 | ||
| .expiration(Date.from(now.plus(expiration))) // 언제까지 유효한지 | ||
| .signWith(secretKey) // sign할 Key | ||
| .compact(); | ||
| } | ||
|
|
||
| // 토큰 정보 가져오기 | ||
| private Jws<Claims> getClaims(String token) throws JwtException { | ||
| return Jwts.parser() | ||
| .verifyWith(secretKey) | ||
| .clockSkewSeconds(60) | ||
| .build() | ||
| .parseSignedClaims(token); | ||
| } | ||
| } |
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 |
|---|---|---|
| @@ -1,10 +1,13 @@ | ||
| package umc.member.controller; | ||
|
|
||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import jakarta.validation.Valid; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.core.annotation.AuthenticationPrincipal; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import umc.global.apiPayload.ApiResponse; | ||
| import umc.global.apiPayload.code.BaseSuccessCode; | ||
| import umc.global.security.entity.AuthMember; | ||
| import umc.member.dto.MemberReqDTO; | ||
| import umc.member.dto.MemberResDTO; | ||
| import umc.member.exception.code.MemberSuccessCode; | ||
|
|
@@ -20,13 +23,13 @@ public class MemberController { | |
| private final MemberService memberService; | ||
| private final MissionService missionService; | ||
|
|
||
| @PostMapping("/v1/users/me") | ||
| @GetMapping("/v2/users/me") | ||
| @Operation(summary = "마이페이지 조회") | ||
| public ApiResponse<MemberResDTO.GetInfo> getInfo( | ||
| @RequestBody MemberReqDTO.GetInfo dto | ||
| @AuthenticationPrincipal AuthMember member | ||
| ){ | ||
| BaseSuccessCode code = MemberSuccessCode.OK; | ||
| return ApiResponse.onSuccess(code, memberService.getInfo(dto)); | ||
| return ApiResponse.onSuccess(code, memberService.getInfo(member)); | ||
| } | ||
|
|
||
| @GetMapping("/v1/home") | ||
|
|
@@ -42,10 +45,18 @@ public ApiResponse<MissionResDTO.MissionListDTO> getHomeInfo( | |
| @PostMapping("/v1/auth/signup") | ||
| @Operation(summary = "회원가입") | ||
| public ApiResponse<MemberResDTO.AuthResDTO.SignUpResultDTO> signUp( | ||
| @RequestBody MemberReqDTO.SingUpDTO request | ||
| @Valid @RequestBody MemberReqDTO.SingUpDTO request | ||
| ) { | ||
| MemberResDTO.AuthResDTO.SignUpResultDTO result = memberService.signUp(request); | ||
|
|
||
| return ApiResponse.onSuccess(MemberSuccessCode.JOIN_OK, result); | ||
| } | ||
|
|
||
| @PostMapping("/v1/login") | ||
|
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. 회원가입 url은 auth를 포함하는데 로그인 url에서는 auth를 안 쓰신 이유가 있나용?? |
||
| @Operation(summary = "로그인") | ||
| public ApiResponse<MemberResDTO.LoginResDTO> login( | ||
| @Valid @RequestBody MemberReqDTO.LoginDTO request | ||
| ) { | ||
| return ApiResponse.onSuccess(MemberSuccessCode.LOGIN_OK, memberService.login(request)); | ||
| } | ||
| } | ||
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
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
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 |
|---|---|---|
|
|
@@ -11,7 +11,8 @@ public enum MemberSuccessCode implements BaseSuccessCode { | |
|
|
||
| OK(HttpStatus.OK, "MEMBER200_1", "성공적으로 유저를 조회했습니다."), | ||
|
|
||
| JOIN_OK(HttpStatus.OK, "MEMBER200_2", "성공적으로 가입을 완료했습니다."); | ||
| JOIN_OK(HttpStatus.OK, "MEMBER200_2", "성공적으로 가입을 완료했습니다."), | ||
|
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. 회원 가입 할 때 OK보다는 회원이 생성되었으니까 CREATED를 사용하고 상태 코드도 201번이 더 알맞아 보입니다! |
||
| LOGIN_OK(HttpStatus.OK, "MEMBER200_3", "성공적으로 로그인했습니다."),; | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
|
|
||
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.
jwt 토큰을 이용해서 마이페이지 조회하는 api 잘 짜신 것 같아요!