## 3. Users Microservice - Security 적용

Young Hwan Kim·2021년 12월 31일
0

Security 적용

pom.xml에 Security 추가

	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

UserService.java

public interface UserService {
    UserDto createUser(UserDto userDto);
}

UserServiceImpl.java

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDto createUser(UserDto userDto) {
        userDto.setUserId(UUID.randomUUID().toString());

        ModelMapper mapper = new ModelMapper();
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        UserEntity userEntity = mapper.map(userDto, UserEntity.class);
        userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd()));

        userRepository.save(userEntity);

        UserDto returnUserDto = mapper.map(userEntity, UserDto.class);


        return returnUserDto;
    }
  • BCRyptPasswordEncoder
    - Password를 해싱하기 위해 Bcrypt 알고리즘 사용
    • 랜덤 Salt를 부여하여 여러번 Hash를 적용한 암호화 방식

UserServiceApplication.java

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

WebSecurity.java <= Security 선언

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurity extends WebSecurityConfigurerAdapter {

    //권한
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/users/**").permitAll();
        http.headers().frameOptions().disable();
    }
}

참고로 http.headers().frameOptions().disable(); 을 꼭 해줘야 h2-console 화면에 들어갈 수 있다.

결과

POSTMAN으로 user를 생성하고 userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd())); 를 통해 암호화되어 DB에 들어가는 걸 볼 수 있다.

profile
Back-End DEVELOPER ☁️

0개의 댓글