ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2차 프로젝트 로그인 기능 구현!
    엘리스트랙 2024. 3. 3. 19:43
    728x90

     

     

     

     

    프로젝트가 csr이기 때문에 jwt로 토큰을 발급 받아서 세션 스토리지에 저장해 주는 방식으로 했다.

     

    @PostMapping("/sign-in")
        public ResponseEntity<?> login(@RequestBody SignInDto signInDto) {
            User user = userService.authenticate(signInDto.getEmail(), signInDto.getPassword());
            if (user != null) {
                String jwt = userService.generateJwtToken(user);
                Map<String, Object> response = new HashMap<>();
                response.put("token", jwt);
                response.put("isAdmin", user.isAdmin());
                response.put("id", user.getId());
    
                return new ResponseEntity<>(response, HttpStatus.OK);
            }
            return new ResponseEntity<>("Invalid email or password", HttpStatus.UNAUTHORIZED);
        }

     

    먼저 authenticate로 입력받은 아이디와 비밀번호가 맞는 정보인지 확인해 주었다.

     

    public User authenticate(String email, String password) {
            User user = userRepository.findByEmail(email);
            if (user != null && passwordEncoder.matches(password, user.getPassword())) {
                return user;
            }
            return null;
        }

     

     

    유저가 존재한다면 토큰을 생성해 주었다.

     

    public String generateJwtToken(User user) {
            return Jwts.builder()
                    .setSubject(user.getEmail())
                    .claim("isAdmin", user.isAdmin()) // isAdmin 정보 추가
                    .setIssuedAt(new Date())
                    .signWith(key)
                    .compact();
        }

     

     

    토큰, 어드민 정보, 유저 아이디를 서버에 보내주면

     

    try {
        const data = { email, password };
    
        const result = await Api.post("/users/sign-in", data);
        const { token, isAdmin, id } = result;
    
        // 로그인 성공, 토큰을 세션 스토리지에 저장
        sessionStorage.setItem("token", token);
        sessionStorage.setItem("id", id);
    
        alert(`정상적으로 로그인되었습니다.`);
    
        // 로그인 성공
    
        // admin(관리자) 일 경우, sessionStorage에 기록함
        if (isAdmin) {
          sessionStorage.setItem("admin", "admin");
        }
    
        // 기존 다른 페이지에서 이 로그인 페이지로 온 경우, 다시 돌아가도록 해 줌.
        const { previouspage } = getUrlParams();
    
        if (previouspage) {
          window.location.href = previouspage;
    
          return;
        }
    
        // 기존 다른 페이지가 없었던 경우, 그냥 기본 페이지로 이동
        window.location.href = "/";
      } catch (err) {
        console.error(err.stack);
        alert(`문제가 발생하였습니다. 확인 후 다시 시도해 주세요: ${err.message}`);
      }

     

     

    세션 스토리지에 저장해 사용할 수 있게 된다.

     

     

     

     

    728x90
Designed by Tistory.