## 3. ユーザーMicroservice-セキュリティの適用


セキュリティの適用


pom.xmlにセキュリティを追加

	<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
    -Bcryptアルゴリズムを使用してPasswordを復号
  • 暗号化方式
  • 、ランダム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<=セキュリティ宣言

    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(); h 2-console画面に入るには必ずしなければなりません.

    結果



    POSTMANを使用して、ユーザーおよびユーザーエンティティを作成します.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd())); これにより、暗号化後にデータベースに入ることがわかります.