반응형

Basic Authentication이란?

  • Authorization 헤더를 활용하는 방식
  • 요청시마다 Authorization: Basic {base64(usename:password)} 형식의 헤더를 포함하여 요청하여 인증을 처리
  • BasicAuthenticationFilter를 사용
    • Authorization 헤더가 없으면 패스
    • "Authorization: Basic {base64(username:password)}" 형태로 전달된 헤더를 분석해서 인증정보 생성(UsernamePasswordAuthenticationToken) 후 아래 로직 수행
    • ThreadLocalSecurityContextHolderStrategy.setContext() 를 호출하여 인증정보를 컨텍스트에 세팅

의존성 추가

implementation("org.springframework.boot:spring-boot-starter-security")

SecurityConfig

@EnableWebSecurity(debug = true)
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            .authorizeRequests(authorize -> {
                authorize.requestMatchers("/error/**").permitAll();
                authorize.anyRequest().authenticated();
            })
            .httpBasic(Customizer.withDefaults())
            .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        User.UserBuilder users = User.builder();
        UserDetails user = users
            .username("tyler")
            .password(passwordEncoder.encode("1234"))
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

DemoController

@RestController
public class DemoController {
    @GetMapping("/api/v1/demo")
    public String demo() {
        return "Hello World";
    }
}

요청 테스트

  • Authorization: Basic {base64(username:password)}
curl -H "Authorization: Basic $(echo -n 'tyler:1234' | base64)" http://localhost:8080/api/v1/demo

 

반응형

+ Recent posts