jar包
在jzs_web中加入
<!--权限验证依赖-->
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.3.2</version>
</dependency>
配置:
在web.xml中配置 :shiro过滤器代理
<!--shiroFilter 过滤器代理 (登录权限)-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在Spring容器中配置(resource下的applicationContext-shiro.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置shiro的 过滤器bean -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<!-- 登录页面路径 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- 登录成功后显示的路径 -->
<property name="successUrl" value="/index.jsp"></property>
<!-- 未授权的页面提示
如果授权失败 不会跳转到此页面 (bug)
那么如何 解决呢?使用springmvc的异常拦截器 处理
-->
<property name="unauthorizedUrl" value="/unauthorize.jsp">
</property>
<!-- url拦截规则 -->
<property name="filterChainDefinitions">
<!--anon 排除认证url authc:学要认证的url-->
<value>
/validatecode.jsp* = anon
/login.jsp = anon
/sysUser/login.action = anon
/js/** = anon
/images/** = anon
/css/** = anon
/json/* = anon
/** = authc
</value>
</property>
</bean>
<!--安全管理器 shiro的核心-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="zjsRealm"></property>
</bean>
<bean id="zjsRealm" class="com.zjs.realm.ZjsRealm"></bean>
</beans>
(注意 一点 为啥 安全管理器 shiro的核心 要在Spring中配置 不在Spring Mvc中配置)
在Spring Mvc中配置:开启扫描shiro注解
<!--开启扫描shiro注解代理。-->
<bean id="defaultAdvisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
<!-- 必须改为true,即使用cglib方式为Action创建代理对象。默认值为false,使用JDK创建代理对象,会造成问题 -->
<property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
一 权限 代码
在controller中 方法上加上注解 : @RequiresRoles(value = {“staff”})
不要忘了自定义realm:ZjsRealm 要实现 AuthorizingRealm 。
在和controller级别包下建个包 realm 和ZjsRealm类
代码
package com.zjs.realm;
import com.zjs.common.utils.MD5Utils;
import com.zjs.mapper.*;
import com.zjs.pojo.*;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Component
public class ZjsRealm extends AuthorizingRealm {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Autowired
private SysAuthRoleMapper sysAuthRoleMapper;
@Autowired
private SysRoleFunctionMapper sysRoleFunctionMapper;
@Autowired
private SysAuthFunctionMapper sysAuthFunctionMapper;
//权限认证
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
SysUser sysUser = (SysUser)principalCollection.getPrimaryPrincipal();
String id = sysUser.getId();
//查询当前sysUser所拥有的所有角色和权限
SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
SysUserRoleExample.Criteria criteria = sysUserRoleExample.createCriteria();
criteria.andUserIdEqualTo(id);
// 用户和角色中间表:得到所有角色id
List<SysUserRoleKey> roles = this.sysUserRoleMapper.selectByExample(sysUserRoleExample);
//角色信息集合
List<String> rolesStringList=new ArrayList<>();
//权限信息集合
List<String> functionStringList=new ArrayList<>();
if(null != roles && roles.size()>0){
//角色信息 添加完成---------
for(SysUserRoleKey sysUserRoleKey:roles){
SysAuthRole sysAuthRole = this.sysAuthRoleMapper.selectByPrimaryKey(sysUserRoleKey.getRoleId());
rolesStringList.add(sysAuthRole.getCode());
//权限添加------------
SysRoleFunctionExample sysRoleFunctionExample = new SysRoleFunctionExample();
SysRoleFunctionExample.Criteria criteria1 = sysRoleFunctionExample.createCriteria();
criteria1.andRoleIdEqualTo(sysUserRoleKey.getRoleId());
// 角色和权限中间表:根据角色id查出所(权限id集合)
List<SysRoleFunctionKey> sysRoleFunctionKeys = this.sysRoleFunctionMapper.selectByExample(sysRoleFunctionExample);
if(null != sysRoleFunctionKeys && sysRoleFunctionKeys.size()>0){
for(SysRoleFunctionKey sysRoleFunctionKey:sysRoleFunctionKeys){
SysAuthFunction sysAuthFunction = this.sysAuthFunctionMapper.selectByPrimaryKey(sysRoleFunctionKey.getFunctionId());
functionStringList.add(sysAuthFunction.getCode());
}
}
}
}
simpleAuthorizationInfo.addRoles(rolesStringList);
simpleAuthorizationInfo.addStringPermissions(functionStringList);
return simpleAuthorizationInfo;
}
//登录验证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) authenticationToken;
String username = usernamePasswordToken.getUsername();
//查询数据库
SysUserExample sysUserExample = new SysUserExample();
sysUserExample.createCriteria().andUsernameEqualTo(username);
List<SysUser> sysUsers = this.sysUserMapper.selectByExample(sysUserExample);
if(sysUsers.size()>=1){
SysUser sysUser = sysUsers.get(0);
return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), getName());
}
return null;
}
}
登录代码(和上边的 Realm 类有关 以及 在Spring中的securityManager对象有关):通过登录代码SecurityUtils进入securityManager然后进入 Realm 类。
package com.zjs.controller;
import com.zjs.common.utils.MD5Utils;
import com.zjs.pojo.SysUser;
import com.zjs.service.sysUserServiceI;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@RequestMapping("sysUser")
@Controller
public class SysUserController {
@Autowired
private sysUserServiceI sysUserServiceI;
private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
@RequestMapping(value = "login.action",method = {RequestMethod.POST,RequestMethod.GET})
public String login(SysUser sysUser, @RequestParam String checkcode, HttpServletRequest request) {
Object key = request.getSession().getAttribute("key");
//1.检验验证码
if (StringUtils.isNotBlank(checkcode) && null != key) {
if (checkcode.equals((String) key)) {
//2.进行shiro登录
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUser.getUsername(), MD5Utils.text2md5(sysUser.getPassword()));
Subject subject = SecurityUtils.getSubject();
try {
subject.login(usernamePasswordToken);
//登录成功
SysUser sysUserLogined = (SysUser) subject.getPrincipal();
request.getSession().setAttribute("loginUser", sysUserLogined);
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datetime =tempDate.format(new Date());
request.getSession().setAttribute("sjm",datetime);
sysUserLogined.setTelephone(datetime);
sysUserServiceI.updateUser(sysUserLogined);
return "common/index";
} catch (RuntimeException e) {
logger.info("登录失败,用户名:{},错误信息{}", sysUser.getUsername(), e.getMessage());
}
}
}
request.getSession().setAttribute("errorMsg", "登录失败 请重新登录");
return "redirect:/login.jsp";
}
// 退出登录
@RequestMapping(value = "logout.action")
public String logout(HttpServletRequest request){
request.getSession().setAttribute("loginUser",null);
return "redirect:/login.jsp";
}
}