[Spring Cloud] Spring Security 처리

jsieon97·2023년 3월 10일
0

Spring Security

  • Authentication + Authorization

Spring Security 적용

  • Dependency 추가
dependencies {
    
    ...
    
    implementation 'org.springframework.boot:spring-boot-starter-security'
    
    ...
  • WebSecurity class 추가
// WebSecurity.java

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

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/users/**").permitAll(); // "/users/**"경로의 접근을 모두 허용
        http.headers().frameOptions().disable(); // 이걸 추가하지 않으면 h2-console 접근 불가
    }
}
  • 메소드 동작
    authenticated() 인증된 사용자의 접근을 허용
    fullyAuthenticated() 인증된 사용자의 접근을 허용, rememberMe 인증 제외
    permitAll() 무조건 접근을 허용
    denyAll() 무조건 접근을 허용하지 않음
    anonymous() 익명 사용자의 접근 허용
    rememberMe() remember-me 인증된 사용자의 접근 허용
    access(String) 주어진 SpEL 표현식의 평가 결과가 true인 경우 접근 허용
    hasRole(String) 사용자가 주어진 역활이 있으면 접근 허용
    hasAuthority(String) 사용자가 주어진 권한이 있으면 접근 허용
    hasAnyRole(String) 사용자가 주어진 역활 중 어떤 것이라도 있으면 접근 허용
    hasAnyAuthority(String) 사용자가 주어진 권한 중 어떤 것이라도 있으면 접근 허용
    hasIpAddress(String) 주어진 IP로부터 요청이 왔다면 접근 허용

  • BCryptPasswordEncoder

    • Password를 해싱하기 위해 Bcrypt 알고리즘 사용
    • 랜덤 Salt를 부여하여 여러번 Hash를 적용한 암호화 방식
  • 인코더 적용

// UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {

    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public  UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @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(bCryptPasswordEncoder.encode(userDto.getPwd()));

        userRepository.save(userEntity);

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

        return returnUserDto;
    }
}
여기서 BCryptPasswordEncoder를 초기화하면 @Bean에 등록되지않아 @Autowired가 적용되지 않아서 초기 실행시 @Bean등록을 위한 과정이 필요하다.
  • Application 초기 실행 시 적용
// UserServiceApplication.java

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {

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

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

Security 테스트

ENCRYPTED_PWD에 저장된 값이 암호화 되어 들어가는 것을 확인할 수 있다.

profile
개발자로써 성장하는 방법

0개의 댓글