• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Spring 게시판 Authentication auth가 null값을 가짐

Authentication auth가 null값을 가짐

  • 이 주제에는 2개 답변, 2명 참여가 있으며 니리8 월, 1 주 전에 전에 마지막으로 업데이트했습니다.
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 글쓴이
  • #131509

    니리
    참가자
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
        @Bean
        public BCryptPasswordEncoder bCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.csrf(AbstractHttpConfigurer::disable);
            http.addFilterBefore(new JwtFilter(), ExceptionTranslationFilter.class);
            http.sessionManagement((session)->session
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS));
            http.cors(cors->cors.configurationSource(corsConfigurationSource()));
            http.formLogin(AbstractHttpConfigurer::disable);
            http.httpBasic(AbstractHttpConfigurer::disable);
            http.authorizeHttpRequests(auth->auth.requestMatchers("/**").permitAll()
                    .anyRequest().authenticated());
    
    
            return http.build();
        }
        @Bean
        public CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173")); // React 개발 서버 주소
            configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
            configuration.setAllowedHeaders(Arrays.asList("*"));
            configuration.addAllowedOrigin("http://localhost:5173");
            configuration.setAllowCredentials(true); // 자격 증명(쿠키 등) 허용
            // 모든 경로에 대해 설정 적용
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }
    
    public class JwtFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain filterChain)
                throws ServletException, IOException {
            Cookie[] cookies = request.getCookies();
    
    
            if (cookies == null) {
                filterChain.doFilter(request, response);
                return;
            }
            var jwtCookie = "";
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("jwt")) {
                    jwtCookie = cookie.getValue();
                }
            }
            System.out.println("check token: "+jwtCookie);
            Claims claim;
            try{
                claim = JwtUtil.extractToken(jwtCookie);
                System.out.println("claim: "+claim);
            }catch (Exception e) {
                filterChain.doFilter(request, response);
                return;
            }
            var arr = claim.get("authorities").toString().split(",");
            var authorities = Arrays.stream(arr).map(a->new SimpleGrantedAuthority(a)).toList();
            var customUser = new CustomUser(
                    claim.get("username").toString(),
                    "none",
                    authorities
            );
            customUser.userIdx = claim.get("userIdx").toString();
            customUser.userEmail = claim.get("userEmail").toString();
            var authToken = new UsernamePasswordAuthenticationToken(
                    customUser,"NONE_PROVIDED"
            );
            System.out.println("authToken: "+authToken);
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            System.out.println("authToken details: "+authToken);
            SecurityContextHolder.getContext().setAuthentication(authToken);
            filterChain.doFilter(request, response);
        }
    }
    결과
    token: eyJhbGciOiJIUzM4NCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJ1c2VyRW1haWwiOiJ0ZXN0QHRlc3QuY29tIiwidXNlcklkeCI6IjEiLCJhdXRob3JpdGllcyI6IlVTRVIiLCJpYXQiOjE3MjkyOTA2NzksImV4cCI6MTcyOTI5MTI3OX0.koXxfmxpVFQqRjzrp_gorvOfPPyC0WZ-QcETUdrU0cR6P3ok3V9JaIIx3kI4LOoo
    
    check token: eyJhbGciOiJIUzM4NCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJ1c2VyRW1haWwiOiJ0ZXN0QHRlc3QuY29tIiwidXNlcklkeCI6IjEiLCJhdXRob3JpdGllcyI6IlVTRVIiLCJpYXQiOjE3MjkyOTA2NzksImV4cCI6MTcyOTI5MTI3OX0.koXxfmxpVFQqRjzrp_gorvOfPPyC0WZ-QcETUdrU0cR6P3ok3V9JaIIx3kI4LOoo
    
    claim: {username=test, userEmail=test@test.com, userIdx=1, authorities=USER, iat=1729290679, exp=1729291279}
    
    authToken: UsernamePasswordAuthenticationToken [Principal=com.muneo.dealwith.Jwt.CustomUser [Username=test, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[USER]], Credentials=[PROTECTED], Authenticated=false, Details=null, Granted Authorities=[]]
    
    토큰 유효기간 검사를 하려는데 프론트에서 토큰은 잘 넘어가는데 auth가 null인지 모르겠어요ㅠ
    #131510

    codingapple
    키 마스터
    서버로 요청할 때 
    SecurityContextHolder.getContext().setAuthentication(authToken);
    이거도 잘 실행되나 주변에서 아무거나 출력해봅시다
    #131518

    니리
    참가자
     
    해결을 하긴했는데 authToken의 반환 값이 달라서 그렇다는데 사실 잘모르겠습니다
    List<SimpleGrantedAuthority> authorities = Arrays.stream(claim.get("authorities").toString().split(","))
            .map(SimpleGrantedAuthority::new)
            .toList();
    var customUser = new CustomUser(
            claim.get("username").toString(),
            "none",
            authorities
    );
    customUser.userEmail = claim.get("userEmail").toString();
    customUser.nickName = claim.get("nickName").toString();
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
            customUser,null,authorities
    );
    System.out.println("authToken: "+authToken);
    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
    System.out.println("authToken details: "+authToken);
    SecurityContextHolder.getContext().setAuthentication(authToken);
    filterChain.doFilter(request, response);
    요렇게 하니까 잘 나옵니다
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠