最好是利用 Spring Security Semantics。
创建一个 bean,它有一个方法来检查特定 Authentication Principal 的访问:
@Component
public class SetLoggerAccessChecker {
public boolean isAuthorizedToChangeLogs(Authentication authentication, HttpServletRequest request) {
// example custom logic below, implement your own
if (request.getMethod().equals(HttpMethod.POST.name())) {
return ((User) authentication.getPrincipal()).getUsername().equals("admin");
}
return true;
}
}
在 WebSecurityConfigurerAdapter 中注入 bean 并使用access
特定 ActuatorLoggerEndpoints 的方法:
@Autowired
private SetLoggerAccessChecker setLoggerAccessChecker;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").httpBasic();
http.csrf().disable().requestMatcher(EndpointRequest.to(LoggersEndpoint.class)).authorizeRequests((requests) -> {
requests.anyRequest().access("@setLoggerAccessChecker.isAuthorizedToChangeLogs(authentication, request)");
});
}
就是这样。
$ http -a user:password localhost:8080/actuator/loggers
// 403
$ http -a admin:password localhost:8080/actuator/loggers
// 200
$ curl --user "admin:password" -i -X POST -H 'Content-Type: application/json' -d '{"configuredLevel": "DEBUG"}' http://localhost:8080/actuator/loggers/com.ikwattro
HTTP/1.1 204
Set-Cookie: JSESSIONID=A013429ADE8B58239EBE385B9DEC524D; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Date: Sat, 02 Jan 2021 22:38:26 GMT
$ curl --user "user:password" -i -X POST -H 'Content-Type: application/json' -d '{"configuredLevel": "DEBUG"}' http://localhost:8080/actuator/loggers/com.ikwattro
HTTP/1.1 403
Set-Cookie: JSESSIONID=2A350627672B6742F5C842D2A3BC1330; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Disposition: inline;filename=f.txt
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sat, 02 Jan 2021 22:41:04 GMT
此处的示例存储库:https ://github.com/ikwattro/spring-boot-actuator-custom-security