Spring Boot与安全(Spring Security)

作者:神秘网友 发布时间:2020-10-05 16:02:01

Spring Boot与安全(Spring Security)

Spring Boot与安全(Spring Security)

博客中涉及的源码,下载地址在博客文章底部,有需要的小伙伴自行下载

? SpringSecurity 是针对Spring项目的安全框架,也是Spring Boot底层安全模块的技术选项。他可以实现强大的web安全控制。对于安全控制,我们需要引入spring-boot-starter-securiy模块。

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

几个类

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

具体的参考Spring官网:https://spring.io/guides/gs/securing-web/

配置thymeleaf模板依赖(springboot 2.3版本)

// 其他有可能需要配置以下配置,2.3不需要
<properties>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>

以下都需要配置

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

① 引入SpringSecurity

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

② 编写SpringSecurity的配置类

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

}

③ 登入

控制请求的访问权限:

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        // 定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level2/**").hasRole("VIP3");
    }
}

定义认证规则

注意:Security5 与之前的传输密码有部分的不同

参考我这篇博客:https://blog.csdn.net/qq_45738810/article/details/108912554

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3")
                .and()
                .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP3");
    }

开启自动配置的登录功能

  • /login 来登录页
  • 重定项到/login?error 表示登录失败
  • 默认post形式的/login 代表处理登录
  • 一但定制loginPage; 那么 loginPage的 post 请求就是登录
@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    http.authorizeRequests().antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasRole("VIP1")
        .antMatchers("/level2/**").hasRole("VIP2")
        .antMatchers("/level2/**").hasRole("VIP3");

    // 开启自动登录功能
    http.formLogin();
}

Spring Boot与安全(Spring Security)

定制页面

http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");

④ 注销

<form th:action="@{/logout}">
	<input type="submit" value="注销">
</form>
@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    http.authorizeRequests().antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasRole("VIP1")
        .antMatchers("/level2/**").hasRole("VIP2")
        .antMatchers("/level2/**").hasRole("VIP3");

    // 开启自动登录功能
    http.formLogin();
    // 开启注销功能
    http.logout(); // 注销成功会返回 /login?logout 页面
    // http.logout().logoutSuccessUrl("/"); 注销成功以后来到首页
}

Spring Boot与安全(Spring Security)

⑤ 记住我

http.rememberMe();

  • 登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录

  • 点击注销会删除cookie

Spring Boot与安全(Spring Security)

Spring Boot与安全(Spring Security)

定制

<form th:action="@{/userlogin}" method="post">
    用户名:<input name="username"/><br>
    密码:<input name="password"><br/>
    <input type="checkbox" name="remeber"> 记住我<br/>
    <input type="submit" value="登陆">
</form>
@Override
protected void configure(HttpSecurity http) throws Exception {

    .....跟上面一致,省略了

        // 记住我
        http.rememberMe().rememberMeParameter("remeber");
}

Spring Boot与安全(Spring Security)

  • 需要引入thymeleaf-extras-springsecurity5
<properties>
   <thymeleaf-extras-springsecurity5.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity5.version>
</properties>

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

    • sec:authentication=“name” 获得当前用户的用户名

    • sec:authorize=“hasRole(‘ADMIN’)” 当前用户必须拥有ADMIN权限时才会显示标签内容

    • xmlns:sec="http://www.thymeleaf.org/extras/spring-security

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

示例:

<div sec:authorize="!isAuthenticated()"> // 不登入显示以下
    <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>

<div sec:authorize="isAuthenticated()">// 登录显示这个
    <h2><span sec:authentication="name"></span>,您好,您的角色有:
        <span sec:authentication="principal.authorities"></span></h2>
    <form th:action="@{/logout}">
        <input type="submit" value="注销">
    </form>
</div>
<div sec:authorize="hasRole('VIP1')">
    <h3>普通武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level1/1}">罗汉拳</a></li>
        <li><a th:href="@{/level1/2}">武当长拳</a></li>
        <li><a th:href="@{/level1/3}">全真剑法</a></li>
    </ul>
</div>

https://www.thymeleaf.org/doc/articles/springsecurity.html
https://github.com/thymeleaf/thymeleaf-extras-springsecurity
该文档介绍了不同版本的 thymeleaf、 springsecurity 、thymeleaf-extras-springsecurity 对应使用以及一些使用示例

源码下载:

链接:https://pan.baidu.com/s/1oT_Dro3yi4xvSJqccU8D2g
提取码:ljj7

Spring Boot与安全(Spring Security)相关教程

  1. Spring Boot与任务

    Spring Boot与任务 两个注解: @EnableAysns、@Aysnc 代码示例 : @EnableAsync // 开启异步注解功能@SpringBootApplicationpublic class SpringBoot04TaskApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot04TaskAp

  2. 将springboot网站部署到linux服务器上遇到的问题,ssl证书,数据

    将springboot网站部署到linux服务器上遇到的问题,ssl证书,数据库等 1. nginx配置好域名与端口号,域名也配置好了ip地址,可是开启nginx之后,访问域名报错,应该是在nginx.cnf文件中设置了代理地址和端口 2. 在IDEA中将网站源码打包成jar包时,mvn clean报

  3. SpringBoot 多环境切换

    SpringBoot 多环境切换 一般我们在开发阶段选择开发环境,测试选择测试环境,实施选择实施环境。 1、利用 properties 文件修改环境 默认SpringBoot会读取application.properties文件中的环境 application.properties 默认环境 server.port=8882# 选择要使用的

  4. SpringCloud - Eureka服务注册和发现

    SpringCloud - Eureka服务注册和发现 Spring Cloud是一系列框架的有序集合。它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、智能路由、消息总线、负载均衡、断路器、数据监控等,都可以用Spring Boot的开发

  5. MyBatis-Spring的配置使用教程理解(一)

    MyBatis-Spring的配置使用教程理解(一) 序言 在学习MyBatis-Spring项目时,碰到许多问题,但是网上的十分乱,这里总结一下,只是最基本的 概括使用 ,详细内容后续出,希望可以帮助各位。 创建项目: 使用Maven构建一个MyBatis-Spring项目,构建完后要使用

  6. SpringBoot 配置文件位置

    SpringBoot 配置文件位置 SpringBoot 默认读取 application.properties 和 application.yml 文件,properties 和 yml 中的配置相互补充,如果冲突,则 properties 优先级高。 SpringBoot默认读取的配置文件可以存在以下四个目录中: hellowoeld-src-main-java

  7. #SpringMVC转发重定向(关键字方式) #forwardredirect关键字 @FDD

    #SpringMVC:转发、重定向(关键字方式) #forward、redirect关键字 @FDDLC 示例: 关于在SpringMVC中使用forward、redirect关键字的说明: 1、这两种方式都不经过视图解析器,因此需要自己加前后缀。 2、【SpringMVC中使用关键字的重定向】和【传统的重定向】

  8. SpringBoot实现定时任务的三种方式

    SpringBoot实现定时任务的三种方式 一,可以有3种方式配置定时任务 Timer TimerTask Quartz Scheduler Task Execution and Scheduling 二, Quartz Scheduler(配置较为复杂) 1. 引用依赖 dependency groupIdorg.springframework.boot/groupId artifactIdsp