我想保护Spring Boot API,以便只有具有有效API密钥和机密的客户端才能访问它。但是,程序内部没有身份验证(使用用户名和密码的标准登录),因为所有数据都是匿名的。我试图实现的是,所有API请求只能用于特定的第三方前端。
我找到了很多有关如何通过用户身份验证保护Spring Boot API的文章。但是我不需要用户身份验证。我在想的只是向我的客户端提供API密钥和机密,以便他可以访问端点。
您能否建议我如何实现?谢谢!
创建一个过滤器,以捕获用于身份验证的标头。
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安全配置中配置过滤器。
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(); } }