SpringSecurity简单使用

什么是SpringSecurity?

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

SpringSecurity核心名词

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

SpringSecurity简单案例

一、引入相关依赖
        <!-- SpringSecurity -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- SpringSecurity整合thymeleaf -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <!-- thymeleaf模板 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
二、认证和授权实现
认证

认证演示.png

授权

从数据库/内存中读取授权信息的代码是相似的,此处为方便练习使用从内存中读取的方式。
值得关注的是在SpringBoot2.2.x及以上的版本中,SpringSecurity强制要求在授权代码处需要为密码添加加密器。如下,分别在.passwordEncoder(加密器).password(加密器)两个位置配置加密器。下面使用了SpringBoot推荐的BCryptPasswordEncoder
授权演示.png
JDBC代码示例
JDBC.png

三、注销实现

注销演示.png
通过查看源码,我们可以看到logout后可继续级联的属性
logout源码提示.png
如上,比如加入.logoutSuccessful("/url")就可以指定注销成功后的跳转页面

前端注销按钮实现
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}">
                        <i class="address card icon"></i> 注销
                    </a>
                </div>
SpringBoot-csrf

在SpringBoot2.0.9以上的版本中,为了防止csrf跨站请求伪造,禁止了表单通过get请求提交数据,所以注销可能发生404错误。有两种解决方案。

  1. 将表单请求改为post
  2. 在SpringSecurity中关闭csrf功能
    下面是用第二种解决方案
    关闭csrf防御.png
四、SpringSecurity整合thymeleaf
1、引入依赖

见前文

2、html页面引入命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
3、使用sec标签进行操作

顶部按钮
顶部按钮选择显示.png
网页模块选择显示.png

五、"记住我"功能实现
        //开启"记住我"功能,默认保存两周
        //.rememberMeParameter()    添加是否记住用户的参数
        http.rememberMe().rememberMeParameter("remember");
六、登录页定制
1、在配置类中定义登录页面

自定义登陆页面.png

2、index页面登录键也指向我们自己的登录页

image.png

3、为登录页的请求设置授权处理请求

在设定自己的登录页后,登录页表单收集到的数据提交到哪里成为一个问题,下面把他们全部设定为同一个请求/login
前端页面
前端页面.png
配置类
配置类.png

4、为自己的登录页添加“记住我”
  • 为前端登陆页面添加"记住我"
    注意参数名为remember
<div class="field">
    <input type="checkbox" name="remember">记住我
</div>

2、配置页面中为rememberMe配置添加参数

http.rememberMe().rememberMeParameter("remember");

2020-5-17

posted @ 2021-01-23 22:24  pedro7  阅读(95)  评论(1编辑  收藏  举报