如何解决Spring Security,我们如何从数据库动态创建授权规则反制
在数据库中存储授权规则反制URL和角色并在服务器启动时动态创建是一种好习惯吗?
如果对应用程序有请求,则每次使用从数据库中获取来创建规则时,都会在WebSecurityConfigurerAdapter的Configure方法中从数据库中获取规则。
我找不到任何示例,说明我们如何仅从数据库动态创建新规则而不更改应用程序代码。
这是我要动态创建规则的示例代码
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/dashboard/**").hasAuthority("VIEW_DASHBOARD")
.antMatchers("/dashboard/**").hasAuthority("EDIT_DASHBOARD")
.antMatchers("/dashboard/**").hasAuthority("DELETE_DASHBOARD")
.antMatchers("/profiling/**").hasAuthority("VIEW_PROFILING")
.antMatchers("/profiling/**").hasAuthority("EDIT_PROFILING")
.antMatchers("/profiling/**").hasAuthority("DELETE_PROFILING");
}
解决方法
您可以创建您的 AccessDecisionVoter
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// you can inject AccessDecisionVoter in spring container
List<AccessDecisionVoter<?>> decisionVoters = new ArrayList<>();
decisionVoters.add(new AccessDecisionVoter<FilterInvocation>() {
@Override
public boolean supports(ConfigAttribute attribute) {
return true;
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication,FilterInvocation invocation,Collection<ConfigAttribute> attributes) {
String url = invocation.getRequestUrl();
AntPathMatcher m = new AntPathMatcher();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
boolean matched = false;
// you can retrieve url pattern from database here
if (m.match("/**",url) && CollectionUtils.isEmpty(authorities) == false) {
matched = authorities.stream().anyMatch(a -> {
return a.getAuthority().equals("your_authority");
});
}
if (matched) {
return AccessDecisionVoter.ACCESS_GRANTED;
} else {
return AccessDecisionVoter.ACCESS_DENIED;
}
}
});
AffirmativeBased aa = new AffirmativeBased(decisionVoters);
http.authorizeRequests().accessDecisionManager(aa);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。