• Shiro安全框架之整合Spring框架


    官方文档:http://shiro.apache.org/spring.html

    要求:实现用户登录功能 (与前几章讲的一样,只不过这里整合到了Spring框架中,可以对比来看)

    一、新建个maven项目

    二、将需要的依赖包贴到pom中

     <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        
        <!-- 添加Servlet支持 -->
          <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        
        <!-- 添加jtl支持 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
      
          <!-- 添加Spring支持 -->
        <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-core</artifactId>
              <version>4.1.7.RELEASE</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-beans</artifactId>
              <version>4.1.7.RELEASE</version>
          </dependency>
          <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-tx</artifactId>
             <version>4.1.7.RELEASE</version>
            </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
              <version>4.1.7.RELEASE</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context-support</artifactId>
              <version>4.1.7.RELEASE</version>
          </dependency>
          
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
      
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
        
      
          <!-- 添加日志支持 -->
          <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        
        <!-- 添加mybatis支持 -->
         <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        
        <!-- jdbc驱动包  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.4</version>
        </dependency>
        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.4</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.4</version>
        </dependency>
        
    
      </dependencies>

    三、src/main/java新建dao entity controller realm service service.impl

     1、entity.User.java

    package com.guo.entity;
    
    public class User {
    
        private Integer id;
        private String userName;
        private String password;
        
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        
        
    }

    2、dao.UserDao.java

    package com.guo.dao;
    
    import java.util.Set;
    
    import com.guo.entity.User;
    
    public interface UserDao {
    
        /**
         * 通过用户名查询用户
         * @param userName
         * @return
         */
        public User getByUserName(String userName);
        
        /**
         * 通过用户名查询角色信息
         * @param userName
         * @return
         */
        public Set<String> getRoles(String userName);
        
        /**
         * 通过用户名查询权限信息
         * @param userName
         * @return
         */
        public Set<String> getPermissions(String userName);
    }

    3、service.UserService.java

    package com.guo.service;
    
    import java.util.Set;
    
    import com.guo.entity.User;
    
    public interface UserService {
    
        /**
         * 通过用户名查询用户
         * @param userName
         * @return
         */
        public User getByUserName(String userName);
        
        /**
         * 通过用户名查询角色信息
         * @param userName
         * @return
         */
        public Set<String> getRoles(String userName);
        
        /**
         * 通过用户名查询权限信息
         * @param userName
         * @return
         */
        public Set<String> getPermissions(String userName);
    }

    4、serviceimpl.UserServiceImpl

    package com.guo.service.impl;
    
    import java.util.Set;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Service;
    
    import com.guo.dao.UserDao;
    import com.guo.entity.User;
    import com.guo.service.UserService;
    
    @Service("userService")
    public class UserServiceImpl implements UserService{
    
        @Resource
        private UserDao userDao;
        
        public User getByUserName(String userName) {
            return userDao.getByUserName(userName);
        }
    
        public Set<String> getRoles(String userName) {
            return userDao.getRoles(userName);
        }
    
        public Set<String> getPermissions(String userName) {
            return userDao.getPermissions(userName);
        }
    
    }

    5、controller.UserController.java

    package com.guo.controller;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.session.Session;
    import org.apache.shiro.subject.Subject;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.guo.entity.User;
    
    
    
    /**
     * 用户Controller层
     * @author Administrator
     *
     */
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        
        /**
         * 用户登录
         * @param user
         * @param request
         * @return
         */
        @RequestMapping("/login")
        public String login(User user,HttpServletRequest request){
            Subject subject=SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(), user.getPassword());
            try{
                subject.login(token);
                Session session=subject.getSession();
                System.out.println("sessionId:"+session.getId());
                System.out.println("sessionHost:"+session.getHost());
                System.out.println("sessionTimeout:"+session.getTimeout());
                session.setAttribute("info", "session的数据");
                return "redirect:/success.jsp";
            }catch(Exception e){
                e.printStackTrace();
                request.setAttribute("user", user);
                request.setAttribute("errorMsg", "用户名或密码错误!");
                return "index";
            }
        }
        
    
    }

    6、realm.MyRealm.java

    package com.guo.realm;
    
    
    import javax.annotation.Resource;
    
    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.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    
    import com.guo.entity.User;
    import com.guo.service.UserService;
    
    public class MyRealm extends AuthorizingRealm{
    
        @Resource
        private UserService userService;
        
        /**
         * 为当限前登录的用户授予角色和权
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            String userName=(String)principals.getPrimaryPrincipal();
            SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
            authorizationInfo.setRoles(userService.getRoles(userName));
            authorizationInfo.setStringPermissions(userService.getPermissions(userName));
            return authorizationInfo;
        }
    
        /**
         * 验证当前登录的用户
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            String userName=(String)token.getPrincipal();
                User user=userService.getByUserName(userName);
                if(user!=null){
                    AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");
                    return authcInfo;
                }else{
                    return null;                
                }
        }
    
    }

    四、在src/main/resource下建mappers.xml映射包(一些SSM配置文件也放到src/main/resource下)

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.guo.dao.UserDao">
    
        <resultMap type="User" id="UserResult">
            <result property="id" column="id"/>
            <result property="userName" column="userName"/>
            <result property="password" column="password"/>
        </resultMap>
        
        <select id="getByUserName" parameterType="String" resultMap="UserResult">
            select * from t_user where userName=#{userName}
        </select>
        
        <select id="getRoles" parameterType="String" resultType="String">
            select r.roleName from t_user u,t_role r where u.roleId=r.id and u.userName=#{userName}
        </select>
        
        <select id="getPermissions" parameterType="String" resultType="String">
            select p.permissionName from t_user u,t_role r,t_permission p where u.roleId=r.id and p.roleId=r.id and u.userName=#{userName}
        </select>
    
    </mapper> 

    五、Shiro.ini配置文件 被放到Spring的配置文件applicationContext.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:aop="http://www.springframework.org/schema/aop"   
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:jee="http://www.springframework.org/schema/jee"  
        xmlns:tx="http://www.springframework.org/schema/tx"  
        xsi:schemaLocation="    
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    
            
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.guo.service" />
        
        <!-- 配置数据源 -->
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/db_shiro"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
        <!-- 配置mybatis的sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 自动扫描mappers.xml文件 -->
            <property name="mapperLocations" value="classpath:com/guo/mappers/*.xml"></property>
            <!-- mybatis配置文件 -->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.guo.dao" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
        
        <!-- 自定义Realm -->
        <bean id="myRealm" class="com.guo.realm.MyRealm"/>  
        
        <!-- 安全管理器 -->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
            <property name="realm" ref="myRealm"/>  
        </bean>  
        
        <!-- Shiro过滤器 -->
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
            <!-- Shiro的核心安全接口,这个属性是必须的 -->  
            <property name="securityManager" ref="securityManager"/>
            <!-- 身份认证失败,则跳转到登录页面的配置 -->  
            <property name="loginUrl" value="/index.jsp"/>
            <!-- 权限认证失败,则跳转到指定页面 -->  
            <property name="unauthorizedUrl" value="/unauthor.jsp"/>  
            <!-- Shiro连接约束配置,即过滤链的定义 -->  
            <property name="filterChainDefinitions">  
                <value>  
                     /login=anon
                    /admin*=authc
                    /student=roles[teacher]
                    /teacher=perms["user:create"]
                </value>  
            </property>
        </bean>  
        
        <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
        
        <!-- 开启Shiro注解 -->
        <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>  
      
        <!-- 配置事务通知属性 -->  
        <tx:advice id="txAdvice" transaction-manager="transactionManager">  
            <!-- 定义事务传播属性 -->  
            <tx:attributes>  
                <tx:method name="insert*" propagation="REQUIRED" />  
                <tx:method name="update*" propagation="REQUIRED" />  
                <tx:method name="edit*" propagation="REQUIRED" />  
                <tx:method name="save*" propagation="REQUIRED" />  
                <tx:method name="add*" propagation="REQUIRED" />  
                <tx:method name="new*" propagation="REQUIRED" />  
                <tx:method name="set*" propagation="REQUIRED" />  
                <tx:method name="remove*" propagation="REQUIRED" />  
                <tx:method name="delete*" propagation="REQUIRED" />  
                <tx:method name="change*" propagation="REQUIRED" />  
                <tx:method name="check*" propagation="REQUIRED" />  
                <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
                <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
                <tx:method name="load*" propagation="REQUIRED" read-only="true" />  
                <tx:method name="*" propagation="REQUIRED" read-only="true" />  
            </tx:attributes>  
        </tx:advice>  
      
        <!-- 配置事务切面 -->  
        <aop:config>  
            <aop:pointcut id="serviceOperation"  
                expression="execution(* com.guo.service.*.*(..))" />  
            <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
        </aop:config>  
        
       
    </beans>
    本博客为博主的学习笔记,不作任何商业用途。
  • 相关阅读:
    数据库知识整理<二>
    数据库知识整理<一>
    面试经历感悟:
    JDK,J2EE,J2SE,J2ME的概念区别是什么呢?
    HTML与JSP页面的区别
    Java并发编程:深入剖析ThreadLocal
    剖析错误原理并解决Hibernate出现No TransactionManagerLookup specified!错误
    MyEclipse中jar包管理技巧
    String,StringBuffer与StringBuilder的区别??
    POJO / JavaBean / Entity Bean
  • 原文地址:https://www.cnblogs.com/guo7533/p/8784672.html
Copyright © 2020-2023  润新知