Warning

本文已过时,当前内容仅作存档。

请通过 Spring Security 官方文档 和 Apache Shiro 官方文档 了解相关信息。

1. Spring Security

在 Web 开发中,安全一直都是一个非常重要的方面,如果开发的应用出现安全漏洞,极大概率会造成隐私泄露。虽然它属于应用的非功能性需求,但应该在应用设计初期就将其考虑进来,如果不在设计之初就考虑清楚,架构一旦确定再进行更改会对架构产生较大的改动。虽然使用过滤器和拦截器也可以达到安全处理,但市面上也有集成的安全框架。

在市面上有两种比较出名的安全框架,一种是 Spring Security,一种是 Shiro,它们主要用来做两件事:认证、授权。

权限分类:功能权限、访问权限、菜单权限,可以使用大量的原生代码编写拦截器或过滤器来实现这些权限。

先对 Spring Security 进行简单的介绍。

来一手官网:Spring Security 官网 😝

1.1 环境搭建

创建项目时,勾选 Web 与 Thymeleaf,向项目中添加 Web 与 Thymeleaf 的启动器。

导入页面模板(目录结构如下):

index.html
|views
    |level1
        1.html
        2.html
        3.html
    |level2
        1.html
        2.html
        3.html
    |level3
        1.html
        2.html
        3.html
    login.html

为了便于测试,关闭模板引擎的缓存:

spring.thymeleaf.cache=false

编写 Controller,实现基本页面映射,也相当于测试:

@Controller
public class RouterController {

    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id")int id){
        return "views/level1/"+id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id")int id){
        return "views/level2/"+id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id")int id){
        return "views/level3/"+id;
    }
}

编写好代码后,运行项目并测试环境。

1.2 初识 Spring Security

PS:回忆并比较我们学习过的 Spring AOP:横切与配置类。

Spring Security 是针对 Spring 项目的安全框架,它可以实现强大的 Web 安全控制。对于安全控制,仅需引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!

记住常用的几个类和注解:

Spring Security 的两个主要目标是「认证」和「授权」(访问控制)。

「认证」(Authentication):身份验证是通过校验您的凭据(如用户名和密码)来确认您的身份。身份验证通常通过用户名和密码完成,有时也与其他身份验证因素结合使用。

「授权」(Authorization):授权根据访问规则决定您是否可以访问资源(如信息、文件、数据库)或执行某项操作。

这个概念是通用的,而不是只在 Spring Security 中存在。

1.3 认证和授权

导入 Spring Security 的启动器:

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

根据官方文档,编写 Spring Security 配置类:

@EnableWebSecurity // 启用 Spring Security 的 Web 安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
		super.configure(http);
    }
}

在配置类中设计权限规则:

// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
    // 首页允许匿名访问,功能页按角色授权
    http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasAnyRole("vip1")
        .antMatchers("/level2/**").hasAnyRole("vip2")
        .antMatchers("/level3/**").hasAnyRole("vip3");
}

启动程序,进入首页,点击功能页的超链接。此时尚未启用表单登录,匿名访问这些受保护的页面会返回 403(Access Denied)。

因为我们没有进行登录,所以当我们进行需要登录的操作时,应该将页面跳转至登录界面,而不是报错。开启登录界面:

// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
    // 首页允许匿名访问,功能页按角色授权
    http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasAnyRole("vip1")
        .antMatchers("/level2/**").hasAnyRole("vip2")
        .antMatchers("/level3/**").hasAnyRole("vip3");
    // 启用表单登录
    // GET /login 显示默认登录页
    // 登录失败时重定向到 /login?error
    http.formLogin();
}

然后我们可以进行测试:没有登录但进行相关操作时,跳转至登录界面。

Spring Security 登录界面

要怎么为用户设置权限呢?

定义认证规则,重写 configure() 方法。Spring Security 支持在内存中定义用户,也支持从数据库读取用户。

这里演示在内存中定义,在配置类中定义认证规则:

// 认证
// 使用 PasswordEncoder 编码密码,使用 BCrypt 对密码进行单向编码
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 将用户信息保存在内存中
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        .withUser("yang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
        .and()
        .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
        .and()
        .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

登录成功后,每个角色拥有自己的访问权限,且只能进行自己权限下的操作。😉

1.4 注销及权限控制

注销

配置注销功能:

// 配置注销
@Override
protected void configure(HttpSecurity http) throws Exception {
    //....
    // 配置注销功能
    http.logout();
}

添加注销超链接:

<a class="item" th:href="@{/logout}">
   <i class="address card icon"></i> 注销
</a>

登录成功后点击注销,默认进入注销确认页,提交后跳转至 /login?logout。

如果想要注销后跳转至首页呢?

// 注销成功后重定向到首页
http.logout().logoutSuccessUrl("/");

权限控制

现在导航条上有两个按钮(或者说超链接),但是这显然不符合实际情况。需要在用户还没有登录时,导航栏上只显示登录按钮;用户登录成功后,显示用户名和注销按钮,同时页面中只显示用户拥有相应权限的内容。

由于使用的是 Thymeleaf 模板引擎,需要结合 Thymeleaf 中的一些功能。

导入相关依赖:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

修改前端界面:

首先声明命名空间:

<html lang="en" xmlns:th="http://www.thymeleaf.org"
        xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

修改导航栏,添加认证判断:

<!-- 登录与注销 -->
<div class="right menu">

    <!-- 未登录时显示登录链接 -->
    <div sec:authorize="!isAuthenticated()">
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i> 登录
        </a>
    </div>

    <!-- 已登录时显示用户名 -->
    <div sec:authorize="isAuthenticated()">
        <a class="item">
            用户名:<span sec:authentication="name"></span>
            <!-- 角色:<span sec:authentication="principal.authorities"></span> -->
        </a>
    </div>
    
    <div sec:authorize="isAuthenticated()">
        <a class="item" th:href="@{/logout}">
            <i class="sign-out icon"></i> 注销
        </a>
    </div>

</div>

PS:在这里用到了 sec:authorize="isAuthenticated()",用来验证是否登录,进而显示不同的界面。

重启项目,登录系统,查看是否修改成功。

Spring Security 默认启用 CSRF(跨站请求伪造)防护。用 POST 表单提交 /logout 时应携带有效的 CSRF 令牌,否则默认返回 403。

这里直接关闭 CSRF 防护,点击注销链接后直接注销:

@Override
protected void configure(HttpSecurity http) throws Exception {

    // --snip--
    // 关闭 CSRF 防护
    http.csrf().disable();
    // 注销成功后重定向到首页
    http.logout().logoutSuccessUrl("/");
}

继续修改界面,根据用户角色在界面上显示对应的内容:

<div>
    <br>
    <div class="ui three column stackable grid">


        <!-- 仅对具有 vip1 角色的用户显示 -->
        <div class="column" sec:authorize="hasRole('vip1')">
            <div class="ui raised segment">
                <div class="ui">
                    <div class="content">
                        <h5 class="content">Level 1</h5>
                        <hr>
                        <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                        <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                        <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 仅对具有 vip2 角色的用户显示 -->
        <div class="column" sec:authorize="hasRole('vip2')">
            <div class="ui raised segment">
                <div class="ui">
                    <div class="content">
                        <h5 class="content">Level 2</h5>
                        <hr>
                        <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                        <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                        <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 仅对具有 vip3 角色的用户显示 -->
        <div class="column" sec:authorize="hasRole('vip3')">
            <div class="ui raised segment">
                <div class="ui">
                    <div class="content">
                        <h5 class="content">Level 3</h5>
                        <hr>
                        <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                        <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                        <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

1.5 记住我及登录页定制

记住我

用户勾选「记住我」后,登录后关掉浏览器,只要 Cookie 仍然有效,再次打开浏览器时不用重新登录。

直接去配置类中开启记住我:

@Override
protected void configure(HttpSecurity http) throws Exception {
    // ... 
    // 启用「记住我」
    http.rememberMe();
}

此时登录页多了一个「记住我」,勾选它,登录成功后关闭浏览器,再重新打开浏览器,仍能识别用户,不用再次登录。

那么这个功能是怎么实现的呢?

用户勾选「记住我」并登录成功后,服务端将 remember-me Cookie 发送给浏览器保存,以后访问时带上这个 Cookie,只要通过检查就可以免登录了(Cookie 的默认有效期为 14 天)。如果点击注销,就会删除这个 Cookie。

注销删除 Cookie

登录页定制

现在使用的登录页面是 Spring Security 自带的,不是很美观,怎么使用自己编写的界面呢?

在登录页配置后面加上 http.formLogin().loginPage("/toLogin"); 即可。

前端页面也要指向自定义的登录页 /toLogin:

<a class="item" th:href="@{/toLogin}">
   <i class="address card icon"></i> 登录
</a>

如果登录表单要提交到 /login,而登录页面是 /toLogin,可以用 loginProcessingUrl("/login") 指定处理表单的地址:

// 未登录时跳转到自定义登录页
// GET /toLogin 显示登录表单
// POST /login 处理表单提交的凭据
// 用户名和密码参数需与表单字段的 name 属性一致
http.formLogin().loginPage("/toLogin").usernameParameter("username")
    .passwordParameter("password").loginProcessingUrl("/login");

由于使用了自定义的登录界面,「记住我」复选框需要自行添加。在配置类中指定表单字段名:

// 从表单的 remember 参数读取「记住我」选项
http.rememberMe().rememberMeParameter("remember");

同时在登录页添加记住我的组件:

<input type="checkbox" name="remember"> 记住我

2. Shiro

2.1 什么是 Shiro

2.2 有哪些功能

Shiro 功能图

2.3 Shiro 快速开始

官方示例代码:ShiroQuickStart

官方快速开始文档:Shiro 官方教程

创建 Maven 项目,然后导入以下依赖:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.1</version>
</dependency>
<!-- Shiro uses SLF4J for logging.  We'll use the 'simple' binding
             in this example app.  See http://www.slf4j.org for more info. -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.21</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.21</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

拷贝官方的 log4j.properties 到项目的 src/main/resources 目录下:

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

# General Apache libraries
log4j.logger.org.apache=WARN

# Spring
log4j.logger.org.springframework=WARN

# Default Shiro logging
log4j.logger.org.apache.shiro=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

拷贝官方的 shiro.ini 到项目的 src/main/resources 目录下:

[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
# 
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

继续拷贝官方的 Quickstart.java 文件到项目的 src/main/java 目录下:

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

    public static void main(String[] args) {

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                         "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                     "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //all done - log out!
        currentUser.logout();

        System.exit(0);
    }
}

运行后,控制台输出一系列日志。

Shiro 通过 SLF4J 记录日志。slf4j-simple 是本例的日志实现,jcl-over-slf4j 用于桥接 Commons Logging。如果运行时缺少日志绑定,SLF4J 1.7 会发出警告,程序仍能运行,但日志调用不会产生输出。

2.4 Shiro 的 Subject 分析

使用工厂模式解析配置文件 shiro.ini,并创建 SecurityManager 对象:

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);

获取当前的用户对象 Subject:

Subject currentUser = SecurityUtils.getSubject();

通过当前用户获取 Session(Shiro 的 Session,非 Web 中的 Session):

Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
    log.info("Retrieved the correct value! [" + value + "]");
}

判断当前的用户是否被认证:

if (!currentUser.isAuthenticated()) {
    // Token: 令牌
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
    token.setRememberMe(true);	// 设置记住我
    try {
        currentUser.login(token);	// 执行登录操作
    } catch (UnknownAccountException uae) {	// 账号不存在
        log.info("There is no user with username of " + token.getPrincipal());
    } catch (IncorrectCredentialsException ice) { // 凭据不正确
        log.info("Password for account " + token.getPrincipal() + " was incorrect!");
    } catch (LockedAccountException lae) { // 账号已锁定
        log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                 "Please contact your administrator to unlock it.");
    }
    // ... catch more exceptions here (maybe custom ones specific to your application?
    catch (AuthenticationException ae) {	// 认证异常
        //unexpected condition?  error?
    }
}

//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

角色检查:

if (currentUser.hasRole("schwartz")) {
    log.info("May the Schwartz be with you!");
} else {
    log.info("Hello, mere mortal.");
}

权限检查,粗粒度:

if (currentUser.isPermitted("lightsaber:wield")) {
    log.info("You may use a lightsaber ring.  Use it wisely.");
} else {
    log.info("Sorry, lightsaber rings are for schwartz masters only.");
}

权限检查(比第一次检查得更具体),细粒度:

if (currentUser.isPermitted("winnebago:drive:eagle5")) {
    log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
             "Here are the keys - have fun!");
} else {
    log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

账户注销:

currentUser.logout();

退出系统:

System.exit(0);

常用代码:

Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated();
currentUser.getPrincipal();
currentUser.hasRole("schwartz");
currentUser.isPermitted("lightsaber:wield");
currentUser.logout();

2.5 Spring Boot 集成 Shiro

2.5.1 项目准备

创建 Spring Boot 项目,选择导入 Web 和 Thymeleaf 的启动器:

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

编写一个简单的首页,用于测试环境是否搭建成功:

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>首页</h1>
        <p th:text="${msg}"></p>
    </body>
</html>

再编写一个简单的 Controller,用于界面跳转:

@Controller
public class MyController {

    @RequestMapping({"/","index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro!");
        return "index";
    }
}

最后,启动项目,访问:http://localhost:8080/ 检查环境是否搭建成功!

Shiro 三大对象:

2.5.2 创建三大对象

导入整合所需依赖:

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

创建包 config,在包下创建 ShiroConfig.java:

@Configuration
public class ShiroConfig {
        // 3. 创建 ShiroFilterFactoryBean
        // 2. 创建 DefaultWebSecurityManager
        // 1. 创建自定义 Realm
}

倒着来进行创建,先创建 Realm 对象。在 config 包下创建自定义 Realm 类 UserRealm.java:

// 自定义 Realm,继承 AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        return null;
    }

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

登录时会调用 Realm 的认证方法。检查角色或权限时,才会按需获取授权信息。

将自定义的 UserRealm 类添加到 Spring 容器中(在 ShiroConfig 类中编写):

// 1. 创建自定义 Realm
@Bean(name = "userRealm")
public UserRealm userRealm(){
    return new UserRealm();
}

创建 DefaultWebSecurityManager:

// 2. 创建 DefaultWebSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    // 关联 UserRealm
    securityManager.setRealm(userRealm);
    return securityManager;
}

创建 ShiroFilterFactoryBean:

// 3. 创建 ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    // 设置安全管理器
    bean.setSecurityManager(defaultWebSecurityManager);
    return bean;
}

2.5.3 页面拦截

编写两个前端页面:

add.html:

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

update.html:

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

在控制器中编写跳转代码:

@RequestMapping("/user/add")
public String add(){
    return "user/add";
}

@RequestMapping("/user/update")
public String update(){
    return "user/update";
}

在 index.html 中编写用于点击的超链接:

<a th:href="@{/user/add}">add</a>

<a th:href="@{/user/update}">update</a>

在配置类中添加 Shiro 过滤器:

// 3. 创建 ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    // 设置安全管理器
    bean.setSecurityManager(defaultWebSecurityManager);
    // Shiro 内置过滤器
    /*
     * anon:无需认证就能访问
     * authc:必须认证才能访问
     * user:允许已认证或通过「记住我」识别的用户访问
     * perms:拥有对某个资源的权限才能访问
     * roles:要求用户具有指定角色
     */
    // 配置过滤器链
    Map<String, String> filterMap = new LinkedHashMap<>();
    filterMap.put("/user/add","authc");
    filterMap.put("/user/update","authc");
	bean.setFilterChainDefinitionMap(filterMap);
    return bean;
}

启动项目,运行测试,进入 index 界面后,点击界面上的 add 或 update 超链接,界面不会跳转至对应的界面,而是报错。

这是因为匿名访问受保护的页面时会重定向到登录地址,如果该地址没有对应的页面,就会看到错误页。

需要编写一个登录界面 login.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>登录</h1>
        <hr>
        <!-- 消息提示 -->
        <p th:text="${msg}" style="color: red"></p>
        <form th:action="@{/login}" method="post">
            <p>用户名:<input type="text" name="username"></p>
            <p>密码:<input type="password" name="password"></p>
            <p><input type="submit" value="提交"></p>
        </form>

    </body>
</html>

添加跳转至登录界面的控制器:

@RequestMapping("/toLogin")
public String toLogin(){
    return "login";
}

在 ShiroConfig 配置类中设置登录的请求:

@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
    // ... 
    //        filterMap.put("/user/add","authc");
    //        filterMap.put("/user/update","authc");
	// 用通配符匹配 /user/ 下的一级路径
    // 未登录时跳转到登录页
    filterMap.put("/user/*","authc");
    bean.setFilterChainDefinitionMap(filterMap);

    // 设置登录页地址
    bean.setLoginUrl("/toLogin");

    return bean;
}

2.5.4 用户认证

在 Controller 中编写登录逻辑:

@PostMapping("/login")
public String login(String username,String password,Model model){
    // 获取当前 Subject
    Subject subject = SecurityUtils.getSubject();
    // 将用户名和密码封装为认证令牌
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token); // 正常返回表示登录成功
        return "index";
    } catch (UnknownAccountException e) {   // 账户不存在
        model.addAttribute("msg","用户名不存在!");
        return "login";
    }catch (IncorrectCredentialsException e){
        model.addAttribute("msg","密码不正确!");
        return "login";
    }
}

在 UserRealm 类中编写认证逻辑:

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

    // 模拟登录数据
    String username = "root";
    String password = "123456";
    UsernamePasswordToken userToken = (UsernamePasswordToken) token;

    if (!userToken.getUsername().equals(username)){ // 账户不存在
        return null;    // UnknownAccountException
    }

    return new SimpleAuthenticationInfo("",password,"");
}

2.5.5 整合数据库

导入依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

编写全局配置文件:

spring:
  datasource:
    username: root
    password: 123456
    # serverTimezone=UTC 指定驱动使用的服务器时区
    url: jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    # Spring Boot 默认不注入下面这些属性值的,需要自己绑定
    # 连接池配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    # stat 收集统计信息,wall 检查 SQL,log4j 记录日志
    # 启用 log4j 过滤器时,缺少对应依赖会导致找不到 org.apache.log4j.Priority
    # log4j Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

在配置文件中配置 MyBatis:

mybatis.type-aliases-package=com.yang.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

创建 POJO:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private int id;
    private String name;
    private float money;
    private String password;
}

编写 Mapper 接口:

@Repository
@Mapper
public interface AccountMapper {

    public Account queryAccountByName(String name);
}

编写 MyBatis 映射文件:

<?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.yang.mapper.AccountMapper">

    <select id="queryAccountByName" parameterType="String" resultType="Account">
        select * from account where name = #{name}
    </select>

</mapper>

编写 Service 层的接口和实现类:

public interface AccountService {
    public Account queryAccountByName(String name);
}
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountMapper accountMapper;

    @Override
    public Account queryAccountByName(String name) {
        return accountMapper.queryAccountByName(name);
    }
}

改造 UserRealm 类:

// 自定义 Realm,继承 AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    AccountService accountService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");

        return null;
    }

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

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        Account account = accountService.queryAccountByName(userToken.getUsername());

        if (account == null){ // 账户不存在
            return null;    // UnknownAccountException
        }

        // 此处直接使用数据库中的示例密码
        return new SimpleAuthenticationInfo("", account.getPassword(), "");
    }
}

2.5.6 MD5 盐值加密密码

上述案例里直接比对明文密码,下面演示用 MD5 对密码进行处理。

注意:这里只做演示,即使加盐,MD5 也不适合存储密码。

UserRealm 的父类 AuthorizingRealm 的父类 AuthenticatingRealm 中有一个 setCredentialsMatcher() 方法,它可以设置凭据匹配器。

进入接口 CredentialsMatcher,使用快捷键 Ctrl + Alt + B 查看接口实现类:

CredentialsMatcher 实现类

可以看到有许多实现类,它们提供了不同的凭据匹配方式。

❓ 那如果想要更换凭据匹配方式,应该怎么做呢?

在配置类中创建一个 Bean:

@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
    HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
    // 使用 MD5 散列算法
    hashedCredentialsMatcher.setHashAlgorithmName("md5");
    // 设置散列迭代次数
    hashedCredentialsMatcher.setHashIterations(1);
    return hashedCredentialsMatcher;
}

将创建的 Bean 设置为 Realm 的凭据匹配器:

// 1. 创建自定义 Realm
@Bean(name = "userRealm")
public UserRealm userRealm(){
    UserRealm userRealm = new UserRealm();
    userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
    return userRealm;
}

修改自定义的 Realm:

// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // ... 

    // 设置盐值
    ByteSource salt = ByteSource.Util.bytes(account.getName());
    // 计算加盐后的 MD5 散列值
    SimpleHash simpleHash = new SimpleHash("MD5", account.getPassword(), salt);
    // 打印十六进制散列值
    System.out.println(simpleHash.toString());
    // 参数依次为身份、凭据、盐和 Realm 名称
    return new SimpleAuthenticationInfo(account, simpleHash, salt, "");
}

重新启动项目,进行登录。测试后,登录成功,控制台也打印出测试密码的散列值:

dbb1c112a931eeb16299d9de1f30161d

使用 CMD5 对上述哈希值进行反向查询,得到:

root123456

这是盐值和测试密码拼接后的内容。😎

❓ 那怎么确定使用了设置的匹配器呢?在下方位置打一个断点:

Shiro MD5 加盐散列断点

使用 Debug 模式启动项目,进入首页,点击登录,输入用户名和密码。

在调试器中找到 this,点开它;找到 credentialsMatcher,点开它。可以发现先前进行的配置都显示在这里了。如果使用最开始的方式,这里显示的是默认的凭据匹配器。💪

Debug-credentialsMatcher

2.5.7 用户拦截与授权

在上面的测试中,控制台上多次输出以下信息:

执行了=>认证doGetAuthenticationInfo
执行了=>授权doGetAuthorizationInfo

这表明 Shiro 先执行了登录认证,访问受保护的页面时又进行了权限检查。

拦截

在 ShiroConfig 类的 ShiroFilterFactoryBean 中添加以下代码:

@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
	// ...
    // 分别检查添加和更新账户所需的权限
    filterMap.put("/user/add","perms[account:add]");
    filterMap.put("/user/update","perms[account:update]");
    filterMap.put("/user/*","authc");
	// ... 
    return bean;
}

运行程序,登录,点击页面中的 add 或 update 链接,这时候页面会跳转至错误页面。状态码是 401,显示未授权。

但在真实业务中,不应该跳转至错误页面,应该跳转至权限不足页面。

编写 Controller 模拟跳转至错误页面:

@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
    return "当前用户权限不足!";
}

同时,需要在 ShiroConfig 类的 ShiroFilterFactoryBean 中设置权限不足界面:

@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
   
    // ...

    // 分别检查添加和更新账户所需的权限
    filterMap.put("/user/add","perms[account:add]");
    filterMap.put("/user/update","perms[account:update]");
    filterMap.put("/user/*","authc");
    
    // ...
    
    // 权限不足时的跳转地址
    bean.setUnauthorizedUrl("/noauth");

    return bean;
}

然后,我们可以再进行测试。

运行程序,登录,再点击页面中的 add 或 update 链接,这时页面会跳转至设定的未授权界面。

授权

我们已经让某些界面需要权限才能够访问,那么应该怎么给用户赋予一些权限呢?

在 UserRealm 类中授权方法中添加权限赋予代码:

// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了=>授权doGetAuthorizationInfo");

    // 给资源进行授权
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    // 授予所有用户 account:add 权限
    info.addStringPermission("account:add");

    return info;
}

运行项目,选择任一用户登录系统。

这时候所有的用户都被示例代码显式授予了 account:add 权限。

在实际的业务中,用户的权限信息储存在数据库中,并且不同用户拥有不同的权限。为了达到这个目的,在现有数据库的用户表中添加 perms 字段,表示用户所拥有的对应权限。

数据表增加 perms 字段

让实体类增加一个属性,用来表示用户的权限:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private int id;
    private String name;
    private float money;
    private String password;
    private String perms;
}

更改 UserRealm 类中认证方法的返回值,使授权方法可以获取到当前用户:

return new SimpleAuthenticationInfo(account,account.getPassword(),"");

更改 UserRealm 类中授权方法的代码:

// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了=>授权doGetAuthorizationInfo");

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    // 授予所有用户 account:add 权限
    info.addStringPermission("account:add");

    // 获取当前 Subject
    Subject subject = SecurityUtils.getSubject();
    // 认证时将 Account 作为身份对象传给 SimpleAuthenticationInfo
    Account currentAccount = (Account) subject.getPrincipal();       // 读取当前账户

    // 添加数据库中为该账户配置的权限
    info.addStringPermission(currentAccount.getPerms());

    return info;
}

2.5.8 整合 Thymeleaf

经过上面的编写与测试,用户在没有 update 权限的情况下,进入首页也会显示 update 的链接。

没有对应的权限时,应该不显示对应的链接。

导入 Shiro 与 Thymeleaf 整合的依赖:

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

在配置类 ShiroConfig 中编写 getShiroDialect() 并向容器中添加一个 Bean:

// 注册 ShiroDialect,使模板可以使用 Shiro 标签
@Bean
public ShiroDialect getShiroDialect(){
    return new ShiroDialect();
}

修改 index.html 前端代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/"
      xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>首页</h1>
        <!-- 未认证时显示登录链接 -->
        <div shiro:notAuthenticated>
            <a th:href="@{/toLogin}">登录</a>
        </div>
        <hr>
        <p th:text="${msg}"></p>

        <div shiro:hasPermission="account:add">
            <a th:href="@{/user/add}">add</a>
        </div>
        <div shiro:hasPermission="account:update">
            <a th:href="@{/user/update}">update</a>
        </div>

    </body>
</html>

最后,启动项目,测试即可。

在判断用户是否登录时,还可以从 Session 中取值判断。

更改前端代码:

<!-- 根据会话中的 loginAccount 属性决定是否显示登录链接 -->
<div th:if="${session.loginAccount==null}">
    <a th:href="@{/toLogin}">登录</a>
</div>

在 UserRealm 类的认证方法中设置 Session:

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

    Subject currentSubject = SecurityUtils.getSubject();
    Session session = currentSubject.getSession();
    session.setAttribute("loginAccount",account);
    
    // ...
}

应该在校验密码后写入 loginAccount,也就是 subject.login(token) 成功返回后再写入,否则用户名存在,但密码输错时,登录链接也可能被隐藏。