new無语 转载请注明原创出处,谢谢!
GlobalMethodSecurityConfiguration
我们通过Spring Security的GlobalMethodSecurityConfiguration
配置类来进行方法级别的安全规则添加。
其中这段代码是进行添加启动注解规则安全验证(securedEnabled = true
等)。
在这里我们进行添加自定义的校验规则。这个规则是验证Spring所管理的bean的调用。
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
List<MethodSecurityMetadataSource> sources = new ArrayList<MethodSecurityMetadataSource>();
ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
getExpressionHandler());
MethodSecurityMetadataSource customMethodSecurityMetadataSource = customMethodSecurityMetadataSource();
if (customMethodSecurityMetadataSource != null) {
sources.add(customMethodSecurityMetadataSource);
}
if (prePostEnabled()) {
sources.add(new PrePostAnnotationSecurityMetadataSource(attributeFactory));
}
if (securedEnabled()) {
sources.add(new SecuredAnnotationSecurityMetadataSource());
}
if (jsr250Enabled()) {
GrantedAuthorityDefaults grantedAuthorityDefaults =
getSingleBeanOrNull(GrantedAuthorityDefaults.class);
if (grantedAuthorityDefaults != null) {
this.jsr250MethodSecurityMetadataSource.setDefaultRolePrefix(
grantedAuthorityDefaults.getRolePrefix());
}
sources.add(jsr250MethodSecurityMetadataSource);
}
return new DelegatingMethodSecurityMetadataSource(sources);
}
通过下面预留的自定义方法,进行重写实现自定义规则添加。
/**
* Provides a custom {@link MethodSecurityMetadataSource} that is registered with the
* {@link #methodSecurityMetadataSource()}. Default is null.
*
* @return a custom {@link MethodSecurityMetadataSource} that is registered with the
* {@link #methodSecurityMetadataSource()}
*/
protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
return null;
}
重写demo,写的比较简单。通俗达意就可以了。
@EnableGlobalMethodSecurity(
securedEnabled = true,
prePostEnabled = true,
jsr250Enabled = true
)
class SpringMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
List<MethodSecurityMetadataSource> sources = new ArrayList<MethodSecurityMetadataSource>();
Map<String, List<ConfigAttribute>> methodMap = new HashMap<>();
List<ConfigAttribute> configAttributes = Arrays.asList(new SecurityConfig("ROLE_ADMIN1"));
methodMap.put("com.zee.springcloudsecurity.controller.TestController.test13", configAttributes);
MethodSecurityMetadataSource methodSecurityMetadataSource = new MapBasedMethodSecurityMetadataSource(methodMap);
Map<String, List<ConfigAttribute>> methodMap2 = new HashMap<>();
List<ConfigAttribute> configAttributes2 = Arrays.asList(new SecurityConfig("ROLE_ADMIN"));
methodMap2.put("com.zee.springcloudsecurity.controller.TestController.test14", configAttributes2);
MethodSecurityMetadataSource methodSecurityMetadataSource2 = new MapBasedMethodSecurityMetadataSource(methodMap2);
sources.add(methodSecurityMetadataSource);
sources.add(methodSecurityMetadataSource2);
return new DelegatingMethodSecurityMetadataSource(sources);
}
}
网友评论