gpt4 book ai didi

java - hasRole() 和 hasPermission() 网络安全表达式如何工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:53:56 24 4
gpt4 key购买 nike

这实际上是两个问题,因为它在 Spring Security 引用资料中没有得到很好的解释。第一个问题是,在我的配置中,我有这样的代码:

 @Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/admin").access("hasRole('ADMIN')");

那么在这两种情况下,Spring 都在哪里寻找当前用户的角色呢?是否可能在 UserDetailsS​​ervice 上调用 loadUserByUsername() 方法,然后在获取的 UserDetails 上调用 getAuthorities()?

我的第二个问题是关于 hasPermission() 表达式。假设我有一个自定义的 PermissionEvaluator,有没有办法让它在配置类中工作,例如:

 @Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers("/admin").access("hasPermission(...)")

或者这是一个只在方法级别起作用的表达式?

最佳答案

针对您的第二个问题:是的,您可以将自己的 PermissionEvaluator 与 HttpSecurity 结合使用。首先,你必须像这样定义一个 WebSecurityExpressionHandler

final DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();           
webSecurityExpressionHandler.setPermissionEvaluator(myPermissionEvaluator);

或者像一颗 bean :

@Bean
public DefaultWebSecurityExpressionHandler webExpressionHandler(PermissionEvaluator myPermissionEvaluator) {
final DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
webSecurityExpressionHandler.setPermissionEvaluator(siraPermissionEvaluator);
return webSecurityExpressionHandler;
}

/*this option then needs to autowire the bean*/

然后将它与 HttpSecurity 一起使用,例如:

http.authorizeRequests().expressionHandler(webSecurityExpressionHandler)
.antMatchers("/admin").access("hasPermission(...)");

关于java - hasRole() 和 hasPermission() 网络安全表达式如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37031689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com