Java 使用 API 密钥和密钥保护 Spring Boot API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48446708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Securing Spring Boot API with API key and secret
提问by Vitalii Oleksiv
I would like to secure the Spring Boot API so it is accessible only for the clients that has valid API key and secret. However, there is no authentication (standard login with username and password) inside the program as all data is anonymous. All I'm trying to achieve is that all API requests can be used only for specific third party front-end.
我想保护 Spring Boot API,以便只有具有有效 API 密钥和机密的客户端才能访问它。但是,程序内部没有身份验证(使用用户名和密码进行标准登录),因为所有数据都是匿名的。我想要实现的只是所有 API 请求只能用于特定的第三方前端。
I found a lot of articles about how to secure the Spring Boot API with user authentication. But I don't need user authentication. What I am thinking of is just provide my client with API key and secret so he has access to the endpoints.
我找到了很多关于如何使用用户身份验证保护 Spring Boot API 的文章。但我不需要用户身份验证。我想到的只是为我的客户提供 API 密钥和秘密,以便他可以访问端点。
Could you please suggest me how can I achieve this? Thank you!
您能否建议我如何实现这一目标?谢谢!
采纳答案by MarkOfHall
Create a filter that grabs what ever header(s) you're using for authentication.
创建一个过滤器来获取您用于身份验证的所有标头。
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";
}
}
Configure the filter in your Web Security config.
在您的网络安全配置中配置过滤器。
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();
}
}