inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

173만명의 커뮤니티!! 함께 토론해봐요.

TypeError: Cannot read properties of undefined (reading 'map')에 대한 문제

미해결

코드로 배우는 React 19 with 스프링부트 API서버

크롬에서의 문제입니다 웹스톰 내에서는 또 다른 문제가 있다고 하네용 import { useEffect, useState } from "react"; import { getList } from "../../api/productsApi"; import useCustomMove from "../../hooks/useCustomMove"; import FetchingModal from "../common/FetchingModal"; import { API_SERVER_HOST } from "../../api/todoApi"; import PageComponent from "../common/PageComponent"; import useCustomLogin from "../../hooks/useCustomLogin"; const host = API_SERVER_HOST const initState= { dtoList:[], pageNumList:[], pageRequestDTO: null, prev: false, next: false, totalCount: 0, prevPage: 0, nextPage: 0, totalPage: 0, current: 0 } const ListComponent = (props) => { const {page, size, refresh, moveToList, moveToRead} = useCustomMove() const {exceptionHandle} = useCustomLogin() //serverData는 나중에 사용 const [serverData, setServerData] = useState(initState) //for FetchingModal const [fetching, setFetching] = useState(false) useEffect(() => { setFetching(true) getList({page,size}).then(data => { console.log(data); if(data && data.dtoList){ setServerData(data); } setFetching(false); }).catch( err => exceptionHandle(err)) }, [page,size, refresh]) return ( <div className={"border-2 border-blue-100 mt-10 mr-2 ml-2"}> {fetching ? <FetchingModal/> :<></>} <div className="flex flex-wrap mx-auto p-6"> {serverData.dtoList && serverData.dtoList.map(product => <div key= {product.pno} className="w-1/2 p-1 rounded shadow-md border-2" onClick={() => moveToRead(product.pno)} > <div className="flex flex-col h-full"> <div className="font-extrabold text-2xl p-2 w-full "> {product.pno} </div> <div className="text-1xl m-1 p-2 w-full flex flex-col"> <div className="w-full overflow-hidden "> <img alt="product" className="m-auto rounded-md w-60" src={`${host}/api/products/view/s_${product.uploadFileNames[0]}`}/> </div> <div className="bottom-0 font-extrabold bg-white"> <div className="text-center p-1"> 이름: {product.pname} </div> <div className="text-center p-1"> 가격: {product.price} </div> </div> </div> </div> </div> )} </div> <PageComponent serverData={serverData} movePage={moveToList}></PageComponent> </div> ); } export default ListComponent; Listcomponent에 문제가 있다고 해서 찾아보려고 하는데 어떻게 봐도 모르겠습니다ㅜㅜ 누구든 도와주세요

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
이수빈 댓글 3 좋아요 0 조회수 436

소셜로그인시 이메일 중복 관련 처리 문의

미해결

코드로 배우는 React 19 with 스프링부트 API서버

소셜로그인 강의까지 봤는데요, 강의에 있는 프로세스는 소셜로그인시 이메일을 가져와서 DB에 저장이 되어있지 않으면 카카오이메일로 회원가입을 시키고, DB에 저장이 되어있으면 비밀번호 없이 해당 계정으로 로그인이 되게끔 만드는 프로세스로 이해 했습니다. 그런데, 기존에 회원가입을 하지 않은 사람이 소셜로그인을 할 때 이미 기존에 가입되어 있는 이메일이 있다면 다른사람 계정을 비밀번호 없이 로그인 할 수 있게되는게 지금 구현한 상황에서는 맞는거죠? ex) 기존에 회원가입한 'A' 의 이메일이 test@AAA.com 일 때 신규 유입된 사람 'B'의 카카오계정 이메일이 test@AAA.com 인 경우 위와 같은 경우를 방지하려면 소셜로그인시(최초로그인) 회원가입을 시킬 때 이메일 중복체크를 하고 중복되어있다면 다른 이메일 사용을 권유 해야되는식으로 처리를 해야 하는건가요?

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
김진용 댓글 1 좋아요 0 조회수 1416

Section 8 소셜 로그인 API 서버 인코딩 관련 문의드립니다.

미해결

코드로 배우는 React 19 with 스프링부트 API서버

위 코드는 수업중 진행하신 MemberServiceImpl.java 파일의 getEmailFromKakaoAccessToken 메소드의 일부입니다. 저기에서 마지막에 bodyMap 을 로그로 확인하는 부분이 있는데 위와 같이 nickname 을 보면 인코딩이 깨져서 나옵니다. 저 nickname 을 확인하려면 어떻게 해야하나요?

  • react
  • spring-boot
  • jpa
  • jwt
김진용 댓글 1 좋아요 0 조회수 230

postman 결과가 다릅니다

해결됨

Spring Boot JWT Tutorial

1강에서 강사님께서 하신 결과는 아래와 같이 나오는데 제 결과는 아래와 같이 body 부분이 비어서 나옵니다 postman 설정문제인걸까요? 401 unauthorized라고 로그가 뜨긴하는거 같은데 json 데이터로 나오지가 않습니다.

  • spring-boot
  • jwt
fgh2585 댓글 2 좋아요 0 조회수 404

챕터 8 카카오 토큰 받기 이후

미해결

코드로 배우는 React 19 with 스프링부트 API서버

카카오 토큰 받기 이후로 많은 오류가 한번에 떠서 질문 드립니다! 부트 서버에서도 member.service, impl에 콘솔 찍은것도 에러로 인해 안뜹니다 상황마다 500오류 400오류 grant value 오류 등이 계속 뜹니다 ㅜㅜ 부트 https://github.com/hyeonbin03/IntelliJHub 일단 부트 코드는 선생님 주셨던 파일 참고해서 Member Modify 기능까지 작성 완료 된 상태입니다 리엑트 https://github.com/hyeonbin03/WebStromHub 깃 주소 남겨드겠습니다 ㅠㅠ

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
양현빈 댓글 1 좋아요 0 조회수 419

jwt 10분 유효기간 끝나면 apiServer 쪽에서 Expired Exception 발생

미해결

코드로 배우는 React 19 with 스프링부트 API서버

jwt 10분 유효기간 끝난 상황에서 jwtAxios를 이용해서 products 를 호출하면 JWTCheckFilter를 걸쳐서 validateToken 메서드를 호출하고 거기서 Exired Exception 이 납니다. accessToken 이 유효시간(10분)이 경과하였으면 refreshToken 으로 교체되는 걸로 강의내용을 인지했었는데요. 제가 어디서 놓친건지 잘 모르겠네요 ㅠ react쪽에서 beforeReq 쪽에서 결국 expired 처리가되고 brforeRes 에서 뭔가 유효기간이 끝났으면 /api/member/refresh 를 호출해야될 것 같은데 예제 소스 잘 따라한거 filter에서 먼저 유효기간이 만료되어 exception 부터 호출되어 더이상 진행이 안되네요. 어디가 정확히 문제인지 모르겠네요. jwtUtil.js 는 제공해주신 소스는 오타가 있을까봐 동일하게 ctrl+c , v 도 했습니다. JWTUtil.java 일부분 public static Map<String, Object> validateToken(String token) { Map<String, Object> claim = null; try { SecretKey key = Keys.hmacShaKeyFor(JWTUtil.key.getBytes("UTF-8")); claim = Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token) // 파싱 및 검증, 실패 시 에러 .getBody(); } catch (MalformedJwtException malformedJwtException) { throw new CustomJWTException("MalFormed"); } catch (ExpiredJwtException expiredJwtException) { throw new CustomJWTException("Expired"); } catch (InvalidClaimException invalidClaimException) { throw new CustomJWTException("Invalid"); } catch (JwtException jwtException) { throw new CustomJWTException("JWTError"); } catch (Exception e) { throw new CustomJWTException("Error"); } return claim; }

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
이재용 댓글 3 좋아요 0 조회수 570

챕터 5 모달 처리 | Add 클릭 이후 모달창이 안떠요

미해결

코드로 배우는 React 19 with 스프링부트 API서버

모달창이 안떠서 settimeout으로 처리 하니 Modal에 result 값이 true로 적용됩니다 코드는 깃으로 올리겠습니다 선생님 강의에 올라와있는 ch06 파일 코드 넣어서 해봐도 모달창이 안뜨네요 ㅜㅜ https://github.com/hyeonbin03/webstromhub

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
양현빈 댓글 4 좋아요 0 조회수 431

react-redux install 이 안되네요 ...

미해결

코드로 배우는 React 19 with 스프링부트 API서버

Module not found: Error: Can't resolve 'react-redux' ... 이런 에러문구가 나오는데 계속 랜더링 오류가 납니다... 다음 추가 한일 1) npm i 2) node_modules 제거 후 다시 npm i

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
코딩도니 댓글 1 좋아요 0 조회수 430

Security 단원에서 Dto와 인증 서비스 강의 관련입니다

미해결

코드로 배우는 React 19 with 스프링부트 API서버

loadUserByUsername 메서드에서 username 으로 조회잘되고 조회된 MemberDto는 log 출력도 잘되는데 다음 단계에서 "Encoded password does not look like BCrypt" 라는 warn 과 함꼐 "Failed to process authentication request" 로 자격증명에 실패했다고 합니다. DB의 패스워드는 암호화 되어 잘 저장된거 확인됩니다 제가 무언가를 잘못 작성한건지 파라미터로 보낸 password 는 어디서 encode해야 하는건지 아니면 다른 문제가 있는건가요?

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
heejoonk5 댓글 5 좋아요 1 조회수 591

섹션 3 | 수정/삭제 처리 부분 질문

해결됨

코드로 배우는 React 19 with 스프링부트 API서버

delete, modify 버튼 클릭 시 오류가 생기는데 선생님 자료에서 ModifyComponent.js ModifyPage.js ResultModal.js 복사해서 사용해도 오류가 생깁니다 cmd에는 오류가 잡히지 않고 콘솔창에서만 오류가 있다고 뜹니다

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
양현빈 댓글 1 좋아요 0 조회수 300

섹션 3. JWT 관련 기능 질문입니다.

미해결

스프링부트 시큐리티 & JWT 강의

안녕하세요, 강의 잘 보고 있습니다. 이번에 JWT 관련 기능을 구현함에 있어 참고차 보게되었는데요. 시큐리티가 인터페이스화가 많이 되어있다보니 동일한 기능임에도 구현하는 사람마다 어느 필터에서 인증/인가를 구현하는 지가 차이가 있는 것 같습니다. 섹션 3 버전2 소스 기준으로 JwtAuthorizationFilter 의 경우 BasicAuthenticationFilter를 확장하여 사용하고 JwtAuthenticationFilter의 경우 UsernamePasswordAuthenticationFilter 를 확장하여 사용하고, 필터에 등록되어 있습니다. 위 2가지 필터는 공식 문서 참고에 의하면 BasicAuthenticationFilter 는 HTTP 헤더에서 토큰을 추출하여 간단히 인증을 하는 용도로, UsernamePasswordAuthenticationFilter는 폼 기반의 로그인을 처리한다고 나와 있습니다. 만약 그렇다면, 폼 로그인 없이 JWT 토큰 만으로는 BasicAuthenticationFilter를 확장하는 JwtAuthorizationFilter만 존재해도 인증 과정 상 크게 문제는 없어보이는데요. (권한 체크는 별도로 할거라 인증 과정에 넣지 않으려고 합니다.) 어떤 분은 토큰 체크하는 부분을 GenericFilterBean 또는 OncePerRequestFilter 로 구현하시는 분들도 존재하더라구요. 단순히 로그인 컨트롤러에서 JWT 토큰을 발급하고 이후 요청 필터에서 토큰 체크 및 리프레시 토큰 체크 등의 인증 처리를 한다면 어떤 필터를 구현하여 등록하는 걸 추천하시는지 개인적으로 궁금합니다. 감사합니다.

  • spring
  • spring-security
  • jwt
Chiptune 댓글 1 좋아요 0 조회수 374

react 프로젝트 설정 문제

미해결

코드로 배우는 React 19 with 스프링부트 API서버

프로젝트를 설정하고 되다가 다시 키니까 안되서 문의드립니다. 제가 java 버전이 3개 정도 설치되어 있는 데 작업할 때 17로 수정해서 쓰고 다른 것 해야 할 때 11로 바꿔서 썼다가 오늘 17로 바꿔서 쓰는 데 자바버전이 안 먹히는 것 같아서 문의 드립니다. The supplied phased action failed with an exception. A problem occurred configuring root project 'mallapi'. Could not resolve all files for configuration ':classpath'. Could not resolve org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT. Required by: project : > org.springframework.boot:org.springframework.boot.gradle.plugin:3.1.10-SNAPSHOT:20240229.214127-20 No matching variant of org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT:20240229.214127-20 was found. The consumer was configured to find a library for use during runtime, compatible with Java 11, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '8.5' but: - Variant 'apiElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a library, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component for use during compile-time, compatible with Java 17 and the consumer needed a component for use during runtime, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'javadocElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a component for use during runtime, and its dependencies declared externally: - Incompatible because this component declares documentation and the consumer needed a library - Other compatible attributes: - Doesn't say anything about its target Java version (required compatibility with Java 11) - Doesn't say anything about its elements (required them packaged as a jar) - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'mavenOptionalApiElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.1.10-SNAPSHOT declares a library, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component for use during compile-time, compatible with Java 17 and the consumer needed a component for use during runtime, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'mavenOptionalRuntimeElements' capability org.springframework.boot:spring-boot-gradle-plugin-maven-optional:3.1.10-SNAPSHOT declares a library for use during runtime, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component, compatible with Java 17 and the consumer needed a component, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'runtimeElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a library for use during runtime, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component, compatible with Java 17 and the consumer needed a component, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.5') - Variant 'sourcesElements' capability org.springframework.boot:spring-boot-gradle-plugin:3.1.10-SNAPSHOT declares a component for use during runtime, and its dependencies declared externally: - Incompatible because this component declares documentation and the consumer needed a library - Other compatible attributes: - Doesn't say anything about its target Java version (required compatibility with Java 11) - Doesn't say anything about its elements (required them packaged as a jar) - Doesn't say anything about org.gradle.plugin.api-version (required '8.5')

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
wkdrns5491 댓글 1 좋아요 0 조회수 404

npm start 시 이런 오류가 발생 하는데 react를 처음 접해서 구글링 해도 해결 방안을 못찾겠습니다 ㅠㅠ

해결됨

코드로 배우는 React 19 with 스프링부트 API서버

기본적으로 터미널에 Starting the development server... 이 뜨고 페이지가 나오긴 하는데 무한 로딩이 걸립니다..그 후 로딩이 멈추면 콘솔창에 이런 오류가 발생합니다 ++기다려 보니 WebSocket connection to 'ws://localhost:3000/ws' failed: WebSocketClient @ WebSocketClient.js:13 initSocket @ socket.js:27 (anonymous) @ socket.js:51 Show 3 more frames Show less 이런 오류도 뜹니다

  • react
  • spring-boot
  • jpa
  • jwt
  • redux-toolkit
양현빈 댓글 2 좋아요 0 조회수 889

선생님 nestjs랑 Nextjs랑 같이 연동해서 작업하는거 어떻게 생각하시나요?

미해결

따라하며 배우는 NestJS

선생님 안녕하세요! 강의내용이랑 상관없는 질문이라 정말 죄송합니다..ㅜㅜ! 다만 궁금한게있어서 염치불구하고 질문드립니다.. 다름아니라, Nextjs에 자체적으로 서버 api가 있는걸로 알고있습니다. 그래서 Nextjs를 사용할때는 DB만 선정해서 작업하는식으로 해도된다고 알고있는데요.. 정말 인가요? 정말이겠지만.. 음 .. 옳은 방식인가요? 만약 제가말한 1번경우말고,Nextjs랑 Nestjs랑 같이 사용할경우 Nestjs용 서버폴더를 따로 만들고 사용하는게 나을까요? 회원가입 로직도 그럼 서버폴더에서 따로 할테고.. 그러면 넥스트js의 auth라이브러리를 따로 사용을 못하는걸까요?

  • postgresql
  • jwt
  • typeorm
  • nextjs
  • nestjs
반가우면반갑다고해 댓글 1 좋아요 0 조회수 2570

로그인 성공 이후의 경로

미해결

스프링부트 시큐리티 & JWT 강의

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 1.postman에서 /login경로로 로그인 시도를 하여 성공하였는데, 로그인 성공 이후에는 어떤 경로로 이동하게 되는건가요? 만약 리액트와 협업을 하여 로그인 기능을 구현한다면 로그인 화면에서 아이디와 비밀번호를 치고 로그인을 시도해야하는데 그 경우에는 경로를 @PostMapping("/login") public void login(User user) { } 이런식으로 해야하는건가요?

  • spring
  • spring-security
  • jwt
yso829612 댓글 1 좋아요 0 조회수 480

postman에서 authorization이 안보입니다.

미해결

jwt를 공부하던 중 JwtAuthenticationFilter에 있는 successfulAuthentication메서드에서 response.addHeader( "Authorization" , "Bearer " + jwtToken) ; 이렇게 header값에 추가를 해주었는데 postman에서 send를 해도 response의 headers쪽에 authorization라는 키값이 안보입니다... 무슨 다른 설정을 해주어야 할까요?

  • jwt
  • security
Moon Ask 댓글 1 좋아요 0 조회수 337

쌤 근데 enum 말고 type 으로 타입선언해주면안될까요?

미해결

따라하며 배우는 NestJS

export enum BoardStatus { PUBLIC = 'PUBLIC', PRIVATE = 'PRIVATE', } 이런식으로 정의를 하셨는데 이러지말고 const BoardStatus = 'PUBLIC'|'PRIVATE' 이런식의 사용은 어려운가요??

  • postgresql
  • jwt
  • nestjs
  • typeorm
반가우면반갑다고해 댓글 1 좋아요 0 조회수 639

안녕하세요 ! 질문이 있습니다.

미해결

스프링부트 시큐리티 & JWT 강의

강사님의 강의를 통해 Jwt 와 시큐리티에 대한 공부를 수월히 할 수 있었습니다. 근데 개인적으로 이제 실습하면서 문제가 발생해서 자문을 구하고자 글을 쓰게 되었습니다. 로그인이 성공하면 토큰을 로컬 스토리지에 담고, 요청할 때는 토큰을 꺼내어 헤더에 담아서 검증절차를 진행하려고 합니다. 근데 분명 위의 프로세스에 해당 하는 로직을 작성하였다고 생각하였는데, 의도한 대로 흘러가지가 않아서 매우 난처한 상황입니다. Index.html <script> $(document).ready(function() { // 로그아웃 버튼 이벤트 $('#logoutButton').click(function() { // 로컬 스토리지에서 토큰 제거 localStorage.removeItem('accessToken'); // 로그인 페이지로 리다이렉션 window.location.href = '/login'; }); // 테스트 버튼 이벤트 $('#testButton').click(function() { // 로컬 스토리지에서 토큰 가져오기 const token = localStorage.getItem('accessToken'); if (token) { $.ajax({ url: '/api/test', // 요청할 서버의 URL type: 'GET', // HTTP 메서드 beforeSend: function(xhr) { // 요청 헤더에 토큰 추가 xhr.setRequestHeader('Authorization', token); }, success: function(data) { // 요청 성공 시 로직 console.log("테스트 요청 성공:", data); alert("테스트 요청 성공"); }, error: function(xhr, status, error) { // 요청 실패 시 로직 console.error("테스트 요청 실패:", xhr.responseText); alert("테스트 요청 실패"); } }); } else { alert("토큰이 없습니다. 다시 로그인해주세요."); } }); }); </script> 이와 같이 /url/test 로 api 요청을 할때 헤더에 토큰을 담게 했습니다. 이에 "테스트 버튼"을 누르게 되면 JwtAuthorizationFilter @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException { // 헤더에서 토큰 추출 log.info("헤더에서 토큰 추출"); String tokenValue = jwtUtil.getJwtFromHeader(req); log.info("토큰 : " + tokenValue); if (StringUtils.hasText(tokenValue)) { // 토큰 유효성 검사 if (!jwtUtil.validateToken(tokenValue)) { log.info("Token Error"); return; } Claims info = jwtUtil.getUserInfoFromToken(tokenValue); try { setAuthentication(info.getSubject()); } catch (Exception e) { log.error(e.getMessage()); return; } } else { log.info("토큰이 없습니다."); } filterChain.doFilter(req, res); } // 인증 처리 public void setAuthentication(String loginId) { log.info("인증 성공"); SecurityContext context = SecurityContextHolder.createEmptyContext(); Authentication authentication = createAuthentication(loginId); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); } // 인증 객체 생성 private Authentication createAuthentication(String loginId) { log.info("인증 객체 생성"); UserDetails userDetails = userDetailsService.loadUserByUsername(loginId); return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); } 로그로 토큰이 출력되는 것과 최종적으로 인증 객체 생성까지 되는 것을 확인했습니다. 그러나 이렇게 인가 필터를 거치고 이제 컨트롤러로 접근하게 되면 @GetMapping("/api/test") public String testPage() { log.info("test controller"); return "test"; } 저기 test controller 라는 로그만 찍힌채 프로세스가 마무리됩니다. 최종로그 2024-02-26T16:19:36.394+09:00 INFO 60592 --- [nio-8081-exec-9] JWT 검증 및 인가 : 토큰 : eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0NiIsImF1dGgiOiJPV05FUiIsImlhdCI6MTcwODkzMTk3MywiZXhwIjoxNzA4OTM1NTczfQ.A2AhGDg5phTcm4gGC-01K0jKoAGE1c5Ygsq9v_J1ntk 2024-02-26T16:19:36.426+09:00 INFO 60592 --- [nio-8081-exec-9] JWT 검증 및 인가 : 인증 성공 2024-02-26T16:19:36.427+09:00 INFO 60592 --- [nio-8081-exec-9] JWT 검증 및 인가 : 인증 객체 생성 Hibernate: /* <criteria> */ select u1_0.id, u1_0.email, u1_0.login_id, u1_0.password, u1_0.role from users u1_0 where u1_0.login_id=? 2024-02-26T16:19:36.434+09:00 INFO 60592 --- [nio-8081-exec-9] TestController : test controller 이때 웹 페이지의 개발자 도구를 열어서 콘솔로그를 확인 해보면, 제가 가지고 오고자 했던 test.html 의 코드만이 적혀있을 뿐입니다. 뭐가 문제인 걸까요.. 혹시나 test 쪽에 토큰을 가져오는 로직도 작성해봤습니다. Test.html <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script> <script> $(document).ready(function () { const auth = getToken(); if (auth) { $.ajaxPrefilter(function (options, originalOptions, jqXHR) { jqXHR.setRequestHeader('Authorization', auth); }); } else { window.location.href = '/user/login-page'; } }); function getToken() { let auth = localStorage.getItem('accessToken'); return auth || ''; } </script> <title>Test Page</title> </head> <body> <h1>This is a test page.</h1> </body> </html> 그럼에도 여전히 해당 페이지에는 접근을 못하고 있습니다 ㅠㅠㅠㅠ 제가 놓친 부분이 뭐가 있을지 조언을 주신다면 감사하겠습니다.

  • spring
  • spring-security
  • jwt
오세창 댓글 2 좋아요 0 조회수 468

버튼 클릭 시 페이지가 로드되지 않는 문제 해결 방법 질문

미해결

개요 로그인 성공 후 인덱스 페이지로 넘어갑니다. 인덱스 페이지에는 "테스트 버튼" 이라는 버튼을 클릭하면, test 로드하는 api 를 호출하도록 했습니다. 그러나 api 요청만 진행되고, 페이지는 바뀌지 않습니다. 개발자도구 메시지에 해당 페이지의 html 코드만 출력됩니다. 참고자료 index.html <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <title>인덱스 페이지</title> <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script> </head> <body> <h1>환영합니다!</h1> <p>성공적으로 로그인하셨습니다.</p> <button id="logoutButton">로그아웃</button> <button id="testButton">테스트 버튼</button> <script> $(document).ready(function() { // 로그아웃 버튼 이벤트 $('#logoutButton').click(function() { // 로컬 스토리지에서 토큰 제거 localStorage.removeItem('accessToken'); // 로그인 페이지로 리다이렉션 window.location.href = '/login'; }); // 테스트 버튼 이벤트 $('#testButton').click(function() { // 로컬 스토리지에서 토큰 가져오기 const token = localStorage.getItem('accessToken'); if (token) { $.ajax({ url: '/api/test', // 요청할 서버의 URL type: 'GET', // HTTP 메서드 beforeSend: function(xhr) { // 요청 헤더에 토큰 추가 xhr.setRequestHeader('Authorization', token); }, success: function(data) { // 요청 성공 시 로직 console.log("테스트 요청 성공:", data); alert("테스트 요청 성공"); }, error: function(xhr, status, error) { // 요청 실패 시 로직 console.error("테스트 요청 실패:", xhr.responseText); alert("테스트 요청 실패"); } }); } else { alert("토큰이 없습니다. 다시 로그인해주세요."); } }); }); </script> </body> </html> 보이는 것처럼 로컬 스토리지에서 토큰을 가져온 후 요청 헤더에 다시 담아서 전송합니다. JwtAuthorizationFilter @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException { // 헤더에서 토큰 추출 log.info("헤더에서 토큰 추출"); String tokenValue = jwtUtil.getJwtFromHeader(req); log.info("토큰 : " + tokenValue); if (StringUtils.hasText(tokenValue)) { // 토큰 유효성 검사 if (!jwtUtil.validateToken(tokenValue)) { log.info("Token Error"); return; } Claims info = jwtUtil.getUserInfoFromToken(tokenValue); try { setAuthentication(info.getSubject()); } catch (Exception e) { log.error(e.getMessage()); return; } } else { log.info("토큰이 없습니다."); } filterChain.doFilter(req, res); } // 인증 처리 public void setAuthentication(String loginId) { log.info("인증 성공"); SecurityContext context = SecurityContextHolder.createEmptyContext(); Authentication authentication = createAuthentication(loginId); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); } // 인증 객체 생성 private Authentication createAuthentication(String loginId) { log.info("인증 객체 생성"); UserDetails userDetails = userDetailsService.loadUserByUsername(loginId); return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); } 이렇게 JwtAuthorizationFilter 가 있을 때 헤더에서 토큰이 추출되는 거까지 로그에 다 출력되고, 인증 객체까지 생성되는 걸 확인했습니다. Console 2024-02-26T14:31:24.699+09:00 INFO 59767 --- [nio-8081-exec-3] JWT 검증 및 인가 : 토큰 : eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0NiIsImF1dGgiOiJPV05FUiIsImlhdCI6MTcwODkyNDY0NiwiZXhwIjoxNzA4OTI4MjQ2fQ.TLjHCc1_ZtTbzGb-2c0ueLmxgCyxQf1rUQs4DkqMv_c 2024-02-26T14:31:24.706+09:00 INFO 59767 --- [nio-8081-exec-3] JWT 검증 및 인가 : 인증 성공 2024-02-26T14:31:24.706+09:00 INFO 59767 --- [nio-8081-exec-3] JWT 검증 및 인가 : 인증 객체 생성 Hibernate: /* <criteria> */ select u1_0.id, u1_0.email, u1_0.login_id, u1_0.password, u1_0.role from users u1_0 where u1_0.login_id=? 2024-02-26T14:31:24.722+09:00 INFO 59767 --- [nio-8081-exec-3] TestController : test controller 로그를 보면 test controller 를 호출하는 거까지 확인할 수 있었습니다. 그러나 페이지는 로드되지 않고, 메시지에 html 코드만 출력이 됩니다. 자료 Test.html <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script> <title>Test Page</title> </head> <body> <h1>This is a test page.</h1> </body> </html> 정리 로그인 성공 후 인덱스 페이지로 넘어감 해당 인덱스 페이지에서 test 페이지로 넘어가고자 함 인가 필터 모두 거치고, 토큰 값이 전달되는 거까지 확인했음 test controller 까지 요청되지만, 정작 페이지는 불러와지지 않음 대체 제가 뭘 놓친 걸까요 ㅠㅠㅠㅠ 이거때문에 며칠 동안 머리 싸매고 있습니다,,, 제발 도와주세요,,,

  • java
  • spring
  • jwt
  • secuity
  • javascript
  • mvc
오세창 댓글 1 좋아요 0 조회수 587

인기 태그

인프런 TOP Writers

주간 인기글