SpringSecurity介绍

Spring Security 是针对 Spring 项目的安全框架,也是 Spring Boot 底层安全模块默认的技术选型。它可以实现强大的 Web 安全控制。对于安全控制吧,我们仅如引入 Security 场景启动器,进行少量配置,即可实现强大的安全管理。

应用程序安全的主要两个区域就是“认证”和“授权”:

  • 认证(Authentication):建立一个声明主体的过程,主体一般是指用户。
  • 授权(Authorization):指确定一个主体是否允许在你的应用程序执行一个动作的过程。

SpringSecurity with Boot 快速开始 | SpringSecurity 官方文档

整合SpringSecurity

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

1、使用 maven 新建 SpringBoot 项目,引入 Web、Thymeleaf、Security 场景启动器,依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.19.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>zze.spring</groupId>
    <artifactId>security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <!--修改 thymeleaf 依赖版本为 3 -->
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
        <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--thymeleaf 模板中使用 springsecurity 标签-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

pom.xml

2、编写测试模板页:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<div sec:authorize="!isAuthenticated()">
    <a th:href="@{/login}">请登录</a>
</div>
<div sec:authorize="isAuthenticated()">
    <span sec:authentication="name"/> 您好,您拥有角色:<span sec:authentication="principal.authorities"/>
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="注销">
    </form>
</div>
<div sec:authorize="hasRole('VIP1')"><a th:href="@{/level/1}">LEVEL 1</a></div>
<div sec:authorize="hasRole('VIP2')"><a th:href="@{/level/2}">LEVEL 2</a></div>
<div sec:authorize="hasRole('VIP3')"><a th:href="@{/level/3}">LEVEL 3</a></div>
</body>
</html>

templates/welcome.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录页</title>
</head>
<body>
<form th:action="@{/login}" method="post" >
    用户名:<input type="text" name="username"> <br>
    密码:<input type="text" name="password"> <br>
    <input type="checkbox" name="rememberMe">
    <input type="submit" value="登录"/>
</form>

</body>
</html>

templates/login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>级别</title>
</head>
<body>
<a th:href="@{/}">首页</a>

<h1 th:text="${level}"></h1>
</body>
</html>

templates/pages/level.html

3、编写测试 Controller:

package zze.spring.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class TestController {
    private final String PREFIX = "pages/";

    // 欢迎页
    @GetMapping("/")
    public String index() {
        return "welcome";
    }

    @GetMapping("/level/{level}")
    public String level(@PathVariable Integer level, Model model) {
        model.addAttribute("level", level == 1 ? "初级" : level == 2 ? "中级" : "高级");
        return PREFIX + "level";
    }

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

zze.spring.security.controller.TestController

4、配置:

package zze.spring.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 编写配置类继承 WebSecurityConfigurerAdapter
 */
@EnableWebSecurity // 启用 WebSecurity 模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 控制请求的访问权限
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        // 定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll() // "/" 允许任何人访问
                .antMatchers("/level/1").hasRole("VIP1") // "/level/1" 仅允许拥有角色 VIP1 的主体访问
                .antMatchers("/level/2").hasRole("VIP2") // "/level/2" 仅允许拥有角色 VIP2 的主体访问
                .antMatchers("/level/3").hasRole("VIP3"); // "/level/3" 仅允许拥有角色 VIP3 的主体访问

        // 开启自动配置的登录功能,开启后未登录状态访问将会自动重定向到 /login 登录页
        //   1、访问 /login 来到登录页
        //   2、重定向到 /login?error 表示登录失败
        //   3、可通过 loginPage() 方法修改使用自己的登录页,登录请求需要为 post,的用户名参数默认为 username ,密码参数为 password 。
        //   4、如果使用了 loginPage() 方法修改了登录页,那么该请求的 post 方式就是登录请求。比如修改 /userLogin 为登录页,那么 post 请求 /userLogin 则是登录操作
        http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login");

        // 开启自动配置的注销
        //   1、访问 /logout 表示用户注销,情况 session
        //   2、注销成功默认会重定向到 /login?logout
        //
        //  通过 logoutSuccessUrl("/") 方法指定注销成功重定向的页面
        http.logout().logoutSuccessUrl("/");

        // 开启记住我功能
        //   1、登录成功后,将 cookie 发送给浏览器保存,以后访问都会带上这个 cookie,通过检查就可以免登录
        //   2、点击注销会删除 cookie
        //   3、可通过 rememberMeParameter 方法定义登录操作的记住我参数名
        http.rememberMe().rememberMeParameter("rememberMe");
    }

    // 定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1", "VIP2") // 内存中存入一个用户(主体),用户名为 zhangsan 密码为 123456,拥有角色 VIP1 和 VIP2
                .and()
                .withUser("lisi").password("123456").roles("VIP2", "VIP3") // 内存中存入一个用户(主体),用户名为 lisi 密码为 123456,拥有角色 VIP2 和 VIP3
                .and()
                .withUser("wangwu").password("123456").roles("VIP1", "VIP3"); // 内存中存入一个用户(主体),用户名为 wangwu 密码为 123456,拥有角色 VIP1 和 VIP3
    }
}

zze.spring.security.config.SecurityConfig

java框架之SpringBoot(15)-安全及整合SpringSecurity的更多相关文章

  1. java框架之SpringBoot(16)-分布式及整合Dubbo

    前言 分布式应用 在分布式系统中,国内常用 Zookeeper + Dubbo 组合,而 SpringBoot 推荐使用 Spring 提供的分布式一站式解决方案 Spring + SpringBoo ...

  2. java框架之SpringBoot(12)-消息及整合RabbitMQ

    前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...

  3. java框架之SpringBoot(13)-检索及整合Elasticsearch

    ElasticSearch介绍 简介 我们的应用经常需要使用检索功能,开源的 Elasticsearch 是目前全文搜索引擎的首选.它可以快速的存储.搜索和分析海量数据.SpringBoot 通过整合 ...

  4. (七) SpringBoot起飞之路-整合SpringSecurity(Mybatis、JDBC、内存)

    兴趣的朋友可以去了解一下前五篇,你的赞就是对我最大的支持,感谢大家! (一) SpringBoot起飞之路-HelloWorld (二) SpringBoot起飞之路-入门原理分析 (三) Sprin ...

  5. 【SpringBoot】Springboot2.x整合SpringSecurity

    一.Spring Security是什么?有什么作用(核心作用)?以及如何阅读本篇文章 1.是什么 Spring Security是Spring家族的一个强大的安全框架,与Springboot整合的比 ...

  6. java框架之SpringBoot(9)-数据访问及整合MyBatis

    简介 对于数据访问层,无论是 SQL 还是 NOSQL,SpringBoot 默认采用整合 SpringData 的方式进行统一处理,添加了大量的自动配置,引入了各种 Template.Reposit ...

  7. 【java框架】SpringBoot(5)--SpringBoot整合分布式Dubbo+Zookeeper

    1.理论概述 1.1.分布式 分布式系统是若干独立计算机的集合,这些计算机对于用户来讲就像单个系统. 由多个系统集成成一个整体,提供多个功能,组合成一个板块,用户在使用上看起来是一个服务.(比如淘宝网 ...

  8. java框架之SpringBoot(11)-缓存抽象及整合Redis

    Spring缓存抽象 介绍 Spring 从 3.1 版本开始定义了 org.springframework.cache.Cache 和 org.springframework.cache.Cache ...

  9. 【java框架】SpringBoot(7) -- SpringBoot整合MyBatis

    1.整合MyBatis操作 前面一篇提到了SpringBoot整合基础的数据源JDBC.Druid操作,实际项目中更常用的还是MyBatis框架,而SpringBoot整合MyBatis进行CRUD也 ...

随机推荐

  1. vim:放弃hjkl

    vim放弃使用hjkl,可以加快文本的编辑速度,不信,看我摘录的文章:http://vimcasts.org/blog/2013/02/habit-breaking-habit-making/ Wor ...

  2. 微信公众号 chinaxdt 的 解压密码 mima

    关于密码:解压密码获取方式第一步关注微信号“chinaxdt”第二步发送信息“mima”即可获取自动回复解压密码 这个 chinaxdt 的微信公众号已经失效,所以大家也不用去加了,密码我这告诉大家. ...

  3. C语言 · 还款计算

    标题: 还款计算 银行贷款的等额本息还款方法是: 每月还固定的金额,在约定的期数内正好还完(最后一个月可能会有微小的零头出入). 比如说小明在银行贷款1万元.贷款年化利率为5%,贷款期限为24个月. ...

  4. Android WebRTC开发入门

    在学习 WebRTC 的过程中,学习的一个基本步骤是先通过 JS 学习 WebRTC的整体流程,在熟悉了整体流程之后,再学习其它端如何使用 WebRTC 进行互联互通. 申请权限 Camera 权限 ...

  5. Linux服务器重启后eureka报错

    在Linux服务器重启后,首次启动应用时查看eureka注册中心,报错 EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP W ...

  6. 对世界首款“人工智能”ERP系统HUE的初步了解 - AI ERP - WAP - 万革始

    偶然的机会,刚好在查找机器人王国[奇妙的餐厅]的时候,看到开发[光的王国],[奇妙的宾馆],[奇妙的餐厅]等豪斯登堡集团在3月17日采用了这个传说中的世界首款人工智能ERP系统AI WORKS的下面4 ...

  7. linux java 安装

    对于java的开发,有openJDK 和 orcale jdk两种,大多数的linux 系统都会内置openjdk的安装包,但是大多数java项目的开发都是基于orcale jdk的,所以安装orca ...

  8. http 请求 post get 长度限制

    一.问题起因在某项目释放后Bug统计的附件<释放后问题>里有:   问题  原因  分析  备注  CSV处理时,如果处理的主题数过多,发生URL参数上限的错误:  可变长度的参数通过UR ...

  9. SpringBoot面试题及答案整理

    1. Spring 和 SpringBoot 有什么不同? Spring 框架提供多种特性使得 web 应用开发变得更简便,包括依赖注入.数据绑定.切面编程.数据存取等等. 随着时间推移,Spring ...

  10. BarTender怎样同时打印自动日期和流水号?

    大多数条形码中都会含有日期和数量信息,而且大部分都是两者兼具.有些使用BarTender软件的小伙伴,不知道怎么同时打印自动日期和流水号,即条形码中兼有自动日期和序列号,且它们都能根据打印的变化而变化 ...