源码自取地址:链接: https://pan.baidu.com/s/12vCcMldjfSx58g75PYnDeA 提取码: q5d9 

一、shiro简介

1.什么是shiro

        1.shiro是apache的一个开源框架,是一个权限管理的框架,实现用户认证,用户授权

        2.spring中有spring security(原名acegi),是一个权限框架,他和spring依赖过于紧密,没有

        shiro使用简单

        3.shiro不依赖于spring,shiro不仅可以实现web应用的权限管理,还可以实现c/s系统,分布

        式系统权限管理,shiro属于轻量框架,越来越多企业项目开始使用shiro

2.在应用程序角度来观察如何使用Shiro完成工作

Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东

西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject 都绑定到

SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个

门面;SecurityManager才是实际的执行者;

SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager 交互;且它管

理着所有Subject;可以看出它是Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习

过SpringMVC,你可以把它看成DispatcherServlet前端控制器

Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要

验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从

Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,

即安全数据源。

3.shiro架构

 3.1 subject:主体,可以是用户也可以是程序,主体要访问系统,系统需要对主体进行认证、授

权。

3.2 securityManager:安全管理器,主体进行认证和授权都是通过securityManager进行。

securityManager是一个集合,真正做事的不是securityManager而是它里面的东西。

3.3 authenticator:认证器,主体进行认证最终通过authenticator进行的。

3.4 authorizer:授权器,主体进行授权最终通过authorizer进行的。

3.5 sessionManager:web应用中一般是用web容器(中间件tomcat)对session进行管理,shiro

也提供一套session管理的方式。

shiro不仅仅可以用于web管理也可以用于cs管理,所以他不用web容器的session管理。

3.6 SessionDao:  通过SessionDao管理session数据,针对个性化的session数据存储需要使用sessionDao(如果用tomcat管理session就不用SessionDao,如果要分布式的统一管理session就要用到SessionDao)。

3.7 cache Manager:缓存管理器,主要对session和授权数据进行缓存(权限管理框架主要就是

对认证和授权进行管理,session是在服务器缓存中的),比如将授权数据通过cacheManager进行

缓存管理,和ehcache整合对缓存数据进行管理(redis是缓存框架)。

3.8 realm:域,领域,相当于数据源,通过realm存取认证、授权相关数据(原来是通过数据库取

的)。

注意:authenticator认证器和authorizer授权器调用realm中存储授权和认证的数据和逻辑。

3.9 cryptography:密码管理,比如md5加密,提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。比如 md5散列算法(md5只有加密没有解密)。

二、shrio授权

1.授权

授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资

源,对于某些资源没有权限是无法访问的。

2.关键对象

授权可简单理解为who对what(which)进行H

        Who,即主体(Subject),主体需要访问系统中的资源。

        What,即资源(Resource),如系统菜单、页面、按钮、类方法、系统商品信息等。资源包括

资源类型资源实例,比如商品信息为资源类型,类型为t01的商品为资源实例,编号为001的商品

信息也属于资源实例。

        How,权限/许可(Permission),规定了主体对资源的操作许可,权限离开资源没有意义,如

用户查询权限、用户添加权限、某个类方法的调用权限、编号为001用户的修改权限等,通过权限

可知主体对哪些资源都有哪些操作许可。

3.授权方式

        基于角色的访问控制

                RBAC基于角色的访问控制(Role-Based Access Control)是以角色为中心进行访问控制

                        if(subject.hasRole("admin")){
                           //操作什么资源
                        }

        基于资源的访问控制

                RBAC基于资源的访问控制(Resource-Based Access Control)是以资源为中心进行访

                问控制

                if(subject.isPermission("user:update:01")){ //资源实例

                        //对01用户进行修改

                        }

                if(subject.isPermission("user:update:*")){ //资源类型

                //对01用户进行修改

                         }

4.权限字符串

        权限字符串的规则时:资源标识符:操作:资源实例标识符,意思是对哪个资源的哪个实例具有什么操作,":"是资源/操作/实例的分隔符,权限字符串也可以使用*通配符

例子:

        用户创建权限:user:create,或user:create:*

        用户修改实例001的权限:user:update:001

        用户实例001的所有权限:user:*:001

         A:B:C,A通过B来操作C

5.shiro中授权编程实现方式 

        编程式:

Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("admin")){
//有权限
}else{
//无权限
}

            注解式:

@RequiresRoles("admin")
pulic void hello(){
//有权限
}

        标签式:

JSP/GSP标签:在JSP/GSP页面通过相应的标签完成:
<shiro:hasRole name = "admin">
    <!-有权限-->
    </shiro:hasRole>
注意:Thymeleaf中使用shiro需要额外集成!

    6.开发授权

               realm的实现:

public class CustomerRealm  extends AuthorizingRealm {

    //认证方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取主身份,也就是用户名
        String primaryPrincipal =(String) principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //添加角色
        simpleAuthorizationInfo.addRole("admin");

        simpleAuthorizationInfo.addStringPermission("user:update:*");
        simpleAuthorizationInfo.addStringPermission("product:*:*");

        return simpleAuthorizationInfo;
    }

    //授权方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal =(String) token.getPrincipal();
        if ("xiaochen".equals(principal)){
            String password = "3c88b338102c1a343bcb88cd3878758e";
            String salt = "Q4F%";
            return new SimpleAuthenticationInfo(principal,
                    password,
                    ByteSource.Util.bytes(salt),
                    this.getName());
        }
        return null;
    }
}

            2.授权

public class TestAuthenticatorCustomerRealm {
    public static void main(String[] args) {
        //创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //IniRealm realm = new IniRealm("classpath:shiro.ini")
        //设置为自定义realm获取认证数据
        CustomerRealm customerRealm = new CustomerRealm();
        //设置md5加密
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        defaultSecurityManager.setRealm(customerRealm);
        //将安装工具类中设置默认安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        //创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("achang", "123");
        try {
            //用户登录
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }

        //认证通过
        if (subject.isAuthenticated()) {
            //基于角色权限管理
            boolean admin = subject.hasRole("admin");

            //基于多角色权限控制,hasAllRole只要有一个该subject不含有,就返回false
            boolean roles = subject.hasAllRoles(Arrays.asList("admin", "super"));

            //是否具有其中一个角色,返回布尔数组,含有就是t,不含就是f
            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "super", "user"));

            boolean permitted = subject.isPermitted("product:create:001");
            System.out.println(permitted);
        }
    }
}

三、Shiro入门案例

1.创建项目

2.导入相关依赖

<!-- shiro 依赖 start-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>    <!-- configure logging -->
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- shiro 依赖 end-->

shiro.ini文件拷贝到resources下 

此代码拷贝过来后会提示下载关于ini的插件,需要下载一下,便于阅读ini类型的文件

[users]
zhangsan = 123456
lisi = 123456

新建几个页面:index.jsp(主页面),add.html,update.html后续我们将通过这三个页面来对我们的Shiro进行测试。这三个页面全部放置在templates下的user(需要自己新建)文件夹下即可:
前端页面中会用到thymeleaf语法,我们先导入thymeleaf的依赖包:

<!-- thymeleaf模板 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

先引入Shiro整合spring的依赖包 

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring-boot-starter</artifactId>
  <version>1.5.3</version>
</dependency>

3、配置shiro环境

(1)配置shiroFilterFactoryBean 

//1.shiroFilter
    //负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        //注入安全管理器
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //注入安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //设置受限资源
        HashMap<String,String> map = new HashMap<>();
        //authc 请求这个资源,需要认证授权
        map.put("/index.jsp","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        return shiroFilterFactoryBean;
    }

(2)配置WebSecurityManager

//2.安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

(3)创建自定义realm

//创建自定义realm
public class CustomRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》认证doGetAuthorizationInfo");
        return null;
    }
}

(4)配置自定义realm 

 //3.自定义Realm
    @Bean
    @Primary
    public CustomRealm getRealm(){
        return new CustomRealm();
    }

导入包名


import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.apache.shiro.realm.Realm;


import java.util.HashMap;

 (5)编写控制器跳转至index.html

@Controller
public class IndexController {
    @RequestMapping("index")
    public String index(){
        System.out.println("跳转到主页");
        return "index";
    }
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>系统主页</h1>
    <a href="">退出用户</a>
    <ui>
        <li><a href="">用户管理</a></li>
        <li><a href="">商品管理</a></li>
        <li><a href="">订单管理</a></li>
        <li><a href="">物流管理</a></li>
    </ui>
</body>
</html>

(6)启动springboot访问index

(7)加入权限控制

        修改ShiroFilterFactoryBean配置

//设置受限资源
HashMap<String, String> map = new HashMap<>();
map.put("/index.jsp","authc");//authc 请求这个资源,需要认证授权
//map.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

//默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
  • /** 代表拦截项目中一切资源 authc 代表shiro中的一个filter的别名,详细内容看文档的shirofilter列表

(8)重启项目访问查看 

4.认证实现

(1)login.jsp开发认证界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    用户名:<input type="text" name="username" > <br/>
    密码  : <input type="text" name="password"> <br>
    <input type="submit" value="登录">
</form>

</body>
</html>

(2)开发controller

@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 用来处理身份认证
     * @param username
     * @param password
     * @return
     * */
    @RequestMapping("/login")
    public String login(String username, String password,String code,HttpSession session) {
        
        try {
            
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username,password));
                return "index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误!");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "login";
    }
}

重定向 :

         redirect的使用:redirect:login.Jsp表示当前请求这层目录加login.jsp 也就是 当前是在localhost/user 提交后是localhost/user/login.jsp
        转发/重定向:redirect:/login.jsp 表示根目录下的login.Jsp 也就是web/login.jsp或localhost/login.jsp

        Action的请求也是如此,建议所有的请求都加/在前,表示从web根目录开始,如:localhost/login

        WEB-INF :代表是个受保护的文件,默认是客户端无法访问的也就是网页地址无法访问,只

能通过服务器端访问,服务端才可以使用的文件地址地址,用于放置客户端无法直接访问,必须使

用controller(servlet)访问

        Web:是默认静态文件的根目录 即/配置文件的根目录 项目/resource(必须使用resource root

标记),默认直接读取代码的根目录 src

        在SpringMVC中返回值是转发/重定向时是不走视图解析器的,同时转发是服务器内部的操作

所以可以操作WEB-INF 下的文件,重定向是游览器的操作的所以只能访问web下的文件,被保护

的WEB-INF的文件无法使用的,(其实视图解析器也是使用转发实现的),所以要操作WEB-INF

下文件使用转发还是重定向看是否要携带数据过去,一般都是直接使用视图解析器,直接返回界面

名称,去配置文件定义的文件内找到对应的视图

        因为我在appilcation.yml中配置了路径,所以将redirect:/index.jsp和redirect:/login.jsp改成index和login即可

  • 在认证过程中使用subject.login进行认证

(3)开发realm中返回静态数据(未连接数据库)

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》认证doGetAuthorizationInfo");
        String principal = (String) token.getPrincipal();
        if ("achang".equals(principal)){
            return new SimpleAuthenticationInfo(principal,"123456",this.getName());
        }
        return null;
    }
 

 认证功能没有md5和随机盐的认证就实现了

5.退出认证

        (1)开发页面退出连接

                

         (2)开发controller

                

         (3)修改退出连接访问退出路径

                

           (4) 退出之后访问受限资源立即返回认证界面

                

 6.MD5,Salt的认证实现

        (1)开发数据库注册

                a.开发注册界面

        

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="${pageContext.request.contextPath}/user/register" method="post">
    用户名: <input type="text" name="username"> <br/>
    密码 : <input type="text" name="password"> <br>
    <input type="submit" value="立即注册">
</form>
</body>
</html>

                 b.创建数据表结构

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
    `id` int(6) NOT NULL AUTO_INCREMENT,
    `username` varchar(40) DEFAULT NULL,
    `password` varchar(40) DEFAULT NULL,
    `salt` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

                

                 c.引入项目依赖

<!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.19</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--mybatis相关依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

                d.配置application.yml配置文件

server:
  port: 8080

  servlet:
    context-path: /shiro

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/student_test?characterEncoding=UTF-8
    password: root
    username: root
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
  application:
    name: shiro

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity

    server.servlet.context-path 解析:

        Servlet 是一种 Java 应用程序,用于在 Web 服务器上处理客户端的请求并向客户端发送响

应。它通常用于构建 Web 应用程序。而 context-path 是指在 Web 应用程序部署到服务器上后,

客户端访问该应用程序的 URL 中的路径部分。在这里,context-path 是 “/shiro”,表示该应用程序

将会在服务器上的根路径 “/shiro” 下提供服务。例如,如果该应用程序有一个名为 “login” 的

Servlet,那么客户端可以通过访问 URL “http://localhost:8080/shiro/login” 来访问该 Servlet。 

       因为配置类加了 server.servlet.context-path:/shiro ,因此前端的路径都要加上/shiro

                e.创建entity实体

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String id;

    private String username;

    private String password;

    private String salt;
}

记得添加lombok依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

                f.添加salt工具类

public class SaltUtils {
    /**
     * 生成salt的静态方法
     * @param n
     * @return
     * */

    public static String getSalt(int n){
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }
}

                g.开发controller

 @Autowired
    private UserService userService;
    
    /**
     * 用户注册
     * */
    
    @RequestMapping("register")
    public String register(User user){
        try{
            userService.register(user);
            return "login";
        }catch (Exception e){
            e.printStackTrace();
            return "register";
        }
    }

                h.创建mapper接口

@Mapper
public interface UserMapper {
    void save(User user);
}

        ·        i.创建service接口

public interface UserService {
    void register(User user);
}

                j.创建service实现类

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        //处理业务逻辑调用mapper
        //1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        //2.将随机盐保存到数据
        user.setSalt(salt);
        //3.明文密码进行md5+salt+hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword());
        user.setPassword(md5Hash.toHex());
        userMapper.save(user);
    }
}

                k.开发mpper配置文件

<?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.example.demo.mapper.UserMapper">

    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user values (#{id},#{username},#{password},#{salt})
    </insert>
</mapper>

                l.启动项目进行注册

         (2)开发数据库认证

                a.开发controller

/**
     * 根据用户名查询业务
     * */
    @RequestMapping("findByUserName")
    public User findByUserName(String username){
        return userService.findByUserName(username);
    }

                 b.开发service接口

public interface UserService {
    //注册用户方法
    void register(User user);

    //根据用户名查询业务的方法
    User findByUserName(String username);

}

                c.开发service实现类

@Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

                d.开发mapper接口

@Mapper
public interface UserMapper {

    void save(User user);

    //根据身份信息认证的方法
    User findByUserName(String username);
    
}

                e.开发mapper配置文件

<select id="findByUserName" resultType="User" parameterType="String">
        select id,username,password,salt from t_user
        where username = #{username}
    </select>

                f.开发在工厂中获取bean对象的工具类

@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
    
    //根据bean名字获取工厂中指定bean对象
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
}

                g.修改自定义realm

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》认证doGetAuthorizationInfo");
        String principal = (String) token.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        //根据身份信息查询
        User user = userService.findByUserName(principal);

        if (!ObjectUtils.isEmpty(user)) {
            //返回数据库信息
            return new SimpleAuthenticationInfo(user.getUsername(),
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()),
                    this.getName());
        }
        return null;
    }

                h.修改ShiroConfig中realm使用凭证匹配器以及hash散列

 //3.自定义Realm
    @Bean
    @Primary
    public CustomRealm getRealm(){
        CustomRealm customRealm = new CustomRealm();
        //设置hashed凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置md5加密
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customRealm.setCredentialsMatcher(credentialsMatcher);
        return customRealm;
    }

7.授权实现

        a.页面资源授权

                index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
</head>
<body>
<h1>系统主页V1.0</h1>
<h1><shiro:principal/></h1>
<shiro:authenticated>
    认证之后展示<br/>
</shiro:authenticated>
<shiro:notAuthenticated>
    没有认证之后展示<br/>
</shiro:notAuthenticated>
<a href="${pageContext.request.contextPath}/user/logout">退出用户</a>
<ul>
    <shiro:hasAnyRoles name="user,admin">
        <li>
            <a href="">用户管理</a>
            <ul>
                <shiro:hasPermission name="user:add:*">
                    <li><a href="">添加</a></li>
                </shiro:hasPermission>
                <shiro:hasPermission name="user:delete:*">
                    <li><a href="">删除</a></li>
                </shiro:hasPermission>
                <shiro:hasPermission name="user:update:*">
                    <li><a href="">修改</a></li>
                </shiro:hasPermission>
                <shiro:hasPermission name="order:find:*">
                    <li><a href="">查询</a></li>
                </shiro:hasPermission>
            </ul>
        </li>
    </shiro:hasAnyRoles>
    <shiro:hasRole name="admin">
        <li><a href="">商品管理</a></li>
        <li><a href="">订单管理</a></li>
        <li><a href="">物流管理</a></li>
    </shiro:hasRole>
</ul>
</body>
</html>

        b.代码方式授权

@Controller
@RequestMapping("order")
public class OrderController {

    @RequestMapping("save")
    public String save(){
        //基于角色
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        //代码方式
        if (subject.hasRole("admin")){
            System.out.println("保存订单");
        }else {
            System.out.println("无权访问");
        }
        //基于字符串方式
        //...
        System.out.println("进入save方法");
        return "index";
    }
}

        c.方法调用授权

//用来判断权限字符串
    @RequiresPermissions("user:update:01")
    //用来判断角色 同时具有admin user
    @RequiresRoles(value = {"admin","user"})
    @RequestMapping("save")
    public String save(){
        System.out.println("进入方法");
        return "index";
    }

        d.授权数据持久化

DROP TABLE IF EXISTS `t_pers`;
CREATE TABLE `t_pers` (
    `id` int(6) NOT NULL AUTO_INCREMENT,
    `name` varchar(80) DEFAULT NULL,
    `url` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_role
-- ----------------------------
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
    `id` int(6) NOT NULL AUTO_INCREMENT,
    `name` varchar(60) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_role_perms
-- ----------------------------
DROP TABLE IF EXISTS `t_role_perms`;
CREATE TABLE `t_role_perms` (
    `id` int(6) NOT NULL,
    `roleid` int(6) DEFAULT NULL,
    `permsid` int(6) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
    `id` int(6) NOT NULL AUTO_INCREMENT,
    `username` varchar(40) DEFAULT NULL,
    `password` varchar(40) DEFAULT NULL,
    `salt` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_user_role
-- ----------------------------
DROP TABLE IF EXISTS `t_user_role`;
CREATE TABLE `t_user_role` (
    `id` int(6) NOT NULL,
    `userid` int(6) DEFAULT NULL,
    `roleid` int(6) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

         e.创建实体类

                user

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "t_user")
public class User implements Serializable {
    private String id;

    private String username;

    private String password;

    private String salt;

    //定义角色集合
    private List<Role> roles;
}

                perms

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "t_perms")
public class Perms implements Serializable {
    private String id;

    private String name;

    private String url;

}

                role

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "t_role")
public class Role implements Serializable {

    private String id;

    private String name;

    //定义权限的集合
    private List<Perms> perms;
}

        f.开发controller

/**
     * 根据角色id查询权限集合
     * */
    @RequestMapping("findPermsByRoleId")
    public List<Perms> findPermsByRoleId(String id){
        return userService.findPermsByRoleId(id);
    }

    /**
     * 根据用户名查询所有角色
     * */
    @RequestMapping("findRolesByUserName")
    public User findRolesByUserName(String username){
        return userService.findRolesByUserName(username);
    }

        g.开发service接口

List<Perms> findPermsByRoleId(String id);

    User findRolesByUserName(String username);

        h.实现service实现类

 @Override
    public List<Perms> findPermsByRoleId(String id) {
        return userMapper.findPermsByRoleId(id);
    }

    @Override
    public User findRolesByUserName(String username) {
        return userMapper.findRolesByUserName(username);
    }

        i.开发mapper

List<Perms> findPermsByRoleId(String id);

    User findRolesByUserName(String username);

         j.实现mapper配置

<resultMap id="userMap" type="User">
        <id column="uid" property="id"/>
        <result column="username" property="username"/>
        <!--角色信息-->
        <collection property="roles" javaType="list" ofType="Role">
            <id column="id" property="id"/>
            <result column="rname" property="name"/>
        </collection>
    </resultMap>

    <select id="findPermsByRoleId" resultType="com.example.demo.entity.Perms">
       select p.id ,p.NAME ,p.url,r.NAME
       from t_role r
       left join t_role_perms rp
       on r.id=rp.roleid
       left join t_perms p on rp.permsid = p.id
       where r.id = #{id}
    </select>

    <select id="findRolesByUserName" resultType="com.example.demo.entity.User">
        select u.id uid,u.username,r.id,r.NAME rname
       from t_user u
       left join t_user ur
       on u.id = ur.userid
       left join t_role r
       on ur.roleid = r.id
       where u.username = #{username}
    </select>

               k.修改自定义realm 

//授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("调用授权验证:"+primaryPrincipal);
        //根据主身份信息获取角色和权限信息
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user =userService.findRolesByUserName(primaryPrincipal);
        //授权角色信息
        if (!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                //权限信息
                List<Perms> perms =userService.findPermsByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(perms)){
                    perms.forEach(perm->{
                        simpleAuthorizationInfo.addStringPermission(perm.getName());
                    });
                }
            });
            return simpleAuthorizationInfo;

        }
        return null;
    }

8.使用CacheManager

        1.Cache作用

                Cache缓存:计算机内存中一段数据

                作用:用来减轻DB的访问压力,从而提高系统的查询效率

        2.使用shiro中默认EhCache实现缓存

         本地缓存

                ①引入依赖

<!--引入shiro和ehache-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <!--版本要和shiro一致-->
            <version>1.5.3</version>
        </dependency>

                ②开启缓存

 //3.创建自定义Realm
    @Bean
    @Primary
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //设置hashed凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置md5加密
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        
        //开启缓存管理器
        //开启全局缓存
        customerRealm.setCachingEnabled(true);
        //开启认证缓存
        customerRealm.setAuthenticationCachingEnabled(true);
        //开启授权缓存
        customerRealm.setAuthorizationCachingEnabled(true);
        customerRealm.setCacheManager(new EhCacheManager());
        return customerRealm;
    }

        3.shiro中使用redis作为缓存实现

                ①引入redis依赖

<!--redis整合springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

               ②配置redis连接

redis:
    port: 6379
    host: localhost
    database: 0

                ③启动redis服务

                 ④开发RedisCacheManager

public class RedisCacheManager implements CacheManager {
    @Override
    public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
        System.out.println("缓存名称:"+cacheName);
        return new RedisCache<K,V>(cacheName);
    }
}

                ⑤开发redisCache实现

public class RedisCache<K, V> implements Cache<K, V> {

    private String cacheName;

    public RedisCache() {

    }

    public RedisCache(String cacheName) {
        this.cacheName = cacheName;
    }

    @Override
    public V get(K k) throws CacheException {
        System.out.println("获取缓存"+k);
        return (V) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
    }

    @Override
    public V put(K k, V v) throws CacheException {
        System.out.println("设置缓存:"+k+"value:"+v);
        getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v);
        return null;
    }

    @Override
    public V remove(K k) throws CacheException {
        return (V) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
    }


    @Override
    public void clear() throws CacheException {
        getRedisTemplate().delete(this.cacheName);
    }

    @Override
    public int size() {
        return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
    }

    @Override
    public Set<K> keys() {
        return getRedisTemplate().opsForHash().keys(this.cacheName);
    }

    @Override
    public Collection<V> values() {
        return getRedisTemplate().opsForHash().values(this.cacheName);
    }

    //封装获取redisTemplate
    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

                ⑥修改自定义realm

  //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        //开启缓存管理
        customerRealm.setCacheManager(new RedisCacheManager());
        customerRealm.setCachingEnabled(true);//全局缓存
        customerRealm.setAuthenticationCachingEnabled(true);//认证缓存
        customerRealm.setAuthenticationCacheName("authenticationCache");
        customerRealm.setAuthorizationCachingEnabled(true);//授权缓存
        customerRealm.setAuthorizationCacheName("authorizationCache");
        return customerRealm;
    }

        ⑦启动报错

错误解释: 由于shiro中提供的simpleByteSource实现没有实现序列化,所以认证存在错误信息

解决方案:需要自动salt实现序列化

        自定义salt实现序列化

//自定义salt实现 实现序列化接口
public class MyByteSource implements ByteSource, Serializable {

    private byte[] bytes;
    private String cachedHex;
    private String cachedBase64;

    //加入无参数构造方法实现序列化和反序列化
    public MyByteSource() {

    }

    public MyByteSource(byte[] bytes) {
        this.bytes = bytes;
    }

    public MyByteSource(char[] chars) {
        this.bytes = CodecSupport.toBytes(chars);
    }

    public MyByteSource(String string) {
        this.bytes = CodecSupport.toBytes(string);
    }

    public MyByteSource(ByteSource source) {
        this.bytes = source.getBytes();
    }

    public MyByteSource(File file) {
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
    }

    public MyByteSource(InputStream stream) {
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
    }

    public static boolean isCompatible(Object o) {
        return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
    }

    public byte[] getBytes() {
        return this.bytes;
    }

    public boolean isEmpty() {
        return this.bytes == null || this.bytes.length == 0;
    }

    public String toHex() {
        if (this.cachedHex == null) {
            this.cachedHex = Hex.encodeToString(this.getBytes());
        }

        return this.cachedHex;
    }

    public String toBase64() {
        if (this.cachedBase64 == null) {
            this.cachedBase64 = Base64.encodeToString(this.getBytes());
        }

        return this.cachedBase64;
    }

    public String toString() {
        return this.toBase64();
    }

    public int hashCode() {
        return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (o instanceof ByteSource) {
            ByteSource bs = (ByteSource) o;
            return Arrays.equals(this.getBytes(), bs.getBytes());
        } else {
            return false;
        }
    }

    private static final class BytesHelper extends CodecSupport {
        private BytesHelper() {
        }

        public byte[] getBytes(File file) {
            return this.toBytes(file);
        }

        public byte[] getBytes(InputStream stream) {
            return this.toBytes(stream);
        }
    }
    
}

        在realm中使用自定义salt

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》认证doGetAuthorizationInfo");
        //根据身份信息
        String principal = (String) token.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        //根据身份信息查询
        User user = userService.findByUserName(principal);

        if (!ObjectUtils.isEmpty(user)) {
            //返回数据库信息
            return new SimpleAuthenticationInfo(user.getUsername(),
                    user.getPassword(),
                    new MyByteSource(user.getSalt()),
                    this.getName());
        }
        return null;
    }

        启动发现可以放入redis缓存

 4.加入验证码验证

        开发页面加入验证码

       验证码工具类

package com.example.demo.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

/**
 *@创建人  
 *@创建时间  
 *@描述   验证码生成
 */
public class VerifyCodeUtils{

    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();


    /**
     * 使用系统默认字符源生成验证码
     * @param verifySize    验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize){
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }
    /**
     * 使用指定源生成验证码
     * @param verifySize    验证码长度
     * @param sources   验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources){
        if(sources == null || sources.length() == 0){
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for(int i = 0; i < verifySize; i++){
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成随机验证码文件,并返回验证码值
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 输出随机验证码图片流,并返回验证码值
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定验证码图像文件
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
        if(outputFile == null){
            return;
        }
        File dir = outputFile.getParentFile();
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch(IOException e){
            throw e;
        }
    }

    /**
     * 输出指定验证码图片流
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for(int i = 0; i < colors.length; i++){
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h-4);

        //绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h-4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for(int i = 0; i < verifySize; i++){
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }
    public static void main(String[] args) throws IOException {
        //获取验证码
        String s = generateVerifyCode(4);
        //将验证码放入图片中
        outputImage(260,60,new File("/Users/chenyannan/Desktop/安工资料/aa.jpg"),s);
        System.out.println(s);
    }
}

               开发页面加入验证码 

<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="text" name="password"><br/>
    请输入验证码:<input type="text" name="code"><img src="${pageContext.request.contextPath}/user/getImage" alt=""><br/>
    <input type="submit" value="登录">
</form>
<a href="${pageContext.request.contextPath}/user/register">点我去注册</a>

                开发控制器

@RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse  response)throws IOException{
        //生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //验证码放入session
        session.setAttribute("code",code);
        //验证码存入图片
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("img/png");
        VerifyCodeUtils.outputImage(220,60,os,code);
    }
}

                放行验证码

map.put("/user/getImage","anon");

                修改认证流程

@RequestMapping("login")
    public String login(String username ,String password,String code,HttpSession session){
        //比较验证码
        String codes = (String) session.getAttribute("code");
        try{
            if (codes.equalsIgnoreCase(code)){
                //获取主题对象
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username,password));
                return "index";
            }else{
                throw new RuntimeException("验证码错误");
            }
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "login";
    }

 

记得修改数据库用户权限

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐