发表文章

[最新] 运行时修改Acegi中authorities 授权信息

iteye9178 2009-11-19 1

运行时修改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 -->
相关推荐
最新评论 (0)
返回
发表文章
iteye9178
文章数
31
评论数
0
注册排名
1342716