외부에서 URL만으로 API 콜을 할 수 없게 만들기 위한 방법이다.
Spring Security 기본 설정이 완료된 이후를 기점으로 작성되었다.
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import javax.servlet.http.HttpServletRequest;
public class APIKeyAuthFilter extends AbstractPreAuthenticatedProcessingFilter {
private String principalRequestHeader;
public APIKeyAuthFilter(String principalRequestHeader) {
this.principalRequestHeader = principalRequestHeader;
}
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
return request.getHeader(principalRequestHeader);
}
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
return "N/A";
}
}
@Value 어노테이션의 값은 application.yml에 설정된 값을 기반으로 작성하면 된다.
@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Value("${appname.http.auth-token-header.name}")
private String principalRequestHeader;
@Value("${appname.http.auth-token}")
private String principalRequestValue;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
APIKeyAuthFilter filter = new APIKeyAuthFilter(principalRequestHeader);
filter.setAuthenticationManager(new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String principal = (String) authentication.getPrincipal();
if (!principalRequestValue.equals(principal)) {
throw new BadCredentialsException("The API key was not found or not the expected value.");
}
authentication.setAuthenticated(true);
return authentication;
}
});
http
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(filter, AbstractPreAuthenticatedProcessingFilter.class)
.authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated())
.formLogin(AbstractHttpConfigurer::disable);
return http.build();
}
}
appname, 토근 이름, 토큰 정보는 custom해서 입력해주면 된다.
appname:
http:
auth-token-header:
name: Authorization
auth-token: fdasrv34atdzbt4zeex7y
postman에서 API 테스트를 할 때, Header에 설정한 이름과 토큰 값을 세팅하고 날려야 한다. 그렇지 않으면 403 에러가 발생한다.