该项目仅作为简单的ssm整合shiro的demo使用,部分代码仅简单实现。
该文只贴出与shiro相关的配置,完整代码可见https://github.com/Zhong-Y/shiro_ssm
UserRealm.java
realm在shiro框架中用于认证、授权等操作。为了满足业务的需求,通常在使用时,使用的是继承了AuthorizingRealm的自定义realm.
public class UserRealm extends AuthorizingRealm{
@Autowired
TUserMapper userMapper;
@Autowired
TUserRoleMapper userRolerMapper;
// 设置realm的名称
@Override
public void setName(String name) {
super.setName("userRealm");
}
//认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("====================认证=====================");
//根据username查询用户
String username = (String) token.getPrincipal();
TUserExample example = new TUserExample();
Criteria criteria = example.createCriteria();
criteria.andUserNameEqualTo(username);
List list = userMapper.selectByExample(example);
TUser user = null;
if(list != null && !list.isEmpty()) {
user = list.get(0);
}
//如果没有查询到用户返回null
if(user == null) {
return null;
}
String id = user.getUserId();
String password = user.getUserPassword();
String salt = user.getUserSalt();
//获取用户角色 ...省略
String userRoleId = "1";
//根据身份信息获取权限信息,并将权限添加到在线用户中....省略
List permissions = new ArrayList();
permissions.add("user:query");
//设置在线用户属性
ActiveUser activeUser = new ActiveUser();
activeUser.setUserRoleId(userRoleId);
activeUser.setUserName(username);
activeUser.setUserId(id);
activeUser.setUserSalt(salt);
activeUser.setPermissions(permissions);
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(activeUser, password,
ByteSource.Util.bytes(salt), this.getName());
return simpleAuthenticationInfo;
}
//授权
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("===================授权==============================");
//从 principals获取主身份信息
//将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型),
ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
//根据身份信息获取权限信息,并将权限添加到在线用户中
List permissions = activeUser.getPermissions();
//查到权限数据,返回授权信息(要包括 上边的permissions)
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//将上边查询到授权信息填充到simpleAuthorizationInfo对象中
simpleAuthorizationInfo.addStringPermissions(permissions);
return simpleAuthorizationInfo;
}
//清除缓存
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}
}
MyFormAuthenticationFilter.java
由于shiro自带的FormAuthenticationFilter仅实现了用户的账号密码认证,而我们还需对验证码进行判断,因此,在这里,我们使用的是自定义的FormAuthenticationFilter。我们将重写它的认证方法,使得在进行账号密码认证前对验证码进行校验。
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue)
throws Exception {
// 校验验证码
// 从session获取正确的验证码
HttpSession session = ((HttpServletRequest) request).getSession();
// 页面输入的验证码
String randomcode = request.getParameter("randomCode");
// 从session中取出服务器生成的验证码
String validateCode = (String) session.getAttribute("randomCode");
if (randomcode != null && validateCode != null) {
// 如果验证码错误,则拒绝访问,不再校验账号和密码
if (!randomcode.equalsIgnoreCase(validateCode)) {
// 存储错误信息
request.setAttribute("shiroLoginFailure", "randomCodeError");
return true;
}
}
//验证码正确,校验账号密码
return super.onAccessDenied(request, response, mappedValue);
}
}
web.xml
配置shiro过滤器:初始化bean的id,及设置filter的匹配规则
contextConfigLocation
classpath:spring/applicationContext-*.xml
org.springframework.web.context.ContextLoaderListener
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring/springmvc.xml
1
springmvc
/
shiroFilter
org.springframework.web.filter.DelegatingFilterProxy
targetFilterLifecycle
true
targetBeanName
shiroFilter
shiroFilter
/*
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
CharacterEncodingFilter
/*
applicationContext-shiro.xml
进行shiro的相关配置
/randomCode = anon
/logout = logout
/ = user
/success = user
/test = perms["admin:query"]
/test3 = perms["user:query"]
/** = authc
shiro-ehcache.xml
shiro的缓存策略配置,若项目中没有配置缓存,则在每一次访问时都会进行授权操作。配置后,仅第一次访问需要权限的url时进行授权,之后直接存缓存中取出授权信息。
UserController.java
Controller,对shiro相关配置进行测试。
其中,用户的登陆、退出操作都已在shiro的配置文件进行了配置,退出操作无需编写,登陆操作仅需写些登陆失败的相关处理及登陆成功的跳转url即可。
@Controller
public class UserController {
//注入realm
@Autowired
private UserRealm userRealm;
@RequestMapping(value="/clearShiroCache", produces="application/json; charset=utf-8")
@ResponseBody
public String clearShiroCache() {
// 清除缓存,将来正常开发要在service调用customRealm.clearCached()
userRealm.clearCached();
return "shiro授权缓存已清除";
}
@RequestMapping("/")
public String defaultIndex() {
return "success";
}
// 登陆提交地址,和applicationContext-shiro.xml中配置的loginurl一致
// 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
@RequestMapping("login")
public String login(HttpServletRequest request) throws Exception {
// 如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
// 根据shiro返回的异常类判断错误原因
if (exceptionClassName != null) {
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
System.out.println("=============账号不存在=============");
} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
System.out.println("=============用户名/密码错误=============");
} else if ("randomCodeError".equals(exceptionClassName)) {
System.out.println("=============验证码错误=============");
} else {
System.out.println("=============未知错误=============");
}
}
// 登陆失败跳回login.jsp
return "login";
}
//没权限时测试
@ResponseBody
@RequestMapping(value="/test", produces="application/json; charset=utf-8")
public String test1() {
return "这是test1";
}
//没权限时测试2,通过注解配置权限
@ResponseBody
@RequestMapping(value="/test2", produces="application/json; charset=utf-8")
@RequiresPermissions("admin:query")
public String test2() {
return "这是test2";
}
//有权限时测试
@ResponseBody
@RequestMapping(value="/test3", produces="application/json; charset=utf-8")
public String test3() {
return "这是test3";
}
//有权限时测试2,通过注解配置权限
@ResponseBody
@RequestMapping(value="/test4", produces="application/json; charset=utf-8")
@RequiresPermissions("user:query")
public String test4() {
return "这是test4";
}
//生成验证码
@RequestMapping("/randomCode")
public void randomCode(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置相应类型,告诉浏览器输出的内容为图片
response.setContentType("image/jpeg");
//设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
RandomValidateCode randomValidateCode = new RandomValidateCode();
try {
//输出图片方法
randomValidateCode.getRandcode(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在使用@RequiresPermissions注解添加权限时,需在springmvc.xml中添加对shiro注解的支持