반응형

본 내용은 인프런의 이도원 님의 강의 "Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)" 내용을 바탕으로 정리한 내용입니다.

 

Spring Security

  • Spring Framework 기반 애플리케이션의 보안을 담당하는 강력한 하위 프레임워크
  • Authentication + Authorization

구현 과정

  1. 애플리케이션에 spring security jar을 Dependency에 추가
  2. WebSecurityConfigureAdapter를 상속받는 Security Configuration 클래스 생성
  3. Security Configuration 클래스에 @EnableWebSecurity 추가
  4. Authentication -> configure(AuthenticationManagerBuilder auth) 메서드를 재정의
  5. Password encode를 위한 BCryptPasswordEncoder 빈 정의
  6. Authorization -> configure(HttpSecurity http) 메서드를 재정의

pom.xml 수정

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-security</artifactId>  
</dependency>
  • 스프링 시큐리티 추가

WebSecurityConfig 클래스

package com.example.UserService.config;  

import lombok.RequiredArgsConstructor;  
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.configurers.AbstractHttpConfigurer;  
import org.springframework.security.web.SecurityFilterChain;  

@Configuration  
@RequiredArgsConstructor  
public class WebSecurityConfig {  

    @Bean  
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {  
        http.csrf(AbstractHttpConfigurer::disable);  

        http.csrf(AbstractHttpConfigurer::disable);  

        http.authorizeHttpRequests(authz -> authz  
                .requestMatchers("/users/**").permitAll()
                .anyRequest().authenticated()  
        );  

        return http.build();  
    }  
}
  • requestMatchers("/users/").permitAll(): /users/ 경로로 들어오는 요청은 인증 없이 접근할 수 있다.
  • anyRequest().authenticated(): 그 외의 모든 요청은 인증이 필요하다.

UserServiceImpl 클래스 수정

package com.example.UserService.service;  

import com.example.UserService.dto.UserDto;  
import com.example.UserService.jpa.UserEntity;  
import com.example.UserService.jpa.UserRepository;  
import org.modelmapper.ModelMapper;  
import org.modelmapper.convention.MatchingStrategies;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;  
import org.springframework.stereotype.Service;  

import java.util.UUID;  

@Service  
public class UserServiceImpl implements UserService{  
    @Autowired  
    private UserRepository userRepository;  
    @Autowired  
    private BCryptPasswordEncoder bCryptPasswordEncoder;  

    @Override  
    public UserDto createUser(UserDto userDto) {  
        // 랜덤으로 ID 생성  
        userDto.setUserId(UUID.randomUUID().toString());  
        ModelMapper mapper = new ModelMapper();  
        // 값들이 정확히 같을 때만 엔티티 클래스로 변환하도록 설정  
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);  
        UserEntity userEntity = mapper.map(userDto, UserEntity.class);  
        userEntity.setEncryptedPwd(bCryptPasswordEncoder.encode(userDto.getPwd()));  

        userRepository.save(userEntity);  

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

        return returnUserDto;  
    }  
}
  • Password를 해싱하기 위해 BCryptPasswordEncoder 클래스의 Bcrypt 알고리즘을 사용한다.
  • Bcrypt 알고리즘은 랜덤 Salt를 부여하여 여러번 Hash를 적용한 암호화 방식이다.
반응형

+ Recent posts