Skip to content
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

인증객체 ,ArgumentResolver추가 #18

Merged
merged 1 commit into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/com/dnd/dndtravel/auth/service/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,21 @@ public String refreshToken(Long memberId) {
.signWith(Keys.hmacShaKeyFor(Base64.getDecoder().decode(this.secretKey)))
.compact();
}

public Claims parseClaims(String splitHeader) {
Jws<Claims> claims;
try {
claims = Jwts.parser()
.verifyWith(Keys.hmacShaKeyFor(Base64.getDecoder().decode(this.secretKey)))
.build()
.parseSignedClaims(splitHeader);

} catch (ExpiredJwtException e) {
throw new RuntimeException("message", e); // 유효하지 않은 토큰
} catch (JwtException e) {
throw new RuntimeException("message", e); // 토큰 해독 실패
}

return claims.getPayload();
}
}
57 changes: 57 additions & 0 deletions src/main/java/com/dnd/dndtravel/config/AuthResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.dnd.dndtravel.config;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.dnd.dndtravel.auth.service.JwtProvider;
import com.dnd.dndtravel.member.domain.Member;
import com.dnd.dndtravel.member.repository.MemberRepository;

import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class AuthResolver implements HandlerMethodArgumentResolver {

private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String MEMBER_ID_CLAIM = "memberId";
private static final String BEARER_PREFIX = "Bearer";
private final MemberRepository memberRepository;
private final JwtProvider jwtProvider;

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(AuthenticationMember.class);
}
Comment on lines +25 to +28
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 메소드는 해당 파라미터가 컨트롤러에서 처리할 수 있는 파라미터 타입인지 확인하는 거 맞나요 ?!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 맞습니다 ㅎㅎ


@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {

// 헤더 자체가 비어있는 경우
String header = webRequest.getHeader(AUTHORIZATION_HEADER);
if (header == null || header.isEmpty()) {
throw new RuntimeException("토큰이 없음");
}

String[] splitHeaders = header.split(" ");

//<Bearer> <token> 형식이 아닌경우
if (splitHeaders.length != 2 || !BEARER_PREFIX.equals(splitHeaders[0])) {
throw new RuntimeException("유효하지 않은 토큰 형식");
}

//토큰 까봐서 만료,조작여부 확인
Claims accessClaim = jwtProvider.parseClaims(splitHeaders[1]);

//토큰에 심었던 user 식별자값 유효성 확인
Member member = memberRepository.findById((Long)accessClaim.get(MEMBER_ID_CLAIM))
.orElseThrow(() -> new RuntimeException("유효하지 않은 토큰 값"));

// 컨트롤러 파라미터로 반환
return new AuthenticationMember(member.getId());
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 클래스는 어디서 사용되나요 ?!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pr 스크린샷에 명시해뒀습니다

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.dnd.dndtravel.config;

public record AuthenticationMember(
long id
) {
}
25 changes: 25 additions & 0 deletions src/main/java/com/dnd/dndtravel/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.dnd.dndtravel.config;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.dnd.dndtravel.auth.service.JwtProvider;
import com.dnd.dndtravel.member.repository.MemberRepository;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Component
public class WebMvcConfig implements WebMvcConfigurer {

private final MemberRepository memberRepository;
private final JwtProvider jwtProvider;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new AuthResolver(memberRepository, jwtProvider));
}
Comment on lines +21 to +24
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 메소드는 어떤 일을 하는건가용
AuthResolver를 생성하면서 memberRepository와 jwtProvider를 주입하게 되면 어떻게 되는지 궁금합니다!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

단순하게 생성자 주입이라고 생각하시면 될것같습니다 AuthResolver에서 memberRepository와 jwtProvider를 사용할수있게됩니다~~~

}
Loading