현재 로그인 기능이 어느정도 만들어졌는데 아직 로그아웃 기능이 구현되지않았다.
그에 따라 로그아웃 기능을 만들어 볼려고 한다.
우선 JWT 토큰 방식이기때문에 헤더에 Authorization 에 AccessToken을 무효화 해주면 된다.
User.xml
우선 해당 유저의 AccessToken을 null로 바꿔주는 쿼리를 작성했다.
UserMapper
UserService
xml과 Mapper에 연결한 invalidateAccessToken 을 UserService에서 가져와서 사용
UserController
컨트롤러에서 Map 형식으로 @RequestHeader에 Authorization Key에 token에 AccessToken을 담아서 전송한다.
기본적으로 Bearer형식이기때문에 Key값에 Bearer가 붙는다. 그래서 Bearer를 제거해주는 로직을 적어준다.
이렇게 되면 해당 토큰 값만 전송되는데 현재 테스트 단계이지만 서버에서 요청이 안되는것같다...
인텔리제이 콘솔창에 System.out.println이 뜨질 않는다.. 어디서부터 문제인것인가...
SecurityConfig
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@MapperScan("com.example.user.mapper")
@CrossOrigin(origins = "http://localhost:3000")
public class SecurityConfig {
private final BCryptPasswordEncoder bCryptPasswordEncoder;
private final UserMapper userMapper;
private final FormUserMapper formUserMapper;
private final JwtUtils jwtUtils;
private final UserService userService;
private final AuthenticationConfiguration authenticationConfiguration; // AuthenticationConfiguration 주입
// AuthenticationManager 빈 등록
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
// CORS 설정을 위한 CorsConfigurationSource 빈 등록
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:3000"); // 허용할 오리진
corsConfiguration.addAllowedMethod("*"); // 모든 HTTP 메서드 허용
corsConfiguration.addAllowedHeader("*"); // 모든 헤더 허용
corsConfiguration.setAllowCredentials(true); // 자격 증명 허용
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration); // 모든 경로에 CORS 설정 적용
return source;
}
// SecurityFilterChain 정의
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// JwtAuthenticationFilter를 SecurityFilterChain 내부에서 직접 생성
JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager(), userMapper, formUserMapper, jwtUtils);
return http.csrf(csrf -> csrf.disable())
.cors(cors -> cors.configurationSource(corsConfigurationSource())) // CORS 설정을 별도로 관리
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeRequests(auth -> auth
.requestMatchers( "/formuser", "/api/kakao-token", "/socialuser").permitAll()
.anyRequest().authenticated())
.logout(logout -> logout
.logoutUrl("/logout") // 로그아웃 URL
.clearAuthentication(true) // 인증 정보 삭제
.invalidateHttpSession(true) // 세션 무효화
.deleteCookies("JSESSIONID") // 쿠키 삭제
.logoutSuccessHandler((request, response, authentication) -> {
// 리디렉션 없이 로그아웃 후 특별한 처리를 하지 않도록 설정
response.setStatus(HttpServletResponse.SC_OK); // HTTP 200 OK 응답만 전송
})
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
// AuthenticationProvider 빈 등록
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(bCryptPasswordEncoder);
return authProvider;
}
// UserDetailsService 빈 등록
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService(userMapper, formUserMapper);
}
}
아직은 구현중이라 로그인, 로그아웃등등 모든 경로를 열어둔 상태이다.
PostMan
포스트맨에 해당 Key, Value값을 넣고 Send를 누르면 200ok가 되면서 1이 뜬다.
그렇지만? 디비의 값은 변경이 안된다. 어디서부터 잘못된 것인지 차차 찾아가면서 수정을 해야겠다.
오늘은 여기까지,,
'Project > STOOCK' 카테고리의 다른 글
JAVA Mybatis 사용자 검증 (0) | 2025.01.03 |
---|---|
JAVA Mybatis Logout(로그아웃)(2) OPTIONS, CORS (0) | 2024.12.21 |
JAVA Mybatis FormLogin Password변경(2) (0) | 2024.12.19 |
JAVA Mybatis FormLogin Password변경(1) (1) | 2024.12.18 |
JAVA [Spring Boot] KaKao 소셜로그인 + 토큰발급 (2) | 2024.12.11 |