Spring Boot 회원가입 및 로그인 구현 + Postman 테스트 기록

2025. 5. 6. 19:40·프로젝트/SnapNote
반응형

Spring Boot와 Spring Security를 사용해 회원가입 및 로그인 API를 구현하고
📮 Postman으로 테스트까지 완료한 과정을 정리함 !


✅ 1. 회원가입 API 구현

📦 SignupRequest DTO

public class SignupRequest {
    @NotBlank @Email
    private String email;
    @NotBlank
    private String password;
    @NotBlank
    private String nickname;
}

📦 SignupResponse DTO

public class SignupResponse {
    private Long userId;
    private String message;
}

🧠 AuthService - 회원가입

public SignupResponse signup(SignupRequest request) {
    if (userRepository.existsByEmail(request.getEmail())) {
        throw new IllegalArgumentException("이미 사용 중인 이메일입니다.");
    }

    User user = User.builder()
        .email(request.getEmail())
        .password(passwordEncoder.encode(request.getPassword()))
        .nickname(request.getNickname())
        .build();

    User savedUser = userRepository.save(user);

    return new SignupResponse(savedUser.getId(), "회원가입이 완료되었습니다.");
}

🎯 AuthController - 회원가입

@PostMapping("/signup")
public ResponseEntity<SignupResponse> signup(@Valid @RequestBody SignupRequest request) {
    SignupResponse response = authService.signup(request);
    return ResponseEntity.status(HttpStatus.CREATED).body(response);
}

✅ 2. 로그인 API 구현

📦 LoginRequest DTO

public class LoginRequest {
    @NotBlank
    private String email;
    @NotBlank
    private String password;
}

📦 LoginResponse DTO

public class LoginResponse {
    private String token;     // 현재는 예시 문자열
    private String nickname;
}

🧠 AuthService - 로그인

public LoginResponse login(LoginRequest request) {
    User user = userRepository.findByEmail(request.getEmail())
        .orElseThrow(() -> new IllegalArgumentException("이메일 또는 비밀번호가 일치하지 않습니다."));

    if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
        throw new IllegalArgumentException("이메일 또는 비밀번호가 일치하지 않습니다.");
    }

    String fakeToken = "jwt-token-example"; // 실제 JWT는 추후 적용

    return new LoginResponse(fakeToken, user.getNickname());
}

🎯 AuthController - 로그인

@PostMapping("/login")
public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
    LoginResponse response = authService.login(request);
    return ResponseEntity.ok(response);
}

✅ 3. Postman으로 API 테스트

🔸 회원가입

  • URL: http://localhost:8080/api/signup
  • Method: POST
  • Body (raw / JSON):
{
  "email": "test@example.com",
  "password": "pass1234",
  "nickname": "시은"
}
  • 성공 응답 예시:
{
  "userId": 1,
  "message": "회원가입이 완료되었습니다."
}

🔸 로그인

  • URL: http://localhost:8080/api/login
  • Method: POST
  • Body (raw / JSON):
{
  "email": "test@example.com",
  "password": "pass1234"
}
  • 성공 응답 예시:
{
  "token": "jwt-token-example",
  "nickname": "시은"
}

🧩 참고: 보안 설정

http
    .csrf(csrf -> csrf.disable())
    .authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/signup", "/api/login").permitAll()
        .anyRequest().authenticated()
    );

✅ 마무리

  • 회원가입 & 로그인 API 구현 완료
  • Spring Security 설정 추가
  • Postman으로 정상 테스트 완료
  • 다음 목표는 ✅ JWT 토큰 발급 기능 구현
반응형

'프로젝트 > SnapNote' 카테고리의 다른 글

Spring Boot에서 JWT 인증 구현하기 (정리)  (0) 2025.05.06
Spring Boot API 테스트 중 401 Unauthorized 에러 해결기  (0) 2025.05.06
SnapNote 프로젝트 개발환경 세팅기  (0) 2025.04.26
Mac에서 MySQL 설치 후 SnapNote용 DB 생성하기  (0) 2025.04.26
'프로젝트/SnapNote' 카테고리의 다른 글
  • Spring Boot에서 JWT 인증 구현하기 (정리)
  • Spring Boot API 테스트 중 401 Unauthorized 에러 해결기
  • SnapNote 프로젝트 개발환경 세팅기
  • Mac에서 MySQL 설치 후 SnapNote용 DB 생성하기
시시응
시시응
시시응 블로그
  • 시시응
    시시응응
    시시응
  • 전체
    오늘
    어제
    • 분류 전체보기 (126)
      • KT AIVLE (31)
      • 대외활동 (32)
        • 사회리더 대학생 멘토링 (0)
        • 22 하반기 코드클럽 (7)
        • 23 상반기 코드클럽 (9)
        • 1784 스쿨혁명 (15)
        • 멋쟁이 사자처럼 (1)
      • 프로젝트 (8)
        • 캡스톤 (3)
        • SnapNote (5)
      • study (1)
        • 데이터분석 (1)
      • 코딩테스트 (49)
        • 프로그래머스 (31)
        • 백준 (15)
        • 알고리즘 (2)
        • 자료구조 (1)
      • IT (5)
        • Git (3)
        • 개발환경 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    playsw_mentor
    대외활동
    코드클럽한국위원회
    KT
    교육봉사
    에이블스쿨
    코테
    코딩테스트
    파이썬
    Python
    대학생
    AIVLE
    네이버커넥트재단
    codeclub_south_korea
    프로그래머스
    소프트웨어야놀자
    KT에이블스쿨
    Lv1
    1784스쿨혁명
    코드클럽
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
시시응
Spring Boot 회원가입 및 로그인 구현 + Postman 테스트 기록
상단으로

티스토리툴바