shiro安全框架是目前为止作为登录注册最常用的框架,因为它十分的强大简单,提供了认证、授权、加密和会话管理等功能 。
shiro能做什么?
认证:验证用户的身份
授权:对用户执行访问控制:判断用户是否被允许做某事
会话管理:在任何环境下使用 Session API,即使没有 Web 或EJB 容器。
加密:以更简洁易用的方式使用加密功能,保护或隐藏数据防止被偷窥
Realms:聚集一个或多个用户安全数据的数据源
单点登录(SSO)功能。
为没有关联到登录的用户启用 "Remember Me“ 服务
Shiro 的四大核心部分
Authentication(身份验证):简称为“登录”,即证明用户是谁。
Authorization(授权):访问控制的过程,即决定是否有权限去访问受保护的资源。
Session Management(会话管理):管理用户特定的会话,即使在非 Web 或 EJB 应用程序。
Cryptography(加密):通过使用加密算法保持数据安全
shiro的三个核心组件:
Subject :正与系统进行交互的人,或某一个第三方服务。所有 Subject 实例都被绑定到(且这是必须的)一个SecurityManager 上。
SecurityManager:Shiro 架构的心脏,用来协调内部各安全组件,管理内部组件实例,并通过它来提供安全管理的各种服务。当 Shiro 与一个 Subject 进行交互时,实质上是幕后的 SecurityManager 处理所有繁重的 Subject 安全操作。
Realms :本质上是一个特定安全的 DAO。当配置 Shiro 时,必须指定至少一个 Realm 用来进行身份验证和/或授权。Shiro 提供了多种可用的 Realms 来获取安全相关的数据。如关系数据库(JDBC),INI 及属性文件等。可以定义自己 Realm 实现来代表自定义的数据源。
shiro整合SSM框架:
1.我的demo目录:
2.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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xingshang</groupId> <artifactId>ShiroDemo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ShiroDemo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>3.2.4.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.4</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.9</log4j.version> </properties> <dependencies> <!-- spring核心包 --> <!-- springframe start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- springframe end --> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mysql驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- junit测试包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 阿里巴巴数据源 包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.2</version> </dependency> <!-- json数据 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!--shiro核心包--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.2</version> </dependency> <!--shiro web支持--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.2</version> </dependency> <!--shiro spring支持--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version> </dependency> <!----> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>com.alipay</groupId> <artifactId>sdk-java</artifactId> <version>20180309170622</version> </dependency> </dependencies> <build> <finalName>ShiroDemo</finalName> </build> </project>
3.配置 web.xml 文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID3" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- 读取spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </context-param> <!-- Spring字符集过滤器 --> <filter> <filter-name>SpringEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>SpringEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- springMVC核心配置 --> <!--前端控制器--> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--初始化所需配置文件位置--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!--设置拦截路径--> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--Filter的代理器:shiro拦截--> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <!--DelegatingFilterProxy:去spring的容器中去找filter—name相同名字的bean--> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 日志记录 --> <context-param> <!-- 日志配置文件路径 --> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <!-- 日志页面的刷新间隔 --> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--spring监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <!-- 错误跳转页面 --> <error-page> <!-- 路径不正确 --> <error-code>404</error-code> <location>/WEB-INF/file/404.jsp</location> </error-page> <error-page> <!-- 没有访问权限,访问被禁止 --> <error-code>405</error-code> <location>/WEB-INF/file/405.jsp</location> </error-page> <error-page> <!-- 内部错误 --> <error-code>500</error-code> <location>/WEB-INF/file/500.jsp</location> </error-page> </web-app>
4.spring-mybatis.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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 引入jdbc配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> <!-- 连接池最大使用连接数 --> <property name="maxActive"> <value>20</value> </property> <!-- 初始化连接大小 --> <property name="initialSize"> <value>1</value> </property> <!-- 获取连接最大等待时间 --> <property name="maxWait"> <value>60000</value> </property> <!-- 连接池最大空闲 --> <property name="maxIdle"> <value>20</value> </property> <!-- 连接池最小空闲 --> <property name="minIdle"> <value>3</value> </property> <!-- 自动清除无用连接 --> <property name="removeAbandoned"> <value>true</value> </property> <!-- 清除无用连接的等待时间 --> <property name="removeAbandonedTimeout"> <value>180</value> </property> <!-- 连接属性 --> <property name="connectionProperties"> <value>clientEncoding=UTF-8</value> </property> </bean> <!-- mybatis文件配置,扫描所有mapper文件 --> <!-- configLocation为mybatis属性;mapperLocations为所有mapper --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:mapper/*.xml" /> <!-- spring与mybatis整合配置,扫描所有dao --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.xingshang.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" /> <!-- 对数据源进行事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> </beans>
5.spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 扫描controller(controller层注入) --> <context:component-scan base-package="com.xingshang.controller" /> <!-- 避免IE在ajax请求时,返回json出现下载 --> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 对模型视图添加前后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/" p:suffix=".jsp" /> <!-- 开启shiro的注解支持 --> <bean id="defaultAdvisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"> <!-- 必须改为true,即使用cglib方式为Action创建代理对象。默认值为false,使用JDK创建代理对象,会造成问题 --> <property name="proxyTargetClass" value="true"></property> </bean> <!-- 使用shiro框架提供的切面类,用于创建代理对象 --> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"></bean> </beans>
6.jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/shirodemo
jdbc_username=root
jdbc_password=123456
7.log4j.properties
### set log levels ###
#log4j.rootLogger = debug , stdout , D , E
log4j.rootLogger = debug , stdout , D
### output to the console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
### Output to the log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### Save exception information to separate file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/error.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
8.spring-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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- 配置 ShiroFilter bean: 该 bean 的 id 必须和 web.xml 文件中配置的 shiro filter 的 name 一致 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- 装配 securityManager:shiro核心安全接口,这个属性是必须的--> <property name="securityManager" ref="securityManager"/> <!-- 配置登陆页面 非必须,若没有指定shiro会在web工程下寻找indexjsp页面--> <property name="loginUrl" value="/login.jsp"/> <!-- 登陆成功后的页面 --> <property name="successUrl" value="/success.jsp"/> <!--用户访问未对其授权的页面时所跳转的页面--> <property name="unauthorizedUrl" value="WEB-INF/file/500.jsp"/> <!--代表需要完成的shiro过滤器的具体配置--> <!-- 具体配置需要拦截哪些 URL, 以及访问对应的 URL 时使用 Shiro 的什么 Filter 进行拦截. 不同的filter有不同的拦截级别 anon:不需要登入 authc:必须需要登入 应用 /**=authc,都必须登入才能访问 --> <property name="filterChainDefinitions"> <value> /WEB-INF/index.jsp=anon /WEB-INF/fail/*.jsp=anon /login=anon /**=authc </value> </property> </bean> <!-- 配置 Shiro 的 SecurityManager Bean. --> <!--配置安全管理器--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!--引入缓存管理器--> <property name="cacheManager" ref="cacheManager"/> <!-- 目标realm的实现--> <property name="realm" ref="myRealm"/> <!-- <property name="sessionMode" value="native"/>--> </bean> <!-- 配置缓存管理器 --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <!-- 指定 ehcache 的配置文件 --> <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/> </bean> <!-- 配置进行授权和认证的 Realm --> <bean id="myRealm" class="com.xingshang.realm.MyRealm"> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <!-- 加密算法为MD5 --> <property name="hashAlgorithmName" value="MD5"></property> <!-- 加密次数 --> <property name="hashIterations" value="2"></property> </bean> </property> </bean> <!-- 配置 Bean 后置处理器: 会自动的调用和 Spring 整合后各个组件的生命周期方法. --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans>
9.ehcache-shiro.xml
<ehcache updateCheck="false" name="shiroCache"> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>
10.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 命名空间 --> </configuration>
到这一步,配置文件都基本准备好了,接下来要写Realm方法了,新建realm包,在包下新建MyRealm.java文件继承AuthorizingRealm
package com.xingshang.realm; import com.xingshang.dao.UserDao; import com.xingshang.entity.User; 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.apache.shiro.util.ByteSource.Util; import java.util.HashSet; import java.util.List; import java.util.Set; public class MyRealm extends AuthorizingRealm { @Autowired private UserDao userDao; /** * 1、登入认证 * thenticationInfo:获取认证消息,如果数据库中没有,返回null,如果得到正确的用户名和密码 * 2、AuthenticationInfo 可用simpleAuthenticationInfo实现类,封装获取到的正确的账号和密码 * 返回正定类型的对象 * * @param authenticationToken * @return * @throws AuthenticationException */ protected SimpleAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //1、将token转换为UserNamePasswordToken UsernamePasswordToken uptoken = (UsernamePasswordToken) authenticationToken; //2、获取用户名 User user = new User(); user.setUsername(uptoken.getUsername()); user.setPassword(uptoken.getPassword().toString()); User us = userDao.login(user); if (us != null) { SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(us.getUsername(), us.getPassword(), "a"); authenticationInfo.setCredentialsSalt(Util.bytes(us.getSalt())); return authenticationInfo; } else { throw new ExcessiveAttemptsException("账号密码错误"); } } /** * 权限角色认证 * * @param principalCollection * @return */ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String username = principalCollection.getPrimaryPrincipal().toString(); List<String> roles = userDao.selectRole(username); List<String> permissions = userDao.selectPermission(username); Set<String> ro = new HashSet<String>(); Set<String> per = new HashSet<String>(); for (String role : roles) { ro.add(role); } for (String permission : permissions) { per.add(permission); } SimpleAuthorizationInfo sim = new SimpleAuthorizationInfo(); sim.setRoles(ro); sim.setStringPermissions(per); return sim; } }
好了,接下来我们写一个简单的controller来通过shiro登录验证。
package com.xingshang.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class LoginController { @RequestMapping("/login") public String login(@RequestParam("username") String username,@RequestParam("password") String password){ Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()){ UsernamePasswordToken token = new UsernamePasswordToken(username,password); try {
//执行认证操作 subject.login(token); }catch (Exception e){ return e.getMessage(); } } return "success"; } @RequestMapping("/test1") @ResponseBody public String test1(){ Subject subject = SecurityUtils.getSubject(); try { subject.checkRole("admin"); }catch (Exception e){ return "不拥有admin角色"; } return "拥有admin角色"; } @RequestMapping("/test2") @ResponseBody public String test2(){ Subject subject= SecurityUtils.getSubject(); try { subject.checkRole("CEO"); }catch (Exception e){ return "不拥有CEO角色"; } return "拥有admin角色"; } }
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" %> <html> <head> <title>Title</title> </head> <body> <form action="/login" method="post"> <div> 账号:<input type="text" name="username"> </div> <div> 密码:<input type="password" name="password"> </div> <div> <input type="submit" value="登入"> </div> </form> </body> </html>
success.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/3/19 Time: 9:31 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="/test1">是不是admin</a> <a href="/test2">是不是ceo</a> </body> </html>
UserMapper.xml
<?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.xingshang.dao.UserDao" > <select id="login" resultType="com.xingshang.entity.User" parameterType="com.xingshang.entity.User"> SELECT u.username, u.password, r.roleId AS "roleid", CONCAT(u.username,u.password_salt) AS "salt" FROM users u JOIN user_role r on u.id=r.userId WHERE u.username=#{userName} </select> <select id="selectRole" parameterType="String" resultType="String"> SELECT r.role FROM roles r where r.id=(select z.roleId FROM users u join user_role z on u.id=z.userId where u.username=#{username}) </select> <select id="selectPermission" parameterType="String" resultType="String"> select p.permission from permissions p join role_permisssion x on p.id=x.permissionId where x.roleId=(select z.roleId FROM users u join user_role z on u.id=z.userId where u.username=#{username}) </select> </mapper>
shirodemo.sql
/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50558 Source Host : localhost:3306 Source Database : shirodemo Target Server Type : MYSQL Target Server Version : 50558 File Encoding : 65001 Date: 2018-03-26 21:27:58 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `permissions` -- ---------------------------- DROP TABLE IF EXISTS `permissions`; CREATE TABLE `permissions` ( `id` int(11) NOT NULL, `permission` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of permissions -- ---------------------------- INSERT INTO `permissions` VALUES ('1', 'add'); INSERT INTO `permissions` VALUES ('2', 'delete'); INSERT INTO `permissions` VALUES ('3', 'update'); INSERT INTO `permissions` VALUES ('4', 'select'); -- ---------------------------- -- Table structure for `role_permisssion` -- ---------------------------- DROP TABLE IF EXISTS `role_permisssion`; CREATE TABLE `role_permisssion` ( `id` int(11) NOT NULL AUTO_INCREMENT, `roleId` int(255) DEFAULT NULL, `permissionId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of role_permisssion -- ---------------------------- INSERT INTO `role_permisssion` VALUES ('1', '4', '1'); INSERT INTO `role_permisssion` VALUES ('2', '4', '2'); -- ---------------------------- -- Table structure for `roles` -- ---------------------------- DROP TABLE IF EXISTS `roles`; CREATE TABLE `roles` ( `id` int(11) NOT NULL, `role` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of roles -- ---------------------------- INSERT INTO `roles` VALUES ('1', 'CEO'); INSERT INTO `roles` VALUES ('2', 'CTO'); INSERT INTO `roles` VALUES ('3', 'CFO'); INSERT INTO `roles` VALUES ('4', 'admin'); -- ---------------------------- -- Table structure for `user_role` -- ---------------------------- DROP TABLE IF EXISTS `user_role`; CREATE TABLE `user_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) DEFAULT NULL, `roleId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; -- ---------------------------- -- Records of user_role -- ---------------------------- INSERT INTO `user_role` VALUES ('1', '1', '1'); INSERT INTO `user_role` VALUES ('2', '1', '2'); INSERT INTO `user_role` VALUES ('3', '1', '3'); INSERT INTO `user_role` VALUES ('4', '1', '4'); INSERT INTO `user_role` VALUES ('5', '2', '4'); -- ---------------------------- -- Table structure for `users` -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, `password_salt` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `idx_users_username` (`username`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of users -- ----------------------------INSERT INTO `users` VALUES ('1', 'miaomiao', '2a9c616f5dc6d23329ad4622ff8fa89f', 'b58c47e10cc56807ce31010a41c7fa65'); INSERT INTO `users` VALUES ('2', 'admin', '123', null);
//执行认证操作.