在 @PreAuthorize 中使用请求标头值

Mat*_*olt 1 spring spring-security spring-boot spring-expression-language

是否可以在@PreAuthorize中使用请求标头值?

在我的应用程序中,所有请求都包含一个自定义标头,我需要将其与用户角色结合使用,以确定是否应允许它们访问控制器。

如果有人手动指定标头也没关系,因为这不会成为安全问题,因为最终角色将控制它。但我需要使用它来减少在每个控制器方法中手动检查的次数。

谢谢你,马特

İsm*_* Y. 7

1 - 如果您只在少数地方使用它,这可能是最快的方法。

@GetMapping(value = "/private-api-method")
@PreAuthorize("#request.getHeader('header-name') == 'localhost:8080'")
public ResponseEntity<String> privateApiMethod(HttpServletRequest request) {
    return ResponseEntity.ok("OK!");
}
Run Code Online (Sandbox Code Playgroud)

OR

@GetMapping(value = "/private-api-method")
@PreAuthorize("#header == 'localhost:8080'")
public ResponseEntity<String> privateApiMethod(@RequestHeader("header-name") String header) {
    return ResponseEntity.ok("OK!");
}
Run Code Online (Sandbox Code Playgroud)

2 - 如果您要在很多地方使用它,这可能是最好的方法。

(在 中SecurityService,您可以添加多种不同的检查方法。)

@GetMapping(value = "/private-api-method")
@PreAuthorize("@securityService.checkHeader(#request)")
public ResponseEntity<String> privateApiMethod(HttpServletRequest request) {
    return ResponseEntity.ok("OK!");
}
Run Code Online (Sandbox Code Playgroud)

3 - 您可以选择适合自己的特殊方法

使用 Spring Security 的自定义安全表达式