본문 바로가기

JAVA/Spring Security

스프링 시큐리티 Basic 인증 재구성

반응형

기본구성 재정의

UserDetailsService

@Configuration
public class ProjectConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        var userDetailsService = new InMemoryUserDetailsManager();

        var user = User.withUsername("john")
                .password("12345")
                .authorities("read")
                .build();

        userDetailsService.createUser(user);

        return userDetailsService;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
  • UserDetailsService를 빈으로 등록하여 재구성을 한다.

NoOpPasswordEncoder

  • 암호화나 해시를 적용하지 않고 일반 텍스트처럼 처리한다.
  • String 클래스의 기본 equals(Object obj) 메서드로 간단한 문자열 비교
  • 개발환경에서만 사용

엔드포인트 권한 부여 구성 재정의

  • WebSecurityConfigurerAdapter 클래스를 확장
  • 엔드포인트 권한 부여
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        var userDetailsService = new InMemoryUserDetailsManager();

        var user = User.withUsername("john")
                .password("12345")
                .authorities("read")
                .build();

        userDetailsService.createUser(user);

        auth.userDetailsService(userDetailsService)
            .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeRequests().anyRequest().authenticated();
    }
}

AuthenticationProvider 구현 재정의

  • AuthenticationProvider는 인증 논리를 구현하고 사용자 관리와 암호 관리를 각각 UserDetailsService, PasswordEncoder에 위임한다.
  • UserDetailsService, PasswordEncoder가 필요없도록 기본 AuthenticationProvider를 재정의할 수 있다.
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //인증논리
        String username = authentication.getName();
        String password = String.valueOf(authentication.getCredentials());

        if ("john".equals(username) && "12345".equals(password)) {
            return new UsernamePasswordAuthenticationToken(username, password, Arrays.asList());
        } else {
            throw new AuthenticationCredentialsNotFoundException("Error!");
        }
    }

    @Override
    public boolean supports(Class<?> authenticationType) {
        // Authentication 형식의 구현
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authenticationType);
    }
}
  • authenticate(Authentication authentication) 메서드는 인증의 전체 논리를 나타낸다.
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeRequests()
                .anyRequest().authenticated();
    }
}
  • 모든 견고한 프레임워크는 계약을 이용해서 프레임워크의 구현과 이에 기반을 둔 애플리케이션을 분리한다.
  • 자바는 인터페이스로 계약을 정의한다.
  • 프로그래머는 올바른 구현을 선택하기 위해 재료가 함께 작동하는 방법을 아는 주방장에 비유할 수 있다.
  • 프로그래머는 프레임워크의 추상화를 알고 이를 이용해 통합한다.
반응형

'JAVA > Spring Security' 카테고리의 다른 글

스프링 시큐리티 Basic 인증  (0) 2022.10.19