회원가입 DB 저장시 비밀번호를 암호화하고 역할을 부여한다.
1. 비밀번호 암호화와 디폴트 유저 권한 부여
DB에 클라이언트의 데이터가 INSERT될 때, 데이터가 그대로 들어갔다.
나중에 어떤 서비스를 하게 되든 개인정보 보호는 매우 중요한 부분이다.
(캡쳐를 깜빡해서 인강 사진으로 대체...)
먼저 SecurityConfig.java안에 @Bean 기능을 삽입한다.
@Bean 어노테이션을 걸어주게 되면, SecurityConfig 가 IoC컨테이너에 등록 될 때,
@Bean 어노테이션을 인식해서 BCryptPasswordEncoder 를 리턴해서 IoC컨테이너에 등록하게 된다.
BCryptPasswordEncoder는 함수명처럼 비밀번호를 암호화시켜주는 메서드이다.
암호화 된 비밀번호가 IoC컨테이너에 담겼으니, 우리는 이걸 의존성주입하여 사용하기만 하면 된다.
SecurityConfig.java
package com.GStagram.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.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity // 해당 파일로 시큐리티를 활성화
@Configuration // IOC
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super 삭제 - 기존 시큐리티가 가지고 있는 기능이 다 비활성화됨.
// 인증이 되지 않은 모든 사용자는 로그인 페이지로 이동
http.headers().frameOptions().disable();
http.csrf().disable();
http
.authorizeRequests() // URL별 관리
.antMatchers("/auth/**", "/css/**","/images/**","/js/**","/h2-console/**").permitAll() //유저 관련 페이지만 접근 가능
.anyRequest().authenticated() // 설정된 값들 이외 나머지 URL은 인증된 사용자만 접근 가능
.and()
.formLogin()
.loginPage("/auth/login") // GET
.defaultSuccessUrl("/");
}
}
다음 AuthService.java로 돌아가서 회원가입 메서드에 @Transactional 어노테이션을 걸어준다.
@Transactional 어노테이션은 해당 메서드가 시작하고 종료될 때 까지 트랜잭션 관리를 해주게 된다.
일반적으로 GET(SELECT) 가 아닌 Write(INSERT, UPDATE, DELETE) 기능일 때 사용한다.
bCryptPasswordEncoder가 가지고 있는 메서드인 encode를 사용하면 자동으로 암호화가 된다.
암호화된 비밀번호를 user의 비밀번호로 넣게되면 암호화는 끝이 난다.
그리고 지금 사용할 것은 아니지만 회원가입하는 유저들의 권한을 'ROLE_USER' 로 지정해주었다.
나중에 관리자 계정을 만들게 된다면 거기서는 'ROLE_ADMIN'으로 바꾸면 된다.
@Transactional
public User signupReg(User user) {
String encPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(encPassword);
user.setRole("ROLE_USER");
User userEntity = userRepository.save(user);
return userEntity;
}
GitHub - minhyeok2487/Gstagram: 인스타그램 클론코딩 Gstagram
인스타그램 클론코딩 Gstagram. Contribute to minhyeok2487/Gstagram development by creating an account on GitHub.
github.com