-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[FU-54] OAuth2.0 연동 및 인증/인가 처리 (#10)
* FU-54 feat: add OAuth2 client registration for kakao OAuth2 Client 등록 설정을 추가함 * FU-54 fix: client-authentication-method 변경 카카오 로그인에서 Client Secret 옵션을 활성화 함에 따라, client-authentication-method를 변경해주었음 * FU-54 feat: add OAuth2 client registration for kakao OAuth2 Client 등록 설정을 추가함 * FU-54 fix: client-authentication-method 변경 카카오 로그인에서 Client Secret 옵션을 활성화 함에 따라, client-authentication-method를 변경해주었음 * FU-54 refactor: update application.yaml FU-55가 develop에 먼저 merge되면서 rebase를 수행하여 yaml파일을 업데이트할 필요가 있었음 * FU-54 fix: application.yaml 오타 수정 autorize -> authorize * FU-54 feat: add SecurityConfig * FU-54 feat: OAuth2UserService 인터페이스 구현 - SpringSecurity에서 제공하는 기본 구현체인 OAuth2UserService를 커스텀하였음. - OAuth2UserService는 인가서버와 통신한 후, 사용자 정보를 OAuth2User 객체에 가져오게 됨. - 추후 해당 객체를 활용하여 DB에 회원등록 처리를 하기 위해 loadUser 메서드를 오버라이드 하였음. * FU-54 feat: 기본적인 회원가입 로직 구현 카카오 서버로부터 받아온 사용자 정보를 DB에 저장하는 로직을 구현하였음 * FU-54 chore: aws cognito 의존성 추가 사용자 토큰 생성 및 관리를 위해 aws cognito를 연동하고자 의존성을 추가함 * FU-54 feat: cognito user pool 등록 api 구현 카카오 서버에서 받아온 유저 정보를 cognito에 등록하기 위한 api를 구현하였음 * FU-54 fix: user pool 등록 시 phone number 포맷팅 에러 수정 - 기존에 카카오 서버에서 받아오는 phone number 포맷은 +82 10-0000-0000이었으나, 이대로 cognito 등록 시 Invalid phone number format error가 발생했음. - AWS Cognito는 전화번호의 형식을 E.164 표준으로 요구하기 때문에 문자(+, -)를 제외하고 숫자만으로 변환하였음 * FU-54 refactor: 코딩컨벤션에 어긋난 변수명 수정 kakao_account -> kakaoAccount * FU-54 refactor: yaml파일 환경변수명 수정 * FU-54 feat: aws, cognito 환경변수 바인딩 용 properties 클래스 생성 * FU-54 refactor: @Autowired 어노테이션 제거 생성자가 하나밖에 없기 때문에 어노테이션을 생략하였음 * FU-54 refactor: registerUserPool 메서드 리팩토링 * FU-54 feat: cognito 토큰 발급 API 구현 cognito 유저 풀에 등록된 유저의 인증 과정을 거쳐 엑세스 토큰 및 리프레시 토큰을 발행하는 메서드를 구현하였음 * FU-54 refactor: cognito 등록 및 토큰 발행 절차를 successHandler에서 처리하도록 수정 기존 코드에서는 카카오에서 사용자 정보를 가져오는 시점에 cognito 유저 풀에 등록하고 토큰을 발행했음. 하지만 이때 토큰을 발행하게 되면 인증이 끝나고 redirect 시키는 시점에서 accessToken, refreshToken을 쿠키에 세팅하기 위해 토큰을 다시 얻어오는 등 유사한 작업을 반복해야하므로 수행 시점을 리팩토링하게 되었음. * FU-54 feat: cognito 유저풀에 등록하기 전에 등록 여부 검증하는 절차 추가 더불어 메서드 추출 리팩토링도 함께 수행함 * FU-54 feat: 로그인 인증 후 responseCookie 생성하여 리다이렉트 로직 추가 로그인 인증을 성공적으로 수행한 뒤, successHandler에서 토큰을 쿠키에 담아 리다이렉트 시키는 로직을 추가하였음 * FU-54 refactor: 인증 관련 클래스를 auth 패키지 하위로 이동 * FU-54 refactor: 패키지명 및 구조 변경 handler를 config에 통합시키고, entity 대신 model이라는 패키지명을 사용함 * FU-54 feat: Cognito 의존성 및 코드 삭제 Cognito에서 생성한 jwt 토큰을 validate하는 API가 별도로 존재하지 않고, payload를 커스텀 하기 어렵다는 이슈가 있음. * FU-54 chore: jjwt dependency 추가 - 토큰 생성 및 검증을 위한 라이브러리 * FU-54 feat: jwt 관련 모델 구현 * FU-54 feat: 토큰 생성 로직 구현 * FU-54 feat: 리프레시 토큰 저장 로직 구현 * FU-54 feat: JwtAuthenticationFilter 설정 클라이언트 요청 시 JwtAuthenticationFilter를 먼저 수행해 jwt 기반 인증을 처리할 수 있도록 함 * FU-54 feat: 토큰 검증 로직 구현 * FU-54 feat: 요청 토큰으로부터 인증 객체 생성 엑세스토큰에서 페이로드 파싱하여 인증객체를 만들고, SecurityContext에 인증객체를 저장해 전역적으로 사용할 수 있도록 함 * FU-54 feat: 배포 테스트를 위해 로그인 후 리다이렉트 설정 변경 * FU-54 feat: cookie maxAge 수정 * FU-54 fix: 테스트 yaml -> yml 확장자 수정 테스트 PR Conflict로 파일명 수정함 * FU-54 refactor: UserDetailsServiceImpl 클래스명 수정 * FU-54 feat: ROLE 타입 변경 및 추가 - 기존에 회원가입한 유저를 ROLE_USER로만 구분하던 것을 세가지 분류로 나누었음. - ROLE_PENDING: 회원타입이 저장되기 전의 상태로, 최초 로그인 성공 후에� 일시적으로 해당 권한을 가짐 * FU-54 feat: OAuth2User 커스텀 - http request시, OAuth2User 객체에 저장된 authority가 security config의 requestMatcher에서 지정한 권한과 일치하는지 확인하는 과정을 거치게됨. - 기존 코드에서는 OAuth2User객체를 커스텀없이 구현하여 authority에 카카오에서 받아온 scope 정보만 저장되어 있었음. - 따라서 authority를 ROLE_PENDING으로 지정하기 위해 해당 객체를 커스텀하게 구현하였음. * FU-54 fix: principal name cannot be empty 에러 해결 * FU-54 fix: CI 테스트 코드 실패 에러 수정 ROLE_USER가 사라짐에 따라 테스트 코드에도 변경사항을 반영하였음 * FU-54 feat: 로그 레벨 debug로 설정 * FU-54 fix: 환경변수명 수정 * FU-54 chore: 코드 위치 변경 * FU-54 feat: actuator 의존성 추가 * FU-54 feat: 쿼리스트링 방식으로 토큰 전송 * FU-54 refactor: redirect URL 수정 * FU-54 feat: 요청 헤더에서 토큰 추출 및 검증 API 요청이 들어올때마다 JwtAuthenticationFilter에서 Authorization 헤더에 담긴 엑세스 토큰을 꺼내와 검증함 * FU-54 refactor: ROLE enum 상수의 prefix 제거 * FU-54 feat: 로그인 성공 직후 회원타입 업데이트 API 구현 * FU-54 fix: casting 에러 수정 에러 메시지: Cannot convert existing claim value of type 'class java.lang.Long' to desired type 'class java.lang.String'. JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. Anything more complex is expected to be already converted to your desired type by the JSON Deserializer implementation. You may specify a custom Deserializer for a JwtParser with the desired conversion configuration via the JwtParserBuilder.deserializer() method. See https://github.com/jwtk/jjwt#custom-json-processor for more information. If using Jackson, you can specify custom claim POJO types as described in https://github.com/jwtk/jjwt#json-jackson-custom-types * FU-54 refactor: indent 설정 tab->space 변경 * FU-54 feat: base url 환경변수 추가 * FU-54 fix: shouldNotFilter 적용 안되는 문제 해결 /login/type 요청 시 jwtAuthenticationFilter가 적용되지 않는 문제가 있었음. 이는 shouldNotFilter에서 요청경로에 /login이 포함되는 경우에 적용이 제외되도록 설정되어있었기 때문인데, startsWith -> contains로 수정하여 해결함. * FU-54 fix: CI 동작 시 테스트코드 실행 실패 에러 수정 * FU-54 fix: RoleTypeRequest 변수명 수정 userType -> roleType * FU-54 feat: member <-> profile 일대일 연관관게 매핑 * FU-54 feat: 회원가입 로직에 사진작가측 고유 URL 생성 및 반환하는 로직 추가 * FU-54 refactor: jwt 패키지 분리 * FU-54 feat: JWT 예외처리 필터 등록 JwtAuthenticationFilter 앞단에 JwtExceptionFilter를 둬서 JwtAuthenticationFilter에서 토큰 검증 중에 예외가 발생하면 앞단으로 예외를 던지도록 처리하였음 * FU-54 refactor: CustomOauth2User, CustomUserDetails 클래스 통합 - Authentication 객체의 두 타입(oauth2User, userDetilas)을 하나로 묶어서 관리하고자 함 - 추가로 멤버 조회, 저장 등의 로직에서 카카오 아이디가 아닌 멤버 고유 아이디를 활용하도록 수정함 * FU-54 feat: 리프레시 토큰 저장 시 기존의 토큰 삭제 후 저장 * FU-54 fix: 서버 재부팅 시 secretKey가 달라지는 문제 해결 기존의 코드에서 서버 재부팅마다 secret key가 달라져 토큰 claim을 parsing할때 SignatureMismatch exception이 발생하는 문제가 있었음. * FU-54 feat: 토큰 재발행 API 구현 * FU-54 feat: 로그인 과정 예외처리 추가 * FU-54 refactor: 클래스명, 메서드명, 코드 일부 리팩토링 * FU-54 feat: member-profile 단방향 매핑으로 변경 * FU-54 fix: 불필요한 코드 삭제 및 임시 코드 수정 * FU-54 fix: 메서드명 수정 후 메서드 추출 * FU-54 feat: 인증필터에서 토큰 재발행 경로 제외
- Loading branch information
Showing
38 changed files
with
947 additions
and
169 deletions.
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
32 changes: 32 additions & 0 deletions
32
src/main/java/com/foru/freebe/auth/controller/AuthController.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,32 @@ | ||
package com.foru.freebe.auth.controller; | ||
|
||
import org.springframework.http.HttpStatusCode; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.util.LinkedMultiValueMap; | ||
import org.springframework.util.MultiValueMap; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
import com.foru.freebe.jwt.model.JwtTokenModel; | ||
import com.foru.freebe.jwt.service.JwtService; | ||
|
||
import jakarta.servlet.http.HttpServletRequest; | ||
import lombok.RequiredArgsConstructor; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
public class AuthController { | ||
private final JwtService jwtService; | ||
|
||
@PostMapping("/reissue") | ||
public ResponseEntity<Void> reissueRefreshToken(HttpServletRequest request) { | ||
String refreshToken = request.getHeader("refreshToken"); | ||
|
||
JwtTokenModel token = jwtService.reissueRefreshToken(refreshToken); | ||
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); | ||
headers.add("accessToken", token.getAccessToken()); | ||
headers.add("refreshToken", token.getRefreshToken()); | ||
|
||
return new ResponseEntity<>(headers, HttpStatusCode.valueOf(200)); | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
src/main/java/com/foru/freebe/auth/dto/RoleTypeRequest.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,19 @@ | ||
package com.foru.freebe.auth.dto; | ||
|
||
import com.foru.freebe.member.entity.Role; | ||
|
||
import jakarta.persistence.EnumType; | ||
import jakarta.persistence.Enumerated; | ||
import jakarta.validation.constraints.NotNull; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class RoleTypeRequest { | ||
@Enumerated(EnumType.STRING) | ||
@NotNull | ||
private String roleType; | ||
|
||
public Role getRole() { | ||
return Role.valueOf(roleType.toUpperCase()); | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
src/main/java/com/foru/freebe/auth/model/CustomUserDetails.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,77 @@ | ||
package com.foru.freebe.auth.model; | ||
|
||
import java.util.Collection; | ||
import java.util.Collections; | ||
import java.util.Map; | ||
|
||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.oauth2.core.user.OAuth2User; | ||
|
||
import com.foru.freebe.member.entity.Member; | ||
|
||
import lombok.Getter; | ||
|
||
@Getter | ||
public class CustomUserDetails implements UserDetails, OAuth2User { | ||
private final Member member; | ||
private final Collection<? extends GrantedAuthority> authorities; | ||
private Map<String, Object> attributes; | ||
|
||
public CustomUserDetails(Member member) { | ||
this.member = member; | ||
this.authorities = Collections.singletonList(new SimpleGrantedAuthority(member.getAuthority())); | ||
} | ||
|
||
public CustomUserDetails(Member member, Map<String, Object> attributes) { | ||
this.member = member; | ||
this.authorities = Collections.singletonList(new SimpleGrantedAuthority(member.getAuthority())); | ||
this.attributes = attributes; | ||
} | ||
|
||
@Override | ||
public Map<String, Object> getAttributes() { | ||
return attributes; | ||
} | ||
|
||
@Override | ||
public Collection<? extends GrantedAuthority> getAuthorities() { | ||
return authorities; | ||
} | ||
|
||
public Long getMemberId() { | ||
return member.getId(); | ||
} | ||
|
||
/** | ||
* 필수 오버라이드 메서드입니다. | ||
* @return 빈 문자열을 리턴합니다. | ||
* @deprecated 사용하지 말아주세요. | ||
*/ | ||
@Deprecated | ||
@Override | ||
public String getPassword() { | ||
return ""; | ||
} | ||
|
||
/** | ||
* 필수 오버라이드 메서드입니다. 인증 객체 로드 시 사용됩니다. | ||
* @deprecated getMemberId 사용을 권장합니다. | ||
*/ | ||
@Override | ||
public String getUsername() { | ||
return member.getId().toString(); | ||
} | ||
|
||
/** | ||
* 필수 오버라이드 메서드입니다. | ||
* @return memberId를 리턴합니다. | ||
* @deprecated getMemberId 사용을 권장합니다. | ||
*/ | ||
@Deprecated | ||
@Override | ||
public String getName() { | ||
return member.getId().toString(); | ||
} | ||
} |
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,40 @@ | ||
package com.foru.freebe.auth.model; | ||
|
||
import java.util.Collection; | ||
import java.util.Map; | ||
|
||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.oauth2.core.user.OAuth2User; | ||
|
||
import lombok.Getter; | ||
|
||
@Getter | ||
public class KakaoUser { | ||
private final Map<String, Object> attributes; | ||
private final Map<String, Object> kakaoAccount; | ||
private final Collection<? extends GrantedAuthority> authorities; | ||
private final Long kakaoId; | ||
|
||
public KakaoUser(OAuth2User oAuth2User) { | ||
this.attributes = oAuth2User.getAttributes(); | ||
this.kakaoAccount = (Map<String, Object>)attributes.get("kakao_account"); | ||
this.authorities = oAuth2User.getAuthorities(); | ||
this.kakaoId = Long.valueOf(oAuth2User.getName()); | ||
} | ||
|
||
public String getUserName() { | ||
return (String)kakaoAccount.get("name"); | ||
} | ||
|
||
public String getEmail() { | ||
return (String)kakaoAccount.get("email"); | ||
} | ||
|
||
public String getPhoneNumber() { | ||
return (String)kakaoAccount.get("phone_number"); | ||
} | ||
|
||
public Integer getBirthYear() { | ||
return (Integer)kakaoAccount.get("birth_year"); | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
src/main/java/com/foru/freebe/auth/model/MemberAdapter.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,24 @@ | ||
package com.foru.freebe.auth.model; | ||
|
||
import java.util.Map; | ||
|
||
import com.foru.freebe.member.entity.Member; | ||
|
||
import lombok.Getter; | ||
|
||
@Getter | ||
public class MemberAdapter extends CustomUserDetails { | ||
private final Member member; | ||
private Map<String, Object> attributes; | ||
|
||
public MemberAdapter(Member member) { | ||
super(member); | ||
this.member = member; | ||
} | ||
|
||
public MemberAdapter(Member member, Map<String, Object> attributes) { | ||
super(member, attributes); | ||
this.member = member; | ||
this.attributes = attributes; | ||
} | ||
} |
32 changes: 32 additions & 0 deletions
32
src/main/java/com/foru/freebe/auth/service/CustomOAuth2UserService.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,32 @@ | ||
package com.foru.freebe.auth.service; | ||
|
||
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; | ||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; | ||
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; | ||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException; | ||
import org.springframework.security.oauth2.core.user.OAuth2User; | ||
import org.springframework.stereotype.Service; | ||
|
||
import com.foru.freebe.auth.model.KakaoUser; | ||
import com.foru.freebe.auth.model.MemberAdapter; | ||
import com.foru.freebe.member.entity.Member; | ||
import com.foru.freebe.member.service.MemberService; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> { | ||
private final MemberService memberService; | ||
|
||
@Override | ||
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { | ||
OAuth2UserService<OAuth2UserRequest, OAuth2User> oAuth2UserService = new DefaultOAuth2UserService(); | ||
OAuth2User oAuth2User = oAuth2UserService.loadUser(userRequest); | ||
|
||
KakaoUser kakaoUser = new KakaoUser(oAuth2User); | ||
Member member = memberService.findOrRegisterMember(kakaoUser); | ||
|
||
return new MemberAdapter(member, kakaoUser.getAttributes()); | ||
} | ||
} |
30 changes: 30 additions & 0 deletions
30
src/main/java/com/foru/freebe/auth/service/CustomUserDetailsService.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,30 @@ | ||
package com.foru.freebe.auth.service; | ||
|
||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
import org.springframework.stereotype.Service; | ||
|
||
import com.foru.freebe.auth.model.CustomUserDetails; | ||
import com.foru.freebe.auth.model.MemberAdapter; | ||
import com.foru.freebe.errors.errorcode.CommonErrorCode; | ||
import com.foru.freebe.errors.exception.RestApiException; | ||
import com.foru.freebe.member.entity.Member; | ||
import com.foru.freebe.member.repository.MemberRepository; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
|
||
@RequiredArgsConstructor | ||
@Service | ||
public class CustomUserDetailsService implements UserDetailsService { | ||
private final MemberRepository memberRepository; | ||
|
||
@Override | ||
public CustomUserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | ||
Long id = Long.valueOf(username); | ||
Member member = memberRepository.findById(id) | ||
.orElseThrow(() -> new RestApiException(CommonErrorCode.RESOURCE_NOT_FOUND)); | ||
|
||
return new MemberAdapter(member); | ||
} | ||
} | ||
|
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 |
---|---|---|
|
@@ -16,4 +16,4 @@ public class ApiResponse<T> { | |
private int status; | ||
private String message; | ||
private T data; | ||
} | ||
} |
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 com.foru.freebe.config; | ||
|
||
import static org.springframework.security.config.Customizer.*; | ||
|
||
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 com.foru.freebe.jwt.filter.JwtAuthenticationFilter; | ||
import com.foru.freebe.jwt.filter.JwtExceptionFilter; | ||
import com.foru.freebe.jwt.handler.CustomAuthenticationSuccessHandler; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
|
||
@Configuration | ||
@RequiredArgsConstructor | ||
@EnableWebSecurity | ||
public class SecurityConfig { | ||
private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; | ||
private final JwtAuthenticationFilter jwtAuthenticationFilter; | ||
private final JwtExceptionFilter jwtExceptionFilter; | ||
|
||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
http | ||
.csrf(AbstractHttpConfigurer::disable) | ||
.cors(withDefaults()) | ||
.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
|
||
.authorizeHttpRequests((request) -> request | ||
.requestMatchers("/photographer").hasAnyRole("PHOTOGRAPHER") | ||
.requestMatchers("/admin").hasAnyRole("ADMIN") | ||
.anyRequest().permitAll()) | ||
|
||
.oauth2Login((oauth2) -> oauth2 | ||
.successHandler(customAuthenticationSuccessHandler) | ||
.failureUrl("/")) | ||
|
||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) | ||
.addFilterBefore(jwtExceptionFilter, JwtAuthenticationFilter.class); | ||
return http.build(); | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
src/main/java/com/foru/freebe/errors/errorcode/JwtErrorCode.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,14 @@ | ||
package com.foru.freebe.errors.errorcode; | ||
|
||
import lombok.Getter; | ||
import lombok.RequiredArgsConstructor; | ||
|
||
@Getter | ||
@RequiredArgsConstructor | ||
public enum JwtErrorCode implements ErrorCode { | ||
EXPIRED_TOKEN(401, "Expired token"), | ||
INVALID_TOKEN(400, "Invalid token"); | ||
|
||
private final int httpStatus; | ||
private final String message; | ||
} |
21 changes: 21 additions & 0 deletions
21
src/main/java/com/foru/freebe/errors/exception/JwtTokenException.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,21 @@ | ||
package com.foru.freebe.errors.exception; | ||
|
||
import com.foru.freebe.errors.errorcode.ErrorCode; | ||
|
||
import lombok.Getter; | ||
import lombok.RequiredArgsConstructor; | ||
|
||
@Getter | ||
@RequiredArgsConstructor | ||
public class JwtTokenException extends RuntimeException { | ||
private final ErrorCode errorCode; | ||
|
||
@Override | ||
public String getMessage() { | ||
return errorCode.getMessage(); | ||
} | ||
|
||
public int getHttpStatus() { | ||
return errorCode.getHttpStatus(); | ||
} | ||
} |
Oops, something went wrong.