1. HTTP basic 인증
- 가장 단순한 형태의 인증 방식으로, 아이디와 비밀번호를 매 요청마다 HTTP Authorization 헤더에 "아이디:비밀번호"를 Base64로 인코딩하여 실어 보내는 방식
간단한 Controller를 만들어보자.
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello!";
}
}
스프링부트 애플리케이션을 실행하면 다음과 같이 일회용 암호가 생성된다.
Using generated security password: fbd9dc84-fba7-46a8-97a1-3ed343a18d57
This generated password is for development use only. Your security configuration must be updated before running your application in production.
HTTP Basic 인증으로 애플리케이션의 엔드포인트를 호출하려면 이 암호를 이용해야 한다.
- 일반 호출 시 : 401 Unauthorized
- 위에서 자동 생성된 암호를 이용하여 호출 시(Authorization 헤더) : 200 OK
401 Unauthorized : 인증 실패
403 Forbidden : (인가) 권한 없음
사용자에 관한 세부 정보는 스프링 시큐리티로 UserDetailSerivce 계약을 구현하는 객체가 관리한다.
PasswordEncoder는 암호를 인코딩하고 암호가 기존 인코딩과 일치하는지 확인하며, UserDetailService의 기본 구현을 대체할 때는 PasswordEncoder도 지정해야 한다.
AuthenticationProvider는 인증 논리를 정의하고 사용자와 암호의 관리를 위임하늗네, 이것의 기본 구현은 UserDetailSerivce 및 PasswordEncoder에 제공된 기본 구현을 이용하면 된다.
2. 기본 구성 재정의
package com.studiop.ssiach2ex1.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@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();
}
}
이제 john:12345 를 이용하여 액세스할 수 있다.
애플리케이션에 맞게 모든 엔드포인트가 아닌 보안이 필요한 엔드포인트에 다른 권한 부여 규칙을 선택하고 싶다면 어떻게 해야할까?
WebSecurityConfigurerAdapter 클래스를 확장하는 것부터 시작해보자.
* Spring Security 5.7.x 부터 WebSecurityConfigurerAdapter가 Deprecated 되었으므로 다음과 같이 등록해야 한다. (ProjectConfig에 이어서 추가)
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.with(new HttpBasicConfigurer<>(), (httpBasic) -> {})
.authorizeHttpRequests(authorize -> authorize
// .anyRequest().authenticated() // 모든 요청에 인증 필요
.anyRequest().permitAll() // 모든 요청에 인증 불필요
);
return http.build();
}
- 사용자 세부 정보 서비스와 암호 인코더를 재정의하였다.
- 인증 공급자(AuthenticaionProvider)는 인증 논리를 구현하고 사용자 관리와 암호 관리를 각각 위임했다.
- 인증 공급자를 재정의해보자.
package com.studiop.ssiach2ex1;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
if ("john".equals(username) && "12345".equals(password)) {
return new UsernamePasswordAuthenticationToken(username, password, Arrays.asList());
} else {
throw new AuthenticationCredentialsNotFoundException("Error in authentication");
}
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
ProjectConfig에서 다음과 같이 받는다.
@Autowired
private CustomAuthenticationProvider authenticationProvider;
@Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(List.of(authenticationProvider));
}
'스프링 > 스프링 시큐리티 인 액션 (도서 정리)' 카테고리의 다른 글
스프링 시큐리티 - 5. 인증 구현 (0) | 2025.04.30 |
---|---|
스프링 시큐리티 - 4. 암호 처리 (0) | 2025.04.30 |
스프링 시큐리티 - 3. 사용자 관리 (0) | 2025.04.29 |
스프링 시큐리티 - 1. 보안 개념 (0) | 2025.04.28 |