welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ群:162333776 邮箱:admin@xlongwei.com

Shiro切换身份之runAs


分类 Java   关键字 分享   标签 java   web   tomcat   spring   发布 hongwei  1501577783882
注意 转载须保留原文链接,译文链接,作者译者等信息。  
Shiro是非常简单的认证和授权组件,用户主体对象Subject含有runAs、releaseRunAs、isRunAs等方法,可用于临时切换主体身份。

runAs,为了安全性最好是要求管理员权限
@RequestMapping("runAs") @RequiresRoles("A") public String runAs(String userName) {
Subject subject = SecurityUtils.getSubject();
User user = userService.getUserByUserName(userName);
if(user!=null && !subject.isRunAs()) {
subject.runAs(new SimplePrincipalCollection(userName, subject.getPrincipals().getRealmNames().iterator().next()));
subject.getSession().setAttribute("userId", user.getId());//设置当前用户信息
}
return "redirect:/account/index.html";//跳至用户中心
}

releaseRunAs,认证用户都可以退出切换
@RequestMapping("runRelease") @RequiresAuthentication public String runRelease() {
Subject subject = SecurityUtils.getSubject();
if(subject.isRunAs()) {
subject.releaseRunAs();//退出身份切换
User user = userBizService.getUserByUserName(subject.getPrincipal().toString()).getObject();
subject.getSession().setAttribute("userId", user.getId());//恢复用户信息
}
return "redirect:/admin/home.html";//回到管理员页面
}

runAs,后台其实执行了UserRealm的授权逻辑
public class UserRealm extends AuthorizingRealm {
@Autowired private CustomerService customerService;
@Autowired private RolePermissionService rolePermissionService;
//每次登陆或RunAs,每次权限判断subject.hasRole("A")都会调用此方法
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(rolePermissionService.getRoles(username));
return authorizationInfo;
}
//登陆后会设置session内容,runAs则需要手动设置相应内容
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = customerService.getUserByUserName(username).getObject();
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("userId", user.getId());
return new SimpleAuthenticationInfo( user.getUserName(), user.getPassword(),
ByteSource.Util.bytes(user.getUserName()+user.getSalt()), getName()
);
}
}