shiro入门

1.创建oracle数据库对应的数据库表结构和数据

CREATE TABLE sys_permission (
	  id number(20) NOT NULL ,
	  name varchar2(128) NOT NULL ,
	  type varchar2(32) NOT NULL  ,
	  url varchar2(128) DEFAULT NULL  ,
	  percode varchar2(128) DEFAULT NULL  ,
	  parentid number(20) DEFAULT NULL  ,
	  parentids varchar2(128) DEFAULT NULL  ,
	  sortstring varchar2(128) DEFAULT NULL ,
	  available char(1) DEFAULT NULL ,
	  PRIMARY KEY (id)
	) ;
	
	/*Table structure for table sys_role */
	
	CREATE TABLE sys_role (
	  id varchar2(36) NOT NULL,
	  name varchar2(128) NOT NULL,
	  available char(1) DEFAULT NULL  ,
	  PRIMARY KEY (id)
	) ;
	
	/*Table structure for table sys_role_permission */
	
	CREATE TABLE sys_role_permission (
	  id varchar2(36) NOT NULL,
	  sys_role_id varchar2(32) NOT NULL ,
	  sys_permission_id varchar2(32) NOT NULL ,
	  PRIMARY KEY (id)
	);
	
	/*Table structure for table sys_user */
	
	CREATE TABLE sys_user (
	  id varchar2(36) NOT NULL  ,
	  usercode varchar2(32) NOT NULL ,
	  username varchar2(64) NOT NULL ,
	  password varchar2(32) NOT NULL ,
	  salt varchar2(64) DEFAULT NULL ,
	  locked char(1) DEFAULT NULL  ,
	  PRIMARY KEY (id)
	) ;
	
	/*Table structure for table sys_user_role */
	
	CREATE TABLE sys_user_role (
	  id varchar2(36) NOT NULL,
	  sys_user_id varchar2(32) NOT NULL,
	  sys_role_id varchar2(32) NOT NULL,
	  PRIMARY KEY (id)
	) ;
	
	insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (1,'权限','menu','null',NULL,0,'0/','0','1');
	 insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (11,'商品管理','menu','/item/queryItem.action',NULL,1,'0/1/','1.','1');
	 insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (12,'商品新增','permission','/item/add.action','item:create',11,'0/1/11/','','1');
	 insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (13,'商品修改','permission','/item/editItem.action','item:update',11,'0/1/11/','','1');
	 insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (14,'商品删除','permission','','item:delete',11,'0/1/11/','','1');
	 
	 insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (15,'商品查询','permission','/item/queryItem.action','item:query',11,'0/1/15/',NULL,'1');
	 insert  into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (21,'用户管理','menu','/user/query.action','user:query',1,'0/1/','2.','1');
	 insert into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (22,'用户新增','permission','','user:create',21,'0/1/21/','','1');
	 insert into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (23,'用户修改','permission','','user:update',21,'0/1/21/','','1');
	 insert into sys_permission(id,name,type,url,percode,parentid,parentids,sortstring,available) values
	 (24,'用户删除','permission','','user:delete',21,'0/1/21/','','1');
	insert  into sys_role(id,name,available) values ('ebc8a441-c6f9-11e4-b137-0adc305c3f28','商品管理员','1');
	insert  into sys_role(id,name,available) values ('ebc9d647-c6f9-11e4-b137-0adc305c3f28','用户管理员','1');
	
	/*Data for the table sys_role_permission */
	
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) values ('ebc8a441-c6f9-11e4-b137-0adc305c3f21','ebc8a441-c6f9-11e4-b137-0adc305c','12'),('ebc8a441-c6f9-11e4-b137-0adc305c3f22','ebc8a441-c6f9-11e4-b137-0adc305c','11'),('ebc8a441-c6f9-11e4-b137-0adc305c3f24','ebc9d647-c6f9-11e4-b137-0adc305c','21'),('ebc8a441-c6f9-11e4-b137-0adc305c3f25','ebc8a441-c6f9-11e4-b137-0adc305c','15'),('ebc9d647-c6f9-11e4-b137-0adc305c3f23','ebc9d647-c6f9-11e4-b137-0adc305c','22'),('ebc9d647-c6f9-11e4-b137-0adc305c3f26','ebc8a441-c6f9-11e4-b137-0adc305c','13');
	
	/*Data for the table sys_user */
	
	insert  into sys_user(id,usercode,username,password,salt,locked) 
		values ('lisi','lisi','李四','bf07fd8bbc73b6f70b8319f2ebb87483','uiwueylm','0'),
		('zhangsan','zhangsan','张三','cb571f7bd7a6f73ab004a70322b963d5','eteokues','0');
	
	/*Data for the table sys_user_role */
	
	insert  into sys_user_role(id,sys_user_id,sys_role_id) values ('ebc8a441-c6f9-11e4-b137-0adc305c3f28','zhangsan','ebc8a441-c6f9-11e4-b137-0adc305c'),('ebc9d647-c6f9-11e4-b137-0adc305c3f28','lisi','ebc9d647-c6f9-11e4-b137-0adc305c');
	
	
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) 
		values ('ebc8a441-c6f9-11e4-b137-0adc305c3f21','ebc8a441-c6f9-11e4-b137-0adc305c','12');
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) 
		values	('ebc8a441-c6f9-11e4-b137-0adc305c3f22','ebc8a441-c6f9-11e4-b137-0adc305c','11');
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) 
		values	('ebc8a441-c6f9-11e4-b137-0adc305c3f24','ebc9d647-c6f9-11e4-b137-0adc305c','21');
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) 
		values	('ebc8a441-c6f9-11e4-b137-0adc305c3f25','ebc8a441-c6f9-11e4-b137-0adc305c','15');
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) 
		values	('ebc9d647-c6f9-11e4-b137-0adc305c3f23','ebc9d647-c6f9-11e4-b137-0adc305c','22');
	insert  into sys_role_permission(id,sys_role_id,sys_permission_id) 
		values	('ebc9d647-c6f9-11e4-b137-0adc305c3f26','ebc8a441-c6f9-11e4-b137-0adc305c','13');
	
	
	insert  into sys_user(id,usercode,username,password,salt,locked) 
		values ('lisi','lisi','李四','bf07fd8bbc73b6f70b8319f2ebb87483','uiwueylm','0');
	insert  into sys_user(id,usercode,username,password,salt,locked) 
		values 	('zhangsan','zhangsan','张三','cb571f7bd7a6f73ab004a70322b963d5','eteokues','0');
	
	
	insert  into sys_user_role(id,sys_user_id,sys_role_id) values 
		('ebc8a441-c6f9-11e4-b137-0adc305c3f28','zhangsan','ebc8a441-c6f9-11e4-b137-0adc305c');
	
	insert  into sys_user_role(id,sys_user_id,sys_role_id) values 	('ebc9d647-c6f9-11e4-b137-0adc305c3f28','lisi','ebc9d647-c6f9-11e4-b137-0adc305c');

2.创建几个表对应的实体类

3.在springboot-mybatis-shiro的基础上,添加支持的jar包

<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>1.4.0</version>
		</dependency>

项目结构
在这里插入图片描述

resources
pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.1.0.6.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/ojdbc6-11.1.0.6.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
   </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!--添加mybatis generator maven插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <!--generatorConfig.xml位置-->
                    <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <phase>generate-sources</phase>
                    </execution>
                </executions>
                <!--此处必须添加oracle驱动包-->
                <dependencies>
                    <dependency>
                        <groupId>com.oracle</groupId>
                        <artifactId>ojdbc6</artifactId>
                        <version>11.1.0.6.0</version>
                        <scope>system</scope>
                        <systemPath>${basedir}/src/main/resources/lib/ojdbc6-11.1.0.6.0.jar</systemPath>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

#spring.datasource.platform=mysql
#spring.datasource.url=jdbc:mysql://localhost/mydb
#spring.datasource.username=root
#spring.datasource.password=hnqy
#spring.datasource.driverClassName=com.mysql.jdbc.Driver
logging.level.com.teng.springbootshiro.mapper=trace
spring.datasource.platform=oracle
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/orcl
spring.datasource.username=jtf
spring.datasource.password=123456
server.port=8080
server.session-timeout=30
server.tomcat.uri-encoding=UTF-8
#####springboot 整合 mybatis
mybatis.mapper-locations= classpath:/com/teng/springbootshiro/mapper/*Mapper.xml
#mybatis.config-location= classpath:/com/teng/springbootshiro/config/mybatis-config.xml
#####定义别名
mybatis.type-aliases-package=com.teng.springbootshiro.domain
###Thymeleaf配置
spring.thymeleaf.prefix=classpath:/html/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
###过滤中文乱码
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
#spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-idle=8

SysUserMapper.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.teng.springbootshiro.mapper.SysUserMapper">
  <resultMap id="BaseResultMap" type="com.teng.springbootshiro.domain.SysUser">
    <id column="ID" jdbcType="VARCHAR" property="id" />
    <result column="USERCODE" jdbcType="VARCHAR" property="usercode" />
    <result column="USERNAME" jdbcType="VARCHAR" property="username" />
    <result column="PASSWORD" jdbcType="VARCHAR" property="password" />
    <result column="SALT" jdbcType="VARCHAR" property="salt" />
    <result column="LOCKED" jdbcType="CHAR" property="locked" />
  </resultMap>
  <sql id="Base_Column_List">
    ID, USERCODE, USERNAME, PASSWORD, SALT, LOCKED
  </sql>
    <select id="findUser" resultType="SysUser">
        select * from sys_user
        where usercode = #{usercode}
    </select>
    <select id="findPermission" resultType="SysPermission">
        select * from sys_permission
         where id in
         (select sys_permission_id
         from sys_role_permission
         where sys_role_id in
         (select sys_role_id from sys_user_role where sys_user_id= #{usercode} ))
    </select>
</mapper>

mapper
SysUserMapper

package com.teng.springbootshiro.mapper;
import com.teng.springbootshiro.domain.SysPermission;
import com.teng.springbootshiro.domain.SysUser;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface SysUserMapper {
    //通过用户code查找用户对象
    public SysUser findUser(String usercode);
    //通过用户code查找权限列表
    public List<SysPermission> findPermission(String usercode);
}

service
SysUserService

package com.teng.springbootshiro.service;
import com.teng.springbootshiro.domain.SysPermission;
import com.teng.springbootshiro.domain.SysUser;
import java.util.List;
/**
 * Created by Administrator on 2018/12/24 0024.
 */
public interface SysUserService {
    //通过用户code查找用户对象
    public SysUser findUser(String usercode);
    //通过用户code查找权限列表
    public List<SysPermission> findPermission(String usercode);
}

service
impl
SysUserServiceImpl

package com.teng.springbootshiro.service.impl;
import com.teng.springbootshiro.domain.SysPermission;
import com.teng.springbootshiro.domain.SysUser;
import com.teng.springbootshiro.mapper.SysUserMapper;
import com.teng.springbootshiro.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resources;
import java.util.List;
/**
 * Created by Administrator on 2018/12/24 0024.
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public SysUser findUser(String usercode) {
        return sysUserMapper.findUser(usercode);
    }
    @Override
    public List<SysPermission> findPermission(String usercode) {
        return sysUserMapper.findPermission(usercode);
    }
}

SpringBoot01Application

package com.teng;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Springboot01Application {
	public static void main(String[] args) {
		SpringApplication.run(Springboot01Application.class, args);
	}

}

4.创建shiro核心类

ShiroConfig

package com.teng.springbootshiro.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

//配置文件注解
@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器.
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/static/**", "anon");
        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");
        //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
        //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        //filterChainDefinitionMap.put("/userInfo/userList", "userInfo:view");
        filterChainDefinitionMap.put("/**", "authc");
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");

        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 凭证匹配器
     * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * )
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
        return hashedCredentialsMatcher;
    }

    @Bean
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myShiroRealm;
    }


    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    /**
     *  开启shiro aop注解支持.
     *  使用代理方式;所以需要开启代码支持;
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean(name="simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver
    createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
        mappings.setProperty("UnauthorizedException","403");
        r.setExceptionMappings(mappings);  // None by default
        r.setDefaultErrorView("error");    // No default
        r.setExceptionAttribute("ex");     // Default is "exception"
        //r.setWarnLogCategory("example.MvcLogger");     // No default
        return r;
    }

    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }
}

5.创建自定义realm认证类

MyShiroRealm

package com.teng.springbootshiro.shiro;


import com.teng.springbootshiro.domain.SysPermission;
import com.teng.springbootshiro.domain.SysUser;
import com.teng.springbootshiro.service.SysUserService;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by Administrator on 2018/12/24 0024.
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;

    //给当前realm起个名
    @Override
    public String getName() {
        return "customReam02";
    }
    //支持UsernamePasswordToken
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户主身份---用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //通过用户名查找用户对应的权限列表
        List<SysPermission> permissionList = sysUserService.findPermission(username);
        //创建一个授权对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        for(SysPermission sysPermission:permissionList){
            authorizationInfo.addStringPermission(sysPermission.getPercode());
        }
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份
        String username = (String) authenticationToken.getPrincipal();
        //通过用户名,查找对应的用户是否存在,如果存在返回用户对象
        SysUser sysUser = sysUserService.findUser(username);
        if(sysUser == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                sysUser.getUsercode(), //用户名
                sysUser.getPassword(), //密码
                ByteSource.Util.bytes(sysUser.getSalt()),//salt
                getName()  //realm name
        );
        return authenticationInfo;
    }
}

6.controller 包下创建homeController和SysUserController

HomeController

package com.teng.springbootshiro.controller;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class HomeController {
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }
    @RequestMapping("/login")
    public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
        System.out.println("HomeController.login()");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");
        System.out.println("exception=" + exception);
        String msg = "";
        if (exception!= null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                System.out.println("UnknownAccountException -- > 账号不存在:");
                msg = "UnknownAccountException -- > 账号不存在:";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                System.out.println("IncorrectCredentialsException -- > 密码不正确:");
                msg = "IncorrectCredentialsException -- > 密码不正确:";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                System.out.println("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            } else {
                msg = "else >> "+exception;
                System.out.println("else -- >" + exception);
            }
        }
        map.put("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        return "login";
    }
    @RequestMapping("/403")
    public String unauthorizedRole(){
        System.out.println("------没有权限-------");
        return "403";
    }

}

SysUserController

package com.teng.springbootshiro.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * Created by Administrator on 2018/12/24 0024.
 */
@Controller
public class SysUserController {
    /**
     * 用户查询.
     * @return
     */
    @RequestMapping("/userList")
    public String userInfo(){
        return "userInfo";
    }
    @RequestMapping("/userDel")
    @RequiresPermissions("item:delete")//权限管理;
    public String userDel(){
        return "userDel";
    }
}

7.创建html文件

login.html
index.html
403.html
userList.html
userDel.html

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
 描述:<h4 th:text="${msg}">message</h4>
    用户登录页面
    <form action="" method="post">
        <input type="text" name="username"><br/>
        <input type="text" name="password"><br/>
        <input type="submit" value="登录">
    </form>
</body>
</html>

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
 描述:<h4 th:text="${msg}">message</h4>
    用户登录页面
    <form action="" method="post">
        <input type="text" name="username"><br/>
        <input type="text" name="password"><br/>
        <input type="submit" value="登录">
    </form>
</body>
</html>

403.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    你没有权限!
</body>
</html>

userDel.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
userDel
</body>
</html>

userInfo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    用户信息页面
</body>
</html>

8.通过工具类,找回密码

package com.qy.springboot01.util;
import com.qy.springboot01.domain.SysUser;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * Created by lenovo on  三月
 */
public class SignUpHelper {
        //生成随机数
        private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        private String algorithmName = "md5";           //加密算法
        private final int hashIterations = 2;           //散列次数

    /**
     * 注册的时候,随机产生一个salt,将密码进行加密处理。
     * toHex将变量改为其他进制
     * @param user
     */
    public void encryptPassword(SysUser user) {
            // User对象包含最基本的字段Username和Password
            String salt = randomNumberGenerator.nextBytes().toHex();
            user.setSalt(salt);
            // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据,散列过程使用了盐
            String newPassword = new SimpleHash(algorithmName, user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()), hashIterations).toHex();
            user.setPassword(newPassword);
            System.out.println(salt+"----"+user.getPassword()+"===="+user.getUsername());
        }
     public static void main(String[] args){
        SysUser sysUser = new SysUser();
        sysUser.setUsername("zhangsan");
        sysUser.setPassword("123456");
        new SignUpHelper().encryptPassword(sysUser);
     }
}

测试

运行项目,在浏览器中输入localhost:8080/index.html
在这里插入图片描述
输入账号密码
账号不存在
在这里插入图片描述
输入正确,跳到你第一次输入导航栏的地址
在这里插入图片描述
访问userList,跳到用户信息界面,因为userList只要登陆上就可以访问,不需要权限
在这里插入图片描述
访问userDel,不让访问,并告知你没有权限
在这里插入图片描述
换个有权限的登录
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值