之前介绍了Shiro的Web访问控制和缓存配置,其实Shiro和Spring一样可以使用Annotation来配置方法级别的安全,省去自己每次获取Subject去做权限验证,比如在修改用户密码的时候只能是用户本人,在修改用户用户帐号的状态(lock/unlock)只有管理员可以,这些操作都需要方法级别的安全保护。
如果要自己获取当前的登录User信息,可以通过Shiro的SecurityUtils来实现,然后对User的权限做判断:
private User getCurrentUser(){
Subject currentUser = SecurityUtils.getSubject();
return userManager.getUserByName((String) currentUser.getPrincipal());
}
如果使用Annotation,这些东西都是由Shiro来帮你实现了,你只要在业务方法上面加上相应的权限管理,一般来说使用的是都是每个对象的读写的权限,如果简单系统,可以把User对应的Role当成权限管理对象。给个简单例子:
@Override
@RequiresRoles("ROLE_ADMIN")
public Show save(Show show){
if(null != show.getId()){
//due to create/update time is not passed back from page
Show oldShow = findById(show.getId());
if(null == oldShow){
return null;
}
List<String> oldFilelist = LYTZUtils.getFilePathFromContent(oldShow.getContent());
if(LOG.isDebugEnabled()){
LOG.debug("the old content contains " + oldFilelist.size() + " images in image server");
}
show = super.save(show);
List<String> newFilelist = LYTZUtils.getFilePathFromContent(show.getContent());
for(String filePath : oldFilelist){
if(!newFilelist.contains(filePath) && fileService.isFileExists(filePath)){
if(LOG.isDebugEnabled()){
LOG.debug("unusedFile: " + filePath);
}
fileService.removeFile(filePath);
}
}
return show;
} else {
return super.save(show);
}
}
Shiro提供的annotation包括了基本验证:@RequiresAuthentication,@RequiresUser,@RequiresGuest ,角色验证:@RequiresRoles(value={“ROLE_VIP”, “ROLE_USER”}, logical= Logical.AND) ,@RequiresPermissions (value={“read”, “write”}, logical= Logical.OR)