JAVA Mybatis Logout(로그아웃)(1)

2024. 12. 20. 12:29·Project/STOOCK

현재 로그인 기능이 어느정도 만들어졌는데 아직 로그아웃 기능이 구현되지않았다.

 

그에 따라 로그아웃 기능을 만들어 볼려고 한다.

 

우선 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
'Project/STOOCK' 카테고리의 다른 글
  • JAVA Mybatis 사용자 검증
  • JAVA Mybatis Logout(로그아웃)(2) OPTIONS, CORS
  • JAVA Mybatis FormLogin Password변경(2)
  • JAVA Mybatis FormLogin Password변경(1)
hankyungtory
hankyungtory
기록이 정답이다.
  • hankyungtory
    한경이의 개발 일지
    hankyungtory
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Study
        • Java
        • DataBase
        • Error
        • Linux
      • Project
        • STOOCK
        • BackOffice
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      springboot
      스프링부트
      servlet
      개발
      war
      container
      build
      서블릿
      에러
      wrapper
      폼로그인
      서블릿컨테이너
      spring
      server
      spring boot
      WAS
      SecurityConfig
      tomcat
      SMTP
      내장톰캣
      jwt
      컨테이너
      서버
      error
      톰캣
      react
      java
      mybatis
      자바
      소셜로그인
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.3
    hankyungtory
    JAVA Mybatis Logout(로그아웃)(1)
    상단으로

    티스토리툴바