스프링
Spring Boot + Security 회원가입 기능
코린F&F프티
2024. 1. 19. 16:46
■ 스프링 부트 환경에서 BCryptPasswordEncoder를 이용하여 회원가입을 통해 비밀번호를 암호화 하여 데이터베이스에 기입하고 security를 통해 데이터 통신에 있어 보안을 강화하도록 한다.
mysql에 테이블, userEntity는 이미 만들어 놓은 상황으로 가정하에 기능을 구현한다.
1. 프로젝트에 spring Security 의존성 추가(Gradle)
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-boot-security-test'
2. securityConfig 클래스 구현
- 프로젝트에 config디렉토리를 생성 후 SecurityConfig.java파일을 생성 하여 설정을 구성해준다.
- 이 구성 파일은 세부 버전별로 구현 방법이 많이 상이 하다.( 필자는 스프링 시큐리티 6.2.1버전으로 구현 )
- 추가 커스텀 할 요소들은 이후 구현할 생각이다.
package com.example.keyboard.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf((auth) -> auth.disable());
//경로별 인가 작업
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/api/login", "/", "/api/join").permitAll()
// .requestMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
- 이로써 데이터 요청 권한은 모두 막아놓고 permitAll()을 이용하여 해당 api주소만 권한을 부여하여 통신이 가능하게 한다.
- 이를 이용하여 해당 유저의 권한을 체크하고 리다이렉트를 이용하여 원하는 장소를 정하여 보낼 수 있다.
- passwordEncoder를 통해 비밀번호 암호화를 진행 할 수 있게 한다.
3. Controller 구성
- user객체를 받아 서비스로 넘긴다.
- 이후 회원가입이 완료되면 가입한 이름을 반환하도록 한다.
@PostMapping("/join")
public ResponseEntity<Object> join(userEntity vo){
try {
String userName = userService.join(vo);
return new ResponseEntity<>(userName, HttpStatus.OK);
}catch (Exception e){
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
4. Service 구성
- 받은 객체로 비밀번호를 암호화를 하고 데이터베이스 쿼리를 실행 시킨다.
public String join(userEntity vo) throws Exception {
userEntity userVO = new userEntity();
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
vo.setPassword(passwordEncoder.encode(vo.getPassword()));
userDao.join(vo);
return vo.getUserName();
}
5. DAO 구성
@Mapper
@Repository
public interface userDao {
public void join(userEntity user) throws Exception;
}
6. xml 파일 구성
- 데이터베이스 테이블의 컬럼에 맞게 Insert문을 작성한다.
<!-- 회원가입 -->
<insert id="join" parameterType="userEntity">
INSERT INTO users(login_id, password, user_name, phone_number, address, email, birthday)
VALUES(#{loginId}, #{password}, #{userName}, #{phoneNum},#{address},#{email}, #{birthday})
</insert>
7. 테스트
- 만들어 놓은 api를 post통신 완료시 controller를 구성할때 작성한 가입한 이름이 나타난다.
- 데이터베이스에서 select 테이블을 했을시에 password에 암호화된 비밀번호가 잘 들어간것을 확인할 수 있다.