반응형
1. 프로젝트 설정
Maven 의존성 추가
먼저, 비밀번호 암호화를 위해 Spring Security 의존성을 추가합니다.
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 비밀번호 암호화(Bcrypt)
Spring Security에서 제공하는 BCryptPasswordEncoder를 사용해 비밀번호를 암호화합니다.
PasswordUtil 클래스
비밀번호 암호화 및 검증 유틸리티를 작성합니다.
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
public class PasswordUtil {
private static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// 비밀번호 암호화
public static String encodePassword(String rawPassword) {
return passwordEncoder.encode(rawPassword);
}
// 비밀번호 검증
public static boolean matches(String rawPassword, String encodedPassword) {
return passwordEncoder.matches(rawPassword, encodedPassword);
}
}
3. 사용자 데이터 저장 및 인증
가상 사용자 데이터베이스
이번 예제에서는 간단히 HashMap을 사용해 사용자 데이터를 저장합니다. 실제 프로젝트에서는 데이터베이스를 사용해야 합니다.
import java.util.HashMap;
import java.util.Map;
public class UserRepository {
private static final Map<String, String> users = new HashMap<>();
// 사용자 추가
public static void saveUser(String username, String rawPassword) {
String encodedPassword = PasswordUtil.encodePassword(rawPassword);
users.put(username, encodedPassword);
}
// 사용자 조회
public static String findPasswordByUsername(String username) {
return users.get(username);
}
}
사용자 저장
애플리케이션 실행 시 기본 사용자 데이터를 추가합니다.
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class DataInitializer implements CommandLineRunner {
@Override
public void run(String... args) {
// 기본 사용자 데이터 추가
UserRepository.saveUser("user1", "password123");
UserRepository.saveUser("admin", "admin123");
System.out.println("Users initialized!");
}
}
4. 인증 API 구현
이제 비밀번호 인증을 위한 API를 작성합니다.
AuthController
AuthController에서 로그인 요청을 받아 인증을 처리합니다.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password) {
// 사용자 조회
String storedPassword = UserRepository.findPasswordByUsername(username);
if (storedPassword == null) {
return "User not found!";
}
// 비밀번호 검증
boolean isValid = PasswordUtil.matches(password, storedPassword);
if (isValid) {
return "Login successful!";
} else {
return "Invalid credentials!";
}
}
}
5. 실행 및 테스트
애플리케이션 실행
Spring Boot 애플리케이션을 실행합니다.
Postman으로 테스트
- 로그인 테스트
- URL: POST http://localhost:8080/auth/login
- Body: username과 password를 전송합니다.
- 응답:
- 로그인 성공 시: Login successful!
- 로그인 실패 시: Invalid credentials!
6. 이후
추후 작성할 포스팅
- JWT 필터를 활용한 전역 인증
- 리프레시 토큰 구현
- 데이터베이스와 JPA를 사용해 사용자 데이터 관리
- JWT를 결합해 인증 토큰 발급
- 인증 실패 시 예외 처리 추가
'SpringBoot' 카테고리의 다른 글
SpringBoot - JWT 필터를 활용한 전역 인증 구현 (0) | 2024.11.26 |
---|---|
SpringBoot - JWT 구현 (기초) (0) | 2024.11.23 |
SpringBoot - SLF4J (0) | 2024.11.17 |
SpringBoot - 백엔드 개발할 때 알아두면 좋은 기술 스택 (1) | 2024.11.16 |
SpringBoot - Could not find artifact mysql:mysql-connector-java:pom:unknown in mvn2s [에러] (0) | 2024.09.24 |