更新时间:2023-11-04 16:36:10
在任何带有@Controller
,@RestController
注释的bean中,您可以直接将Principal
用作方法参数.
In any @Controller
, @RestController
annotated bean you can use Principal
directly as a method argument.
@RequestMapping("/users/{user_id}")
public String getUserInfo(@PathVariable("user_id") Long userId, Principal principal){
// test if userId is current principal or principal is an ADMIN
....
}
如果您不想在Controller
中进行安全检查,则可以使用 Spring EL 表达式.
您可能已经使用了一些内置表达式,例如hasRole([role])
.
If you don't want the security checks in your Controller
s you could use Spring EL expressions.
You probably already use some build-in expressions like hasRole([role])
.
您可以编写自己的表达式.
And you can write your own expressions.
bean
@Component("userSecurity")
public class UserSecurity {
public boolean hasUserId(Authentication authentication, Long userId) {
// do your check(s) here
}
}
http
.authorizeRequests()
.antMatchers("/user/{userId}/**")
.access("@userSecurity.hasUserId(authentication,#userId)")
...
令人高兴的是,您还可以组合以下表达式:
The nice thing is that you can also combine expressions like:
hasRole('admin') or @userSecurity.hasUserId(authentication,#userId)