上门链接是上次分享了在jfinal中添加jcaptcha验证码
后看到@的jfinal-shiro插件,顺便将验证码加入
MyShiroRealm.java
/** * 认证回调函数, 登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { //是否启用验证码 if (useCaptcha) { CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken; String parm = token.getCaptcha(); if (StringUtils.isNotBlank(parm)) parm = parm.toUpperCase(); try { if (!CaptchaServiceSingleton.getInstance().validateResponseForID(SecurityUtils .getSubject().getSession().getId().toString(), parm)) { throw new IncorrectCaptchaException("验证码错误!"); } } catch (Exception e) { // session如果没有刷新,validateResponseForID会抛出com.octo.captcha.service.CaptchaServiceException的异常 throw new IncorrectCaptchaException("验证码错误!"); } } UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String password = String.valueOf(token.getPassword()); // 调用操作数据库的方法查询user信息 User user = User.dao.getUserByName(token.getUsername()); if (user != null) { byte[] salt = Encodes.decodeHex(user.getStr(User.SALT)); Listroles = Role.dao.getRoleByUser(user.getStr(User.ID)); ShiroUser shiroUser = new ShiroUser(user.getStr(User.ID), user.getStr(User.USERNAME), user,roles); Session session = SecurityUtils.getSubject().getSession(); session.setAttribute(SecurityConstants.LOGIN_USER, shiroUser); // 这里可以缓存认证 return new SimpleAuthenticationInfo(shiroUser, user.getStr(User.PASSWORD), ByteSource.Util.bytes(salt), getName()); } else { return null; } }
view-login.ftl
登录