服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - spring security动态配置url权限的2种实现方法

spring security动态配置url权限的2种实现方法

2021-05-08 10:41JadePeng Java教程

对于使用spring security来说,存在一种需求,就是动态去配置url的权限,即在运行时去配置url对应的访问角色。下面这篇文章主要给大家介绍了关于spring security动态配置url权限的2种实现方法,需要的朋友可以参考下

缘起

标准的rabc, 权限需要支持动态配置,spring security默认是在代码里约定好权限,真实的业务场景通常需要可以支持动态配置角色访问权限,即在运行时去配置url对应的访问角色。

基于spring security,如何实现这个需求呢?

最简单的方法就是自定义一个filter去完成权限判断,但这脱离了spring security框架,如何基于spring security优雅的实现呢?

spring security 授权回顾

spring security 通过filterchainproxy作为注册到web的filter,filterchainproxy里面一次包含了内置的多个过滤器,我们首先需要了解spring security内置的各种filter:

 

alias filter class namespace element or attribute
channel_filter channelprocessingfilter http/intercept-url@requires-channel
security_context_filter securitycontextpersistencefilter http
concurrent_session_filter concurrentsessionfilter session-management/concurrency-control
headers_filter headerwriterfilter http/headers
csrf_filter csrffilter http/csrf
logout_filter logoutfilter http/logout
x509_filter x509authenticationfilter http/x509
pre_auth_filter abstractpreauthenticatedprocessingfilter subclasses n/a
cas_filter casauthenticationfilter n/a
form_login_filter usernamepasswordauthenticationfilter http/form-login
basic_auth_filter basicauthenticationfilter http/http-basic
servlet_api_support_filter securitycontextholderawarerequestfilter http/@servlet-api-provision
jaas_api_support_filter jaasapiintegrationfilter http/@jaas-api-provision
remember_me_filter remembermeauthenticationfilter http/remember-me
anonymous_filter anonymousauthenticationfilter http/anonymous
session_management_filter sessionmanagementfilter session-management
exception_translation_filter exceptiontranslationfilter http
filter_security_interceptor filtersecurityinterceptor http
switch_user_filter switchuserfilter n/a

 

最重要的是filtersecurityinterceptor,该过滤器实现了主要的鉴权逻辑,最核心的代码在这里:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
protected interceptorstatustoken beforeinvocation(object object) {
 // 获取访问url所需权限
 collection<configattribute> attributes = this.obtainsecuritymetadatasource()
 .getattributes(object);
 
 
 authentication authenticated = authenticateifrequired();
 
 // 通过accessdecisionmanager鉴权
 try {
 this.accessdecisionmanager.decide(authenticated, object, attributes);
 }
 catch (accessdeniedexception accessdeniedexception) {
 publishevent(new authorizationfailureevent(object, attributes, authenticated,
  accessdeniedexception));
 
 throw accessdeniedexception;
 }
 
 if (debug) {
 logger.debug("authorization successful");
 }
 
 if (publishauthorizationsuccess) {
 publishevent(new authorizedevent(object, attributes, authenticated));
 }
 
 // attempt to run as a different user
 authentication runas = this.runasmanager.buildrunas(authenticated, object,
 attributes);
 
 if (runas == null) {
 if (debug) {
 logger.debug("runasmanager did not change authentication object");
 }
 
 // no further work post-invocation
 return new interceptorstatustoken(securitycontextholder.getcontext(), false,
  attributes, object);
 }
 else {
 if (debug) {
 logger.debug("switching to runas authentication: " + runas);
 }
 
 securitycontext origctx = securitycontextholder.getcontext();
 securitycontextholder.setcontext(securitycontextholder.createemptycontext());
 securitycontextholder.getcontext().setauthentication(runas);
 
 // need to revert to token.authenticated post-invocation
 return new interceptorstatustoken(origctx, true, attributes, object);
 }
 }

从上面可以看出,要实现动态鉴权,可以从两方面着手:

  • 自定义securitymetadatasource,实现从数据库加载configattribute
  • 另外就是可以自定义accessdecisionmanager,官方的unanimousbased其实足够使用,并且他是基于accessdecisionvoter来实现权限认证的,因此我们只需要自定义一个accessdecisionvoter就可以了

下面来看分别如何实现。

自定义accessdecisionmanager

官方的三个accessdecisionmanager都是基于accessdecisionvoter来实现权限认证的,因此我们只需要自定义一个accessdecisionvoter就可以了。

自定义主要是实现accessdecisionvoter接口,我们可以仿照官方的rolevoter实现一个:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class rolebasedvoter implements accessdecisionvoter<object> {
 @override
 public boolean supports(configattribute attribute) {
 return true;
 }
 
 @override
 public int vote(authentication authentication, object object, collection<configattribute> attributes) {
 if(authentication == null) {
 return access_denied;
 }
 int result = access_abstain;
 collection<? extends grantedauthority> authorities = extractauthorities(authentication);
 for (configattribute attribute : attributes) {
 if(attribute.getattribute()==null){
 continue;
 }
 if (this.supports(attribute)) {
 result = access_denied;
 
 // attempt to find a matching granted authority
 for (grantedauthority authority : authorities) {
  if (attribute.getattribute().equals(authority.getauthority())) {
  return access_granted;
  }
 }
 }
 }
 return result;
 }
 
 collection<? extends grantedauthority> extractauthorities(
 authentication authentication) {
 return authentication.getauthorities();
 }
 
 @override
 public boolean supports(class clazz) {
 return true;
 }
}

如何加入动态权限呢?

vote(authentication authentication, object object, collection<configattribute> attributes)里的object object的类型是filterinvocation,可以通过getrequesturl获取当前请求的url:

?
1
2
filterinvocation fi = (filterinvocation) object;
string url = fi.getrequesturl();

因此这里扩展空间就大了,可以从db动态加载,然后判断url的configattribute就可以了。

如何使用这个rolebasedvoter呢?在configure里使用accessdecisionmanager方法自定义,我们还是使用官方的unanimousbased,然后将自定义的rolebasedvoter加入即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@enablewebsecurity
@enableglobalmethodsecurity(prepostenabled = true, securedenabled = true)
public class securityconfiguration extends websecurityconfigureradapter {
 @override
 protected void configure(httpsecurity http) throws exception {
 http
 .addfilterbefore(corsfilter, usernamepasswordauthenticationfilter.class)
 .exceptionhandling()
 .authenticationentrypoint(problemsupport)
 .accessdeniedhandler(problemsupport)
 .and()
 .csrf()
 .disable()
 .headers()
 .frameoptions()
 .disable()
 .and()
 .sessionmanagement()
 .sessioncreationpolicy(sessioncreationpolicy.stateless)
 .and()
 .authorizerequests()
 // 自定义accessdecisionmanager
 .accessdecisionmanager(accessdecisionmanager())
 .and()
 .apply(securityconfigureradapter());
 
 }
 
 @bean
 public accessdecisionmanager accessdecisionmanager() {
 list<accessdecisionvoter<? extends object>> decisionvoters
 = arrays.aslist(
 new webexpressionvoter(),
 // new rolevoter(),
 new rolebasedvoter(),
 new authenticatedvoter());
 return new unanimousbased(decisionvoters);
 }

自定义securitymetadatasource

自定义filterinvocationsecuritymetadatasource只要实现接口即可,在接口里从db动态加载规则。

为了复用代码里的定义,我们可以将代码里生成的securitymetadatasource带上,在构造函数里传入默认的filterinvocationsecuritymetadatasource。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class appfilterinvocationsecuritymetadatasource implements org.springframework.security.web.access.intercept.filterinvocationsecuritymetadatasource {
 private filterinvocationsecuritymetadatasource supermetadatasource;
 @override
 public collection<configattribute> getallconfigattributes() {
 return null;
 }
 
 public appfilterinvocationsecuritymetadatasource(filterinvocationsecuritymetadatasource expressionbasedfilterinvocationsecuritymetadatasource){
  this.supermetadatasource = expressionbasedfilterinvocationsecuritymetadatasource;
  // todo 从数据库加载权限配置
 }
 
 private final antpathmatcher antpathmatcher = new antpathmatcher();
 
 // 这里的需要从db加载
 private final map<string,string> urlrolemap = new hashmap<string,string>(){{
 put("/open/**","role_anonymous");
 put("/health","role_anonymous");
 put("/restart","role_admin");
 put("/demo","role_user");
 }};
 
 @override
 public collection<configattribute> getattributes(object object) throws illegalargumentexception {
 filterinvocation fi = (filterinvocation) object;
 string url = fi.getrequesturl();
 for(map.entry<string,string> entry:urlrolemap.entryset()){
  if(antpathmatcher.match(entry.getkey(),url)){
  return securityconfig.createlist(entry.getvalue());
  }
 }
 // 返回代码定义的默认配置
 return supermetadatasource.getattributes(object);
 }
 
 @override
 public boolean supports(class<?> clazz) {
 return filterinvocation.class.isassignablefrom(clazz);
 }
}

怎么使用?和accessdecisionmanager不一样,expressionurlauthorizationconfigurer 并没有提供set方法设置filtersecurityinterceptor的filterinvocationsecuritymetadatasource,how to do?

发现一个扩展方法withobjectpostprocessor,通过该方法自定义一个处理filtersecurityinterceptor类型的objectpostprocessor就可以修改filtersecurityinterceptor。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@enablewebsecurity
@enableglobalmethodsecurity(prepostenabled = true, securedenabled = true)
public class securityconfiguration extends websecurityconfigureradapter {
 @override
 protected void configure(httpsecurity http) throws exception {
 http
  .addfilterbefore(corsfilter, usernamepasswordauthenticationfilter.class)
  .exceptionhandling()
  .authenticationentrypoint(problemsupport)
  .accessdeniedhandler(problemsupport)
 .and()
  .csrf()
  .disable()
  .headers()
  .frameoptions()
  .disable()
 .and()
  .sessionmanagement()
  .sessioncreationpolicy(sessioncreationpolicy.stateless)
 .and()
  .authorizerequests()
  // 自定义filterinvocationsecuritymetadatasource
  .withobjectpostprocessor(new objectpostprocessor<filtersecurityinterceptor>() {
  @override
  public <o extends filtersecurityinterceptor> o postprocess(
   o fsi) {
   fsi.setsecuritymetadatasource(mysecuritymetadatasource(fsi.getsecuritymetadatasource()));
   return fsi;
  }
  })
 .and()
  .apply(securityconfigureradapter());
 }
 
 @bean
 public appfilterinvocationsecuritymetadatasource mysecuritymetadatasource(filterinvocationsecuritymetadatasource filterinvocationsecuritymetadatasource) {
 appfilterinvocationsecuritymetadatasource securitymetadatasource = new appfilterinvocationsecuritymetadatasource(filterinvocationsecuritymetadatasource);
 return securitymetadatasource;
}

小结

本文介绍了两种基于spring security实现动态权限的方法,一是自定义accessdecisionmanager,二是自定义filterinvocationsecuritymetadatasource。实际项目里可以根据需要灵活选择。

延伸阅读:

spring security 架构与源码分析

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.cnblogs.com/xiaoqi/p/spring-security-rabc.html

延伸 · 阅读

精彩推荐