登录功能
准能一个登录页面
两个登录方法,完成登录的功能
一个用于跳转(get),一个用于登录(post)
//跳转login页面
//发送get请求
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String index(){
return "login";
}
//跳转login页面 post请求
@RequestMapping(value = "/login",method = RequestMethod.POST)
@ResponseBody//Ajax请求,返回数据,不要跳转
public JsonResult login(String username, String password){
//拿到当前用户currentUser
Subject subject = SecurityUtils.getSubject();
//如果当前用户未登录就让他登录
if (!subject.isAuthenticated()){
try {
//获取令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//登录
subject.login(token);
} catch (UnknownAccountException e) {
e.printStackTrace();
System.out.println("用户名出错!!!");
return new JsonResult(false,"账号或者密码错误");
} catch (IncorrectCredentialsException e) {
e.printStackTrace();
System.out.println("密码出错!!!");
return new JsonResult(false,"账号或者密码错误");
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("登录错误");
return new JsonResult(false,"出现未知错误");
}
}
//把当前用户放到session中去
Employee employee = (Employee) subject.getPrincipal();
UserContext.setUser(employee);//设置到session中去
//登录成功后 跳转main.jsp页面
return new JsonResult();
}
登录的细节
有一套自己的加密规则 使用MD5
public class MD5Util {
//常量使用大写
public static final String SALT = "xxx";
public static final Integer HASHITERATIONS = 10;
//密码加密
public static String changePwd(String password){
SimpleHash hash = new SimpleHash("MD5",password,SALT,HASHITERATIONS);
return hash.toHex();
}
}
添加用户密码吗加密
@Override
public void save(Employee employee) {
if(employee.getId()==null){
//添加功能就进行密码修改
employee.setPassword(MD5Util.changePwd(employee.getPassword()));
}
employeeRepository.save(employee);
}
加密的判断必须个规则一致
在applicationContext-shiro.xml中
<!-- 被引用的realm(一定会写一个自定义realm) -->
<bean id="jpaRealm" class="cn.itsource.aisell.shiro.JpaRealm">
<!-- 为这个realm设置相应的匹配器 -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 设置加密方式 -->
<property name="hashAlgorithmName" value="md5"/>
<!-- 设置加密次数 -->
<property name="hashIterations" value="10" />
</bean>
</property>
</bean>
JpaRealm中加盐要一致
//身份认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1.拿用户名与密码
UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
String username = token.getUsername();
//2.根据用户名拿到相应的对象
Employee loginUser = employeeService.findByUsername(username);
if(loginUser==null){
return null; //如果用户用空代表用户名不存在
}
String password = loginUser.getPassword();
//返回认证信息
//准备盐值
//传的第一个值就是主体(username名称做的主体)
ByteSource salt = ByteSource.Util.bytes(MD5Util.SALT);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,getName());
return authenticationInfo;
}
资源的放行
public class FilterChainDefinitionMapBuilder {
@Autowired
private IPermissionService permissionService;
public Map<String,String> createFilterChainDefinitionMap(){
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();//LinkedHashMap表示有序的
//设置不需要访问也可以的放行的路径
filterChainDefinitionMap.put("/s/login.jsp","anon");//anon:不需要权限也可以访问的页面
filterChainDefinitionMap.put("/login","anon");
filterChainDefinitionMap.put("*.js","anon");
filterChainDefinitionMap.put("*.css","anon");
filterChainDefinitionMap.put("/css/**","anon");
filterChainDefinitionMap.put("/js/**","anon");
filterChainDefinitionMap.put("/easyui/**","anon");
filterChainDefinitionMap.put("/images/**","anon");
filterChainDefinitionMap.put("/login/**","anon");
//设置需要权限访问的路径
// filterChainDefinitionMap.put("/employee/index","perms[employee:index]");
// filterChainDefinitionMap.put("/dept/index","perms[dept:index]");
//从数据库拿到所有的权限
List<Permission> perms = permissionService.findAll();
//遍历所有权限
perms.forEach(p ->{
//拿到路径和权限
filterChainDefinitionMap.put(p.getUrl(),"aiPerms["+ p.getSn()+"]");
});
//设置需要登录才能访问
filterChainDefinitionMap.put("/**","authc");//authc:需要登录才能访问(有顺序)
return filterChainDefinitionMap;
}
}
判断登录过期
// 检查自己是否是顶级页面
if (top != window) {// 如果不是顶级
//把子页面的地址,赋值给顶级页面显示
window.top.location.href = window.location.href;
}
回车登录
$(document.documentElement).on("keyup", function(event) {
//console.debug(event.keyCode);
var keyCode = event.keyCode;
console.debug(keyCode);
if (keyCode === 13) { // 捕获回车
submitForm(); // 提交表单
}
});
展示用户名和注销
<head>
<title>Title</title>
<%@include file="/WEB-INF/views/head.jsp" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
</head>
<body class="easyui-layout">
<div data-options="region:'north'" style="height:100px;">
<div style="text-align: center;color: #0000FF">
<h1>智能销售系统</h1>
</div>
<div style="text-align: center">
欢迎${userInSession.username}进入 <a href="/logout">注销</a>
</div>
</div>
</body>
角色管理
先使用代码生成器成表,在配置表和表之间的关系
角色和角色权限的展示
<body>
<div id="gridToolBar" style="height:auto">
<div style="margin-bottom:5px">
<a href="javascript:;" data-method="add" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
<a href="javascript:;" data-method="edit" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>
<shiro:hasPermission name="employee:delete">
<a href="javascript:;" data-method="delete" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
</shiro:hasPermission>
</div>
<div>
<form id="searchForm" method="post" action="/employee/export">
用户名: <input name="username" class="easyui-textbox" style="width:80px">
邮件: <input name="email" class="easyui-textbox" style="width:80px">
部门:<input name="departmentId" class="easyui-combobox" panelHeight="auto" style="width:auto"
data-options="valueField:'id',textField:'name',url:'/util/deptList'" />
<a href="javascript:;" data-method="search" class="easyui-linkbutton" iconCls="icon-search">查询</a>
<button class="easyui-linkbutton" iconCls="icon-search">导出</button>
</form>
</div>
</div>
<table id="employeeDataGrid" class="easyui-datagrid" style="width:400px;height:250px"
data-options="url:'/employee/page',fit:true,fitColumns:true,singleSelect:true,
pagination:true,
toolbar:'#gridToolBar'
">
<thead>
<tr>
<%--formatter格式化--%>
<th data-options="field:'headImage',width:100,formatter:formatImg">头像</th>
<th data-options="field:'username',width:100" >用户名</th>
<th data-options="field:'password',width:100">密码</th>
<th data-options="field:'email',width:100">邮件</th>
<th data-options="field:'age',width:100">年龄</th>
<th data-options="field:'department',width:100,formatter:formatName">部门</th>
</tr>
</thead>
</table>
<%--表单弹出框--%>
<div id="employeeDialog" class="easyui-dialog" title="功能操作"
data-options="iconCls:'icon-save',closed:true,modal:true,buttons:'#formBtns'"
style="padding:10px">
<form id="employeeForm" method="post">
<input id="employeeId" type="hidden" name="id" />
<table cellpadding="5">
<tr>
<td>用户名:</td>
<td><input class="easyui-validatebox" type="text" name="username" data-options="required:true,validType:'checkName'"></input></td>
</tr>
<tr data-show="false">
<td>密码:</td>
<td><input id="password" class="easyui-validatebox" type="text" name="password" data-options="required:true"></input></td>
</tr>
<tr data-show="false">
<td>确认密码:</td>
<td><input class="easyui-validatebox" type="text" name="repassword" validType="equals['password','id']" data-options="required:true"></input></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input class="easyui-validatebox" type="text" name="email" data-options="required:true,validType:'email'"></input></td>
</tr>
<tr>
<td>年龄:</td>
<td><input class="easyui-validatebox" type="text" name="age" data-options="required:true,validType:'integerRange[10,60]'"></input></td>
</tr>
<tr>
<td>部门:</td>
<td>
<input name="department.id" class="easyui-combobox" panelHeight="auto" style="width:120px"
data-options="required:true,valueField:'id',textField:'name',url:'/util/deptList'" />
</td>
</tr>
</table>
</form>
</div>
<%--弹出框(表单)操作--%>
<div id="formBtns">
<a href="javascript:;" data-method="save" class="easyui-linkbutton c1">确认</a>
<a href="javascript:;" "$('#employeeDialog').dialog('close')" class="easyui-linkbutton c5">取消</a>
</div>
</body>
add() {
//把所有带data-show的元素显示起来
$("*[data-show]").show();
//开启验证功能
$("*[data-show] input").validatebox("enable");
//打开对话框
employeeDialog.dialog("center").dialog("open");
//把form中的数据清空
employeeForm.form("clear");
},
edit() {
var row = employeeDataGrid.datagrid("getSelected");
if (!row) {
$.messager.alert("提示", "请选中", "info");
return;
}
//把有data-show的所有的元素隐藏起来
$("*[data-show]").hide();
//让验证的失效
$("*[data-show] input").validatebox("disable");
//打开对话框
employeeDialog.dialog("center").dialog("open");
//把form表单中的数据清空
employeeForm.form("clear");
if (row.department) {
row["department.id"] = row.department.id;
}
//完成回显
employeeForm.form("load", row);
},
//保存功能
save() {
//根据id确定添加路径还是修改路径
var url = "/employee/save";
var id = $("#employeeId").val();
if (id) {
url = "/employee/update?cmd=update";
}
employeeForm.form('submit', {
url: url,
//提交表单前的方法
onSubmit: function () {
return $(this).form('validate')
},
//操作成功后的回调
success: function (data) {
//console.debug(data); //{"success":true}
//var result = eval("("+data+")");
//console.debug(result);
//返回的是JSON字符串,我们需要把转成一个JSON对象
var result = JSON.parse(data);
if (result.success) {
//成功后刷新
employeeDataGrid.datagrid("reload");
//关闭窗口
employeeDialog.dialog("close");
} else {
//把失败信息做一个提示
$.messager.alert("提示", `你出错了! 原因是:${result.msg}`, "error");
}
}
});
},
delete() {
//先判断有没有选中
var row = employeeDataGrid.datagrid("getSelected");
//没有选中就给出提示
if (!row) {
$.messager.alert("提示", "请选中", "info");
return;
}
//选中就让用户是否确认删除
$.messager.confirm('确认删除', '真的狠心删除我吗', function (r) {
if (r) {
//确认删除直接访问后台
$.get("/employee/delete", {id: row.id}, function (result) {
if (result.success) {
//成功后刷新
employeeDataGrid.datagrid("reload");
} else {
$.messager.alert("提示", `出错了,原因是:${result.msg}`, "error");
}
})
}
})
},
search() {
//拿到列表中的参数
var params = searchForm.serializeObject();
employeeDataGrid.datagrid('load', params);
}
解决只增不减问题 n-to-n
修改的时候只增加不减少
@ModelAttribute("editRole")
public Role beforeEdit(Long id,String cmd){
if(id!=null && "update".equals(cmd)) {
Role role = roleService.findOne(id);
//把要传过来的关联对象都清空,就可以解决n-to-n的问题
role.getPermissions().clear();
return role;
}
return null;
}
session处理
登录之后传一个Employee对象
sesion从subject中去获取
存在shiro的session中后,HttpSession也会有值
public class UserContext {
public static final String USER_IN_SESSION ="loginUser";
//把登录成功的用户放到session中
public static void setUser(Employee loginUser){
Subject subject = SecurityUtils.getSubject();
//代表登录成功,把当前登录用户放到Session中去(shiro的session)
//1.拿到session
Session session = subject.getSession();
//2.把当前登录成功的用户放到session中去
session.setAttribute(USER_IN_SESSION, loginUser);
}
//获取到当前登录用户
public static Employee getUser(){
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
Employee employee = (Employee) session.getAttribute(USER_IN_SESSION);
return employee;
}
}
授权管理
FilterChainDefinitionMapFactory
保存所有权限过滤的苏剧都是从数据中获取
转----->>>权限拦截
获取授权
//根据用户拿到他对应的所有权限
@Query("select distinct p.sn from Employee e join e.roles r join r.permissions p where e.id = ?1")
Set<String> findPermsByUser(Long userId);
service层调用
JpaReaml拿到当前登录用户,在获取权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
Employee loginUser = UserContext.getUser();
//根据当前用户拿到对应的权限
Set<String> perms = permissionService.findPermsByUser(loginUser.getId());
//准备并返回AuthorizationInfo这个对象
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setStringPermissions(perms);
return authorizationInfo;
}
Ajax请求的权限处理
shiro处理没有权限是跳转页面,而我们如果是ajax请求,我们希望是返回json数据 ajax请求会有一个请求头:X-Requested-With: XMLHttpRequest 需要自定义一个shiro的权限过滤器
自定义权限过滤器
//自定义拦截器
public class AiSellPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
//request:请求对象(包含所有的请求信息)
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
//判断是否是Ajax的请求
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
//获取到相应的请求头X-Requested-With:XMLHttpRequest
//只有Ajax请求有这个数据
String xhr =req.getHeader("X-Requested-With");
if("XMLHttpRequest".equals(xhr)){//判断是否为Ajax请求
//设置响应头(告诉前端返回的数据格式)
resp.setContentType("application/json;charset=UTF-8");
//代表是一个Ajax请求,单独处理 返回json字符串
resp.getWriter().print("{\"success\":false,\"msg\":\"你没有权限\"}");
}else {
String unauthorizedUrl = this.getUnauthorizedUrl();//拿到路径
if (StringUtils.hasText(unauthorizedUrl)) {
//跳转没有权限的路径
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
}
return false;
}
}
在applicationContext-shiro中配置权限
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- securityManager:Spring创建核心对象 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="aiSellRealm"/>
</bean>
<bean id="aiSellRealm" class="aisell.shiro.AiSellRealm">
<!-- 为这个realm设置相应的匹配器 -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="10" />
</bean>
</property>
</bean>
<!-- 支持我们做注解权限判断 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!--Shiro中真正的过滤器:名称必须和web.xml中的那个过滤器名字一样-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<!--如果你没有登录,就会进入这个页面-->
<property name="loginUrl" value="/login"/>
<!--如果登录成功,就会进入这个页面-->
<property name="successUrl" value="/main"/>
<!--如果没有权限,就会进入这个页面-->
<property name="unauthorizedUrl" value="/s/unauthorized.jsp"/>
<!-- 这个配置可以直接给一个map(动态的可以从代码中获取) -->
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMapBuilderMap" />
<!--一个自定义的权限过滤器-->
<property name="filters">
<map>
<entry key="aiPerms" value-ref="aiSellPermissionsAuthorizationFilter"></entry>
</map>
</property>
</bean>
<bean id="aiSellPermissionsAuthorizationFilter" class="aisell.shiro.AiSellPermissionsAuthorizationFilter"></bean>
<!--最后的结果就是对应方法返回的Map值-->
<bean id="filterChainDefinitionMapBuilderMap" factory-bean="filterChainDefinitionMapBuilder"
factory-method="createFilterChainDefinitionMap" />
<!--配置相应的bean-->
<bean id="filterChainDefinitionMapBuilder" class="aisell.shiro.FilterChainDefinitionMapBuilder" />
</beans>
菜单管理
员工 -> 角色 -> 权限 -> 菜单
菜单管理的自关联配置
需要配置双向,但是不能让JPA去管理一对多(我们自己理:@Transient)
双向生成JSON会产生死循环,需要一边进行忽略:@JsonIgnore
//让它不再生成JSON
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
@JsonIgnore
private Menu parent;
// 临时属性 -> 这个字段JPA就不管它了
@Transient
private List<Menu> children = new ArrayList<>();
MenuRepository
public interface MenuRepository extends BaseRepository<Menu,Long>{
@Query("select distinct m from Employee e join e.roles r join r.permissions p join p.menu m where e.id = ?1")
List<Menu> findByUser(Long userId);
}
MenuService
@Override
public List<Menu> findLoginMenu() {
//准备一个装父菜单的容器
List<Menu> parentMenus = new ArrayList<>();
//拿到当前登录用户的所有子菜单
Employee loginUser = UserContext.getUser();
List<Menu> children = menuRepository.findByUser(loginUser.getId());
//遍历子菜单,设置它们的关系
for (Menu child : children) {
//根据子菜单拿到它对应的父菜单
Menu parent = child.getParent();
//判断这个父菜单是否在容器中
if(!parentMenus.contains(parent)){
//如果不在,把父菜单放进去
parentMenus.add(parent);
}
//为这个父菜单添加对应的子菜单
parent.getChildren().add(child);
}
return parentMenus;
}
UtilController中返回值
@Autowired
private IMenuService menuService;
@RequestMapping("/loginUserMenu")
@ResponseBody
public List<Menu> loginUserMenu(){
return menuService.findLoginMenu();
}
main.jsp中要修改路径
没有权限不展示按键
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<shiro:hasPermission name="employee:delete">
<a href="javascript:;" data-method="delete" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
</shiro:hasPermission>