基于路径变量的弹簧安全性授权 [英] Authorization in spring-security based on path variables
问题描述
我的用例是对&然后根据@PathVariable参数授权用户.我需要执行一些自定义代码来授权主体.我不确定在这里采用的方法-
My use case is to authenticate & then authorize users based on @PathVariable parameters. I need to execute some custom code to authorize the principal. I'm not sure of the approach to take here -
-
我已经实现了自定义的AbstractAuthenticationProcessingFilter&用于身份验证的AuthenticationProvider,最终将角色授予主体.我可以检查servlet请求中的路径变量(使用HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE),并将其他权限添加到身份验证令牌.然后,我可以使用内置的hasRole,hasPermission表达式来实现访问控制.
I have implemented a custom AbstractAuthenticationProcessingFilter & AuthenticationProvider for authentication, which ends up granting roles to the principal. I can inspect the pathvariables in the servlet request (using HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE), and add additional authorities to the Authentication token. Then I can use the built-in hasRole, hasPermission expressions to implement access control.
我可以扩展WebSecurityExpressionRoot并实现自定义AbstractSecurityExpressionHandler并定义我自己的表达式,以在拦截URL访问控制表达式中使用.我不确定在WebSecurityExpressionRoot实现中定义自定义方法时如何访问@PathVariables.
I can extend WebSecurityExpressionRoot and implement a custom AbstractSecurityExpressionHandler and define my own expressions to be used in the intercept-url access-control expressions. I'm not sure how I can access the @PathVariables when defining custom methods in my WebSecurityExpressionRoot implementation.
哪种方法更可取,或者还有另一种方法可以干净地做到这一点?
Which approach is preferable, or is there another way to do this cleanly?
推荐答案
我确实有解决方案. 在配置类中
I do have a solution. In a configuration class
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
我可以有方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/student/{id}/**")
.access("@guard.checkUserId(authentication,#id)");
}
同时SpEL中的@guard链接到
while @guard in SpEL links to
@Component
public class Guard {
@Autowired
private UserRepository repo;
public boolean checkUserId(Authentication authentication, int id) {
String name = authentication.getName();
System.out.println(name+" at "+id);
User result = repo.findByUsername(name);
return result != null && result.getPid() == id;
}
}
在实践中,SpEL中的#id可以获取从上一行的{id}中提取的值.您可以在checkUserId中执行任何操作,然后返回值决定是否允许访问路径.
In practice, the #id in SpEL can get the value extracted from {id} in the previous line. You can do whatever you want in checkUserId, and the return value decides whether the access to the path would be allowed.
这篇关于基于路径变量的弹簧安全性授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!