반응형
본 내용은 인프런의 이도원 님의 강의 "Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)" 내용을 바탕으로 정리한 내용입니다.
Spring Security
- Spring Framework 기반 애플리케이션의 보안을 담당하는 강력한 하위 프레임워크
- Authentication + Authorization
구현 과정
- 애플리케이션에 spring security jar을 Dependency에 추가
- WebSecurityConfigureAdapter를 상속받는 Security Configuration 클래스 생성
- Security Configuration 클래스에 @EnableWebSecurity 추가
- Authentication -> configure(AuthenticationManagerBuilder auth) 메서드를 재정의
- Password encode를 위한 BCryptPasswordEncoder 빈 정의
- 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를 적용한 암호화 방식이다.
반응형
'Cloud > MSA' 카테고리의 다른 글
[MSA] MicroService 구현(상품 서비스) (0) | 2024.11.27 |
---|---|
[MSA] MicroService 구현(사용자 서버 기능 추가) (0) | 2024.11.26 |
[MSA] MicroService 구현(회원가입 구현) (0) | 2024.11.26 |
[MSA] MicroService 구현(사용자 서비스) (0) | 2024.06.29 |
[MSA] Gateway Filter (0) | 2024.06.29 |