SSM+shiro实现角色授权认证管理

一、pom.xml添加依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>sdm.cngroupId>
  <artifactId>sdm-webartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>warpackaging>
  
    <dependencies>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webmvcartifactId>
			<version>4.3.9.RELEASEversion>
		dependency>
		
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-jdbcartifactId>
			<version>4.3.9.RELEASEversion>
		dependency>
		
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatisartifactId>
			<version>3.2.8version>
		dependency>
		
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatis-springartifactId>
			<version>1.3.2version>
		dependency>
		
		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<version>5.1.6version>
		dependency>
		
		
		<dependency>
			<groupId>commons-dbcpgroupId>
			<artifactId>commons-dbcpartifactId>
			<version>1.4version>
		dependency>
		
		
		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
			<version>4.12version>
		dependency>
		
		
		<dependency>
			<groupId>jstlgroupId>
			<artifactId>jstlartifactId>
			<version>1.2version>
		dependency>
		
		
		<dependency>
			<groupId>org.apache.shirogroupId>
			<artifactId>shiro-coreartifactId>
			<version>1.2.1version>
		dependency>
		<dependency>
			<groupId>org.apache.shirogroupId>
			<artifactId>shiro-webartifactId>
			<version>1.2.1version>
		dependency>
		<dependency>
			<groupId>org.apache.shirogroupId>
			<artifactId>shiro-ehcacheartifactId>
			<version>1.2.1version>
		dependency>
		<dependency>
			<groupId>org.apache.shirogroupId>
			<artifactId>shiro-springartifactId>
			<version>1.2.1version>
		dependency>
	dependencies>
project>
二、web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>sdm-webdisplay-name>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
  
   
   
  	
	<context-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>
			classpath:application-*.xml,
			classpath:spring-shiro.xml
		param-value>
	context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
	listener>
	
	
	<filter>
		<filter-name>encodingFilterfilter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
		
		<init-param>
			<param-name>encodingparam-name>
			<param-value>utf-8param-value>
		init-param>
	filter>
	<filter-mapping>
		<filter-name>encodingFilterfilter-name>
		<url-pattern>/*url-pattern>
	filter-mapping>
	
	
	<servlet>
		<servlet-name>dispatcherServletservlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
		<init-param>
			<param-name>contextConfigLocationparam-name>
			<param-value>classpath:spring-mvc.xmlparam-value>
		init-param>
		<load-on-startup>1load-on-startup>
	servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServletservlet-name>
		<url-pattern>*.dourl-pattern>
	servlet-mapping>
	
	
    <filter>
        <filter-name>shiroFilterfilter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
        <init-param>
            <param-name>targetFilterLifecycleparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>shiroFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
web-app>
三、spring-shiro.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd">

	
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		
		<property name="securityManager" ref="securityManager" />
		
		<property name="loginUrl" value="/user/showLogin.do" />
		
		<property name="successUrl" value="/dormitory/showIndex.do" />
		
		<property name="unauthorizedUrl" value="/unauthorized" />
		
		<property name="filters">
			<util:map>
				<entry key="logout" value-ref="logoutFilter" />
			util:map>
		property>
		
		<property name="filterChainDefinitions">
			<value>
				
				/css/**=anon
				/images/**=anon
				/js/**=anon
				/user/showLogin.do=anon
				/user/login.do=anon
				
                /user/exit.do = logout
				
				/** = authc
			value>
		property>
	bean>
	
	<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
		<property name="redirectUrl" value="/user/showLogin.do" />
	bean>

	
	<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
	
	<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
		<constructor-arg value="sid" />
		<property name="httpOnly" value="true" />
		<property name="maxAge" value="-1" />
	bean>
	
	<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
		<property name="sessionIdGenerator" ref="sessionIdGenerator" />
	bean>
	
	<bean name="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
		<property name="interval" value="1800000" />
		<property name="sessionManager" ref="sessionManager" />
	bean>
	
	<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
		
		<property name="globalSessionTimeout" value="1800000" />
		<property name="deleteInvalidSessions" value="true" />
		<property name="sessionValidationSchedulerEnabled" value="true" />
		<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
		<property name="sessionDAO" ref="sessionDAO" />
		<property name="sessionIdCookieEnabled" value="true" />
		<property name="sessionIdCookie" ref="sessionIdCookie" />
	bean>

	
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="myUserRealm" />
		<property name="sessionManager" ref="sessionManager" />
	bean>
	
	<bean
		class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
		<property name="staticMethod"
			value="org.apache.shiro.SecurityUtils.setSecurityManager" />
		<property name="arguments" ref="securityManager" />
	bean>

	<bean id="myUserRealm" class="cn.sdm.shiro.MyUserRealm">
	bean>

	
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
beans>
四、Controller 添加异步提交登录请求方法
// 异步提交登录
@RequestMapping("/login.do")
@ResponseBody
public ResponseResult<Void> login(String username, String password, String inputCaptcha){
   // 获取当前应用交互主体
   Subject subject = SecurityUtils.getSubject(); 
   Session session=subject.getSession();
   ResponseResult<Void> rr = null;
   // UsernamePasswordToken用来存储用户和密码
   UsernamePasswordToken token = new UsernamePasswordToken(username, password);
   try { 
      // 跳转到认证
      subject.login(token);
      rr = new ResponseResult<Void>(1,"登录成功");
      System.out.println("登录成功");
   } catch (AuthenticationException e) { 
      rr = new ResponseResult<Void>(0,"用户名或密码错误");
      System.out.println("登录失败: "+e.getMessage());
   }
        
   return rr;
}
五、MyUserRealm
package cn.shiro;
 
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.ObjectUtils;
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.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import cn.bean.User;
import cn.mapper.UserMapper;
import cn.service.UserService;
import cn.service.ex.PasswordNotMatchException;

/**
 * shiro安全权限管理
 * @author 
 *
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
//    // 加盐
//     @Value("#{config.salt}")
//     private String salt;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //账号已通过验证
        String username =(String) principalCollection.getPrimaryPrincipal();
        System.out.println("username:"+username);
        //通过service获取角色和权限
        List<Map<String,Object>> permissionsList = userService.selectPermissionsByUsername(username);
        Set<String> permissions = new HashSet<String>();
        for(Map<String,Object> map : permissionsList){
           permissions.add(ObjectUtils.toString(map.get("permissionCode")));
        }
        List<Map<String,Object>> rolesList = userService.selectRolesByUsername(username);
        Set<String> roles = new HashSet<String>();
        for(Map<String,Object> map : rolesList){
           roles.add(ObjectUtils.toString(map.get("roleName")));
        }
        System.out.println("roles: "+roles.toString());
        //授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //把通过service获取到的角色和权限放进去
        info.setStringPermissions(permissions);
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String username= token.getPrincipal().toString();
        String password= new String(t.getPassword());
        // 获取数据库中的密码
        User user = userMapper.selectByUsername(username);
        String passwordInDB = user.getPassword();
//        // 如果为空就是账号不存在,如果不相同就是密码错误,但是都抛出AuthenticationException,而不是抛出具体错误原因,免得给破解者提供帮助信息
//        if(null==passwordInDB || !passwordInDB.equals(password)){
//         throw new AuthenticationException();
//        }
        // 认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :myUserRealm
//        // 获取盐,用于对密码在加密算法(MD5)的基础上二次加密
//        ByteSource byteSalt = ByteSource.Util.bytes(salt);?
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,passwordInDB,this.getName());
        Session session=SecurityUtils.getSubject().getSession();
        session.setAttribute("user", user);
        return info;
    }
 
}
六、前端部分
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<%@ taglib prefix="shiroextend" tagdir="/WEB-INF/tags" %>

<html>
<head lang="en">
   <meta charset="utf-8" />
   <title>XXX管理平台title>
   <script src="../js/jquery-3.1.1.min.js">script>
   <script src="../js/jquery.cookie.js">script>
 <script type="text/javascript">
 script>
head>

<body>
   <div class="left-container"> 
      <ul class="left-menu" onclick="">
         <li class="big-menu" id="">
            <img class="icon1" src="../images/icon/dormitory.png"/>
            <a href="#" class="menu1">宿舍管理<img class="icon2" src="../images/icon/tobottom.png"/>a>
            <ul class="small-menu">
               <li class="menu2" id="" onclick="">
                  <a href="../dormitory/showIndex.do">  宿舍查看a>
               li>
               
               <%-- <shiro:hasRole name="管理员"> --%>
               <shiro:hasPermission name="dormitory_manage">
               <li class="menu2" id="" onclick="">
                  <a href="../dormitory/dormitoryManage.do">  宿舍调整a>
               li>
               shiro:hasPermission>
               <%-- shiro:hasRole> --%>
            ul>
         li>

         <shiroextend:hasAnyPermissions name="dormitory_cost,apartment_cost">
            <li class="big-menu" id="">
               <img class="icon1" src="../images/icon/cost.png"/>
               <a href="#" class="menu1">费用管理<img class="icon2" src="../images/icon/tobottom.png"/>a>
               <ul class="small-menu">
                  <shiro:hasPermission name="dormitory_cost">
                     <li class="menu2" id="" onclick="">
                        <a href="../cost/dormitoryCost.do">  宿舍费用a>
                     li>
                  shiro:hasPermission>
                  <shiro:hasPermission name="apartment_cost">
                     <li class="menu2" id="" onclick="">
                        <a href="../cost/apartmentCost.do">  公寓物品费用a>
                     li>
                  shiro:hasPermission>
               ul>
            li>
         shiroextend:hasAnyPermissions>
         
         <shiroextend:hasAnyPermissions name="role_manage,account_manage">
         <li class="big-menu" id="">
            <img class="icon1" src="../images/icon/user.png"/>
            <a href="#" class="menu1">用户管理<img class="icon2" src="../images/icon/tobottom.png"/>a>
            <ul class="small-menu">
               <shiro:hasPermission name="role_manage">
               <li class="menu2" id="" onclick="">
                  <a href="../user/roleManage.do">  角色管理a>
               li>
               shiro:hasPermission>
               <shiro:hasPermission name="account_manage">
               <li class="menu2" id="" onclick="">
                  <a href="../user/accountManage.do">  账号管理a>
               li>
               shiro:hasPermission>
            ul>
         li>
         shiroextend:hasAnyPermissions>
      ul>
   div>
   
   
   <%@ include file="update_password.jsp" %>
body>
html>

你可能感兴趣的:(我的随笔)