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

home2 게시판 Spring 게시판 JWT 사용 시 auth 변수 null

JWT 사용 시 auth 변수 null

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

    서다솔
    참가자
    auth 변수는 null로 나오고 SecurityContextHolder에서 불러오면 출력이 잘 됩니다..
    auth는 왜 null로 나오는걸까요?ㅠㅠ
    
    -------------- controller --------------------------------
    @GetMapping("/my-page/jwt")
    @ResponseBody
    String mypageJWT(Authentication auth){
        System.out.println(SecurityContextHolder.getContext().getAuthentication());
        if (auth == null) auth = SecurityContextHolder.getContext().getAuthentication();
        CustomUser user = (CustomUser) auth.getPrincipal();
        System.out.println(user);
        System.out.println(user.getDisplayName());
        System.out.println(user.getAuthorities());
    return "mypage.html";
    }
    
    ------------ filter ----------------------
    
    @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 (int i = 0; i < cookies.length; i++){
                if (cookies[i].getName().equals("jwt")){
                    jwtCookie = cookies[i].getValue();
                }
            }
            Claims claim;
            try {
                claim = JwtUtil.extractToken(jwtCookie);
            } catch (Exception e) {
                filterChain.doFilter(request, response);
                return;
            }
            CustomUser customUser = new CustomUser(claim.get("username").toString()
                    , ""
                    , Arrays.stream(claim.get("authorities").toString().split(",")).map(x -> new SimpleGrantedAuthority(x)).toList() //authorities
                    );
            customUser.setDisplayName(claim.get("displayName").toString());
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(customUser, "" );
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authToken);
    //        System.out.println(SecurityContextHolder.getContext().getAuthentication());
            filterChain.doFilter(request, response);
        }
    #134405

    codingapple
    키 마스터
    Authentication을 import해오는 경로가 뭔가 이상한걸수도요
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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