实现登录验证、权限验证、缓存存储提高查询效率等功能,主要看思路而不是跑通,这是我配置的真实的项目实例
思路:1登录首先经过过滤器类RequestFilter - 2登录控制器LoginController -3AuthRealm 登录认证 - 4认证成功登录主页(认证缓存)
main.js 加载菜单数据需要请求MenuController 中的方法(利用到自定义缓存)
这里权限认证没有给出,有时间跟大家分享,登录表结构设计以及shiro权限认证的前后台实现思路
spring-mvc.xml
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
spring-shiro.xml
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
ehcache-shiro.xml
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
pom.xml
AuthRealm
package com.qkkj.hardwaremgmt.framework.security;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.qkkj.hardwaremgmt.database.beans.SysUser;
import com.qkkj.hardwaremgmt.database.service.IMenuService;
import com.qkkj.hardwaremgmt.database.service.ISysUserService;
import com.qkkj.hardwaremgmt.framework.config.SysConstants;
import com.qkkj.hardwaremgmt.framework.util.EmptyUtil;
import com.qkkj.hardwaremgmt.framework.util.MySimpleByteSource;
/**
* @Title: AuthRealm.java
* @Package com.qkkj.usrmgmt.framework.security
* @Description: shiro安全认证
* @author fuxin
* @date 2018年2月25日 上午11:16:38
* @version V1.0
*/
public class AuthRealm extends AuthorizingRealm {
@Autowired
private ISysUserService sysUserService;
@Autowired
private IMenuService menuService;
/*
* 权限认证
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//获取登录时输入的用户名
String accountName=(String) principals.fromRealm(getName()).iterator().next();
//从缓存中获取权限认证信息
Cache
}
package com.qkkj.hardwaremgmt.framework.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* @Title: RequestFilter.java
* @Package com.qkkj.hardwaremgmt.framework.filter
* @Description: 拦截处理
* @author fuxin
* @date 2018年5月15日 上午9:17:34
* @version V1.0
*/
@ControllerAdvice
public class RequestFilter extends OncePerRequestFilter {
/*
* 拦截请求
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String urlStr = request.getRequestURI();
if(null != SecurityUtils.getSubject()) {//只允许一个用户登录同一个浏览器窗口
String htmlUserAccount = request.getParameter("userAccount");
Subject currentUser = SecurityUtils.getSubject();
String sessionUserAccount = (String) currentUser.getSession().getAttribute("userAccount");
if(StringUtils.isNotBlank(htmlUserAccount)&&StringUtils.isNotBlank(sessionUserAccount)) {
if(!StringUtils.equals(htmlUserAccount, sessionUserAccount)) {
response.addHeader("sessionstatus", "timeOut");
return;
}
}
}
if(urlStr.equals("/main")) {
Subject currentUser = SecurityUtils.getSubject();
if(currentUser.isAuthenticated()) {
request.getRequestDispatcher("/qkkjapp/views/main.html").forward(request, response);
}
else {
response.sendRedirect("/");
}
}else if (urlStr.equals("/loginController/login")) {
Subject currentUser = SecurityUtils.getSubject();
if(null != currentUser) {
currentUser.logout();
}
filterChain.doFilter(request, response);
}
else {
filterChain.doFilter(request, response);
}
}
}
LoginController
package com.qkkj.hardwaremgmt.web.controller;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.Valid;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.qkkj.hardwaremgmt.database.beans.SysUser;
import com.qkkj.hardwaremgmt.database.service.CodeService;
import com.qkkj.hardwaremgmt.database.service.IMenuService;
import com.qkkj.hardwaremgmt.database.service.ISysUserService;
import com.qkkj.hardwaremgmt.framework.base.BaseController;
import com.qkkj.hardwaremgmt.framework.config.SysConstants;
import com.qkkj.hardwaremgmt.framework.enums.TablePrefixEnum;
import com.qkkj.hardwaremgmt.framework.util.AuthUtil;
import com.qkkj.hardwaremgmt.framework.util.CommonUtil;
import com.qkkj.hardwaremgmt.framework.util.EmptyUtil;
import com.qkkj.hardwaremgmt.framework.util.KeyGenerator;
import com.qkkj.hardwaremgmt.web.condition.LoginVO;
import com.qkkj.hardwaremgmt.web.condition.SetPasswordVO;
import com.qkkj.hardwaremgmt.web.util.ApiResult;
/**
*
* @Title: LoginController.java
* @Package com.qkkj.usrmgmt.web.controller
* @Description: 用户登录
* @author wangfudong
* @date 2018年5月23日 上午11:06:26
* @version V1.0
*/
@Controller
@RequestMapping("/loginController")
public class LoginController extends BaseController {
@Autowired
private IMenuService menuService;
@Autowired
private ISysUserService ISysUserService;
@Autowired
private CodeService CodeService;
/**
* 用户登录
*
* @param sysUser
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public ApiResult
// 校验信息
String errorStr = CommonUtil.validError(result);
if (EmptyUtil.isNotEmpty(errorStr)) {
return ApiResult.error(errorStr);
}
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(loginVO.getUserAccount(), loginVO.getPassword());
token.setRememberMe(true);
try {
currentUser.login(token);
currentUser.getSession().setAttribute("userAccount", token.getUsername());
menuService.putIntoCache(token.getUsername());
return ApiResult.success();
}
// 没有指定的账户
catch (UnknownAccountException uae) {
return ApiResult.error(getMessage("loginController.checkUserAccount.error"));
}
// 密码不匹配
catch (IncorrectCredentialsException ice) {
return ApiResult.error(getMessage("loginController.checkUserAccount.error"));
}
// 用户被锁定
catch (LockedAccountException lae) {
return ApiResult.error(getMessage("loginController.checkUserAccountState.error"));
}
// 所有认证时异常的父类
catch (AuthenticationException ae) {
return ApiResult.error(getMessage("loginController.loginException.error"));
} finally {
// 登录不成功,清除token
if (!currentUser.isAuthenticated()) {
token.clear();
}
}
}
return ApiResult.success();
}
@RequestMapping(value = "/getcode", method = RequestMethod.POST)
@ResponseBody
public ApiResult
String code = KeyGenerator.getCheckCode();
loginVO.setCheckCode(code);
loginVO.setCheck_code_id(KeyGenerator.getId(TablePrefixEnum.TB0000015.getCode()));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
loginVO.setCreate_date(df.format(now));
Date afterDate = new Date(now.getTime() + 300000);
loginVO.setExpire_date(df.format(afterDate));
Boolean f = CodeService.insertcode(loginVO);
if (!f) {
return ApiResult.error(getMessage("data.error"));
}
return ApiResult.success();
}
@SuppressWarnings("unused")
@RequestMapping(value = "/setpass", method = RequestMethod.POST)
@ResponseBody
public ApiResult
SysUser UserAccount =ISysUserService.getuserbyname(loginVO.getUserAccount());
if(UserAccount==null) {
return ApiResult.error("no find user or user lock");
}
SetPasswordVO user = CodeService.getcodebymobile(loginVO.getMobile());
if (user == null) {
return ApiResult.error("no find Mobile or code use");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
Date Expiredate = df.parse(user.getExpire_date());
if (user.getCheckCode().equals(loginVO.getCheckCode())) {
if (now.getTime() < Expiredate.getTime()) {
if (loginVO.getPassword().equals(loginVO.getComfirePassword())) {
loginVO.setPassword(AuthUtil.shiroMd5(loginVO.getPassword(), loginVO.getUserAccount()).toString());
Boolean f = ISysUserService.updatepass(loginVO.getPassword(), loginVO.getUserAccount());
Boolean fl = CodeService.updatecodestate(SysConstants.UNUSABLE, df.format(now), user.getCreate_date());
} else {
return ApiResult.error(getMessage("ComfirePassword out !!!"));
}
} else {
return ApiResult.error(getMessage("time out !!!"));
}
} else {
return ApiResult.error(getMessage("code error !!!"));
}
return ApiResult.success();
}
}
MenuController
package com.qkkj.hardwaremgmt.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.qkkj.hardwaremgmt.database.beans.SysUser;
import com.qkkj.hardwaremgmt.database.resultmap.SysFuncOperatePermissionResult;
import com.qkkj.hardwaremgmt.database.resultmap.SysMenuTreeResultMap;
import com.qkkj.hardwaremgmt.database.service.IMenuService;
import com.qkkj.hardwaremgmt.database.service.ISysUserService;
import com.qkkj.hardwaremgmt.framework.config.SysConstants;
import com.qkkj.hardwaremgmt.web.util.ApiResult;
/**
*
* @Title: MenuController.java
* @Package com.qkkj.hardwaremgmt.web.controller
* @Description: TODO(用一句话描述该文件做什么)
* @author wangfudong
* @date 2018年5月23日 下午5:29:54
* @version V1.0
*/
@Controller
@RequestMapping("/menuController")
public class MenuController {
@Autowired
private IMenuService menuService;
@Autowired
private ISysUserService sysUserService;
@Autowired
private EhCacheManager ehCacheManager;
/**
* 登录成功后加载菜单
* @author wangfd
* @param params
* @return
*/
@RequestMapping(value = "/selectMenuTree",method = RequestMethod.POST)
@ResponseBody
@SuppressWarnings("unchecked")
public ApiResult
}
main.js 主页js
/**
* Created by Administrator on 2017/12/13.
*/
$(function () {
// get menu
function menuInit(id) {
var data = null;
$.ajax({
url: requestMapping.MENU_TREE,
data:JSON.stringify({}),
type: "POST",
async:true,
success: function(result) {
if(result.code == resultCode.SUCCESS) {
data = result.data.menuTree;
$("#main_userAccount_id").val(result.data.userAccount);
$("#userAccount_id").html(result.data.userAccount);
if(!data) {
data = [];
}
for(var i in data) {
// 重组url
if(data[i].menuUrl) {
data[i].menuUrl = data[i].menuUrl;
}
// 添加子节点标记
if(data[i].children.length > 0) {
data[i]["childflag"] = true;
$.each(data[i].children, function(n, citem) {
// 重组url
if(citem.menuUrl) {
citem.menuUrl = citem.menuUrl;
}
});
}
else {
data[i]["childflag"] = false;
}
}
// compile our template
var template = Handlebars.compile($("#menu-template").html());
$("#" + id).html(template(data));
mainMenuClickFunc();
refreshPage();
}
}
});
}
// click menu
function mainMenuClickFunc() {
$("#pk-menu a").click(function() {
if($(this).parents("li").hasClass("treeview")) {
$( ".sidebar-menu .treeview li").removeClass("active");
if(!$(this).parents(".treeview").hasClass("active")){
$( ".sidebar-menu li").removeClass("active");
$(this).parents(".treeview").addClass("active");
}
}
else {
$( ".sidebar-menu li").removeClass("active");
$( ".sidebar-menu li").removeClass("menu-open");
}
$($(this).parent("li")).addClass("active");
var dataUrl = $(this).attr("data-url");
var menuIdli = $(this).attr("id");
if(dataUrl) {
storeDatas(dataUrl, dataUrl, { menuId:menuIdli});
}
});
}
// store message
function storeDatas(menuUrl, pageUrl, params) {
if(menuUrl) {
sessionStorage.setItem("menuUrl", menuUrl);
}
if(pageUrl) {
sessionStorage.setItem("pageUrl", pageUrl);
}
if(params) {
//根据菜单主键、从缓存中查询权限集合
$.ajax({
url: requestMapping.PERMISSION_FUNCS,
data:JSON.stringify(params),
type: "POST",
async:false,
success: function(result) {
if(result.code == resultCode.SUCCESS) {
sessionStorage.setItem("pageParams", JSON.stringify({"permissions":result.data}));
$("#qk-content").html("");
$("#qk-content").load(pageUrl);
}else{//查询权限失败
window.open("/qkkjapp/views/login.html","_self");
}
}
});
}
else {
sessionStorage.removeItem("pageParams");
$("#qk-content").html("");
$("#qk-content").load(pageUrl);
}
}
// refresh page
function refreshPage() {
var menuUrl = sessionStorage.getItem("menuUrl");
var pageUrl = sessionStorage.getItem("pageUrl");
if(menuUrl) {
$("#pk-menu").find("a").each(function(index, item) {
if(menuUrl.trim() == $(item).attr("data-url").trim()) {
$($(this).parent("li")).addClass("active");
$(this).parents(".treeview").addClass("active").addClass("menu-open");
return false;
}
});
}
if(pageUrl) {
$("#qk-content").load(pageUrl);
}
}
menuInit("pk-menu");
});