这个完整的答案是由一个工作的 Spring Boot 应用程序支持的,并带有单元测试来确认它。
如果你觉得这个答案有帮助,请投票。
简短的回答是您的安全配置可能如下所示
http
.sessionManagement()
.disable()
//application security
.authorizeRequests()
.anyRequest().hasAuthority("API_KEY")
.and()
.addFilterBefore(new ApiKeyFilter(), HeaderWriterFilter.class)
.addFilterAfter(new UserCredentialsFilter(), ApiKeyFilter.class)
.csrf().ignoringAntMatchers(
"/api-key-only",
"/dual-auth"
)
;
// @formatter:on
}
}
让我告诉你发生了什么。我鼓励您查看我的示例,特别是涵盖您的许多场景的 unit tests。
我们有两个安全级别
1. 每个 API 都必须由 ApiKey 保护
2. 只有部分 API 必须由 UserCredentials 保护
在我的example project 中,我选择了以下解决方案
-
我使用 WebSecurityConfigurerAdapter 来满足 ApiKey 要求
.authorizeRequests()
.anyRequest().hasAuthority("API_KEY")
-
我通过启用它来使用方法级别的安全性
@EnableGlobalMethodSecurity(prePostEnabled = true)
然后在我的控制器中要求它
@PreAuthorize("hasAuthority('USER_CREDENTIALS')")
public String twoLayersOfAuth() {
//only logic here
}
ApiKey 过滤器超级简单
public class ApiKeyFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String authorization = request.getHeader("Authorization");
final String prefix = "ApiKey ";
if (hasText(authorization) && authorization.startsWith(prefix)) {
String key = authorization.substring(prefix.length());
if ("this-is-a-valid-key".equals(key)) {
RestAuthentication<SimpleGrantedAuthority> authentication = new RestAuthentication<>(
key,
Collections.singletonList(new SimpleGrantedAuthority("API_KEY"))
);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(request, response);
}
}
第二层身份验证甚至很简单(它依赖于第一层来执行)
public class UserCredentialsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String userCredentials = request.getHeader("X-User-Credentials");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if ("valid-user".equals(userCredentials) && authentication instanceof RestAuthentication) {
RestAuthentication<SimpleGrantedAuthority> restAuthentication =
(RestAuthentication<SimpleGrantedAuthority>)authentication;
restAuthentication.addAuthority(new SimpleGrantedAuthority("USER_CREDENTIALS"));
}
filterChain.doFilter(request, response);
}
}
请注意:每个过滤器如何不关心在没有认证或认证不充分时会发生什么。这一切都为你处理好了。您的过滤器只需验证正确的数据;
Spring、Spring Boot 和 Spring Security 有一些出色的测试设施。
我可以调用具有两种安全级别的 api-only 端点
mvc.perform(
post("/api-key-only")
.header("Authorization", "ApiKey this-is-a-valid-key")
.header("X-User-Credentials", "valid-user")
)
.andExpect(status().isOk())
.andExpect(authenticated()
.withAuthorities(
asList(
new SimpleGrantedAuthority("API_KEY"),
new SimpleGrantedAuthority("USER_CREDENTIALS")
)
)
)
.andExpect(content().string("API KEY ONLY"))
;
或者我可以通过第一级安全并被第二级拒绝
mvc.perform(
post("/dual-auth")
.header("Authorization", "ApiKey this-is-a-valid-key")
)
.andExpect(status().is4xxClientError())
.andExpect(authenticated()
.withAuthorities(
asList(
new SimpleGrantedAuthority("API_KEY")
)
)
)
;
当然,我们总是有幸福的道路
mvc.perform(
post("/dual-auth")
.header("Authorization", "ApiKey this-is-a-valid-key")
.header("X-User-Credentials", "valid-user")
)
.andExpect(status().isOk())
.andExpect(content().string("DUAL AUTH"))
.andExpect(authenticated()
.withAuthorities(
asList(
new SimpleGrantedAuthority("API_KEY"),
new SimpleGrantedAuthority("USER_CREDENTIALS")
)
)
)
;