运行时修改Acegi中authorities 授权信息

运行时修改Acegi中authorities 授权信息


用户授权信息在登录的时候就被存放在securityContextHolder,我们可以再任何时候去查看这些授权信息。
下面的代码可以获得当前授权信息:

Authentication currentUser = securityContextHolder.getContext().getAuthentication();
UserDetailsImpl userDetails = (UserDetailsImpl) currentUser.getPrincipal();
GrantedAuthority gas[] =userDetails.getAuthorities();

 
然后,我想添加一些授权到这个数组gas,然后再次放回当前用户使之生效。

userDetails.setAuthorities(gas);

 

My web interface is made using acegi taglibs in order to render the menu only with granted options:

Code:
<authz:authorize ifAnyGranted="MENU1,MENU2">
But, after refreshing or rendering again the JSP, it looks like the new granted options are not available (or the user authorities are not updated) and I can't see the new menu options that I should see.

Anyone could help me whit this? Any idea?

解决办法

Okay ... I found the solution.

Acegi securitycontext stores the user information in the ContextHolder. And you can get all the information of the authenticated user.

You can change the authorities in this way:
SecurityContext sc = SecurityContextHolder.getContext();
Authentication currentUser = sc.getAuthentication();
UserDetailsImpl userDetails = (UserDetailsImpl) currentUser.getPrincipal();

ArrayList authorities = new ArrayList(2);
authorities.add(new GrantedAuthorityImpl("DUMMY"));
			userDetails.setAuthorities((GrantedAuthority[])authorities.toArray(new GrantedAuthority[]{}));
 
But this is only valid for the life of the current thread. If you need to make persistent this every time you invoke the above code:
Code:
SecurityContext sc = SecurityContextHolder.getContext();
Authentication currentUser = sc.getAuthentication();
UserDetailsImpl userDetails = (UserDetailsImpl) currentUser.getPrincipal();
You have to re-aunthenticate the authentication token (in my issue, an UsernamePasswordAuthenticationToken) in this way:
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(currentUser.getPrincipal(),currentUser.getCredentials(),(GrantedAuthority[])authorities.toArray(new GrantedAuthority[]{}));

sc.setAuthentication(authentication);
SecurityContextHolder.setContext(sc);
 
Now, the changes will be available every time you need it.
<!-- / message -->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值