복붙노트

[SPRING] API 키와 비밀 키로 스프링 부트 API 보안

SPRING

API 키와 비밀 키로 스프링 부트 API 보안

유효한 API 키와 비밀 키를 가진 클라이언트에서만 액세스 할 수 있도록 Spring Boot API를 보호하고 싶습니다. 그러나 모든 데이터는 익명으로되어 있으므로 프로그램 내에 인증 (사용자 이름과 암호가있는 표준 로그인)이 없습니다. 달성하고자하는 모든 API 요청은 특정 타사 프런트 엔드에만 사용할 수 있습니다.

나는 사용자 인증을 사용하여 Spring Boot API를 보호하는 방법에 관한 많은 기사를 발견했다. 하지만 사용자 인증이 필요하지 않습니다. 내가 생각하고있는 것은 고객에게 API 키와 비밀 정보를 제공하여 엔드 포인트에 액세스 할 수 있도록하는 것입니다.

이걸 어떻게 성취 할 수 있겠 어? 고맙습니다!

해결법

  1. ==============================

    1.인증을 위해 사용중인 헤더를 가져 오는 필터를 만듭니다.

    인증을 위해 사용중인 헤더를 가져 오는 필터를 만듭니다.

    import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
    
    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";
        }
    
    }
    

    Web Security 구성에서 필터를 구성하십시오.

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.annotation.Order;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.BadCredentialsException;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.AuthenticationException;
    
    @Configuration
    @EnableWebSecurity
    @Order(1)
    public class APISecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Value("${yourapp.http.auth-token-header-name}")
        private String principalRequestHeader;
    
        @Value("${yourapp.http.auth-token}")
        private String principalRequestValue;
    
        @Override
        protected void configure(HttpSecurity httpSecurity) 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;
                }
            });
            httpSecurity.
                antMatcher("/api/**").
                csrf().disable().
                sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                and().addFilter(filter).authorizeRequests().anyRequest().authenticated();
        }
    
    }
    
  2. from https://stackoverflow.com/questions/48446708/securing-spring-boot-api-with-api-key-and-secret by cc-by-sa and MIT license