一、Spring Security 介绍

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块的默认技术选型。我们仅需引入spring-boot-stater-security模块,进行少量的配置,即可实现强大的安全管理功能。

重要类

  • WebSecurityConfigurerAdapter:定义Security策略。
  • AuthenticationManagerBuilder:定义认证策略

二、Demo

使用 IDEA 通过 Spring Initializer 创建一个Spring Boot项目并选中 security 、web、thymeleaf模块。并导入实验素材(存储在我的github上,链接无效是因为图片、文件我是上传到github上的,请进入我的github观看)。

pom.xml:

<?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>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yunche</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>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--引入 thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</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> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

项目文件树结构如下图:

打开KungfuController类:

package com.atguigu.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; @Controller
public class KungfuController {
private final String PREFIX = "pages/";
/**
* 欢迎页
* @return
*/
@GetMapping("/")
public String index() {
return "welcome";
} /**
* 登陆页
* @return
*/
@GetMapping("/userlogin")
public String loginPage() {
return PREFIX+"login";
} /**
* level1页面映射
* @param path
* @return
*/
@GetMapping("/level1/{path}")
public String level1(@PathVariable("path")String path) {
return PREFIX+"level1/"+path;
} /**
* level2页面映射
* @param path
* @return
*/
@GetMapping("/level2/{path}")
public String level2(@PathVariable("path")String path) {
return PREFIX+"level2/"+path;
} /**
* level3页面映射
* @param path
* @return
*/
@GetMapping("/level3/{path}")
public String level3(@PathVariable("path")String path) {
return PREFIX+"level3/"+path;
} }

此时我们访问:http://localhost:8080/

这说明了Spring Security已经生效了,并且它需要我们认证后才可以访问。所以我们需要编写一个类继承

WebSecurityConfigurerAdapter 来自定 Security 策略,并加上@EnableWebSecurity:开启WebSecurity模式:

package com.yunche.security.config;

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; /**
* @ClassName: MySecurityConfig
* @Description:
* @author: yunche
* @date: 2019/02/07
*/
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
http.authorizeRequests().antMatchers("/").permitAll();
}
}

此时,"/"请求全部允许通过,访问localhost:8080,就可以进入正常的首页了:

此时我们为了使不同的登录用户,查看到不同的武林秘籍(类似于普通用户和管理员),就可以让不同的登录用户根据一些规则成为特定的角色,此过程称为认证。然后再授权给不同的角色不同的访问权限。

此时我们还可以访问localhost:8080/level1/1,查看普通的武功秘籍信息,接下来我们就来实现认证授权

  • 认证:这一过程显然是发生在登录中的,首先添加基于登录表单的认证:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http); //自定义规则
    http.authorizeRequests().antMatchers("/").permitAll()
    .and().formLogin() //开启基于登录表单的认证
    ; }

    此时login请求会进入默认的登录表单认证,点击登录按钮,访问:localhost:8080/login,结果如下:

    MySecurityConfig:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // super.configure(auth);
    auth.inMemoryAuthentication() // 添加基于内存的身份验证
    .withUser("zhangsan").password("z123").roles("VIP1") //将用户张三认证成VIP1角色
    .and()
    .withUser("lisi").password("l123").roles("VIP2") //将用户李四认证成VIP2角色
    .and()
    .withUser("wangwu").password("w123").roles("VIP3") //将用户王五认证成VIP3角色
    ;
    }
  • 授权:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http); //自定义规则
    http.authorizeRequests().antMatchers("/").permitAll()
    .antMatchers("/level1/**").hasRole("VIP1") //允许VIP角色1访问/level1/**请求
    .antMatchers("/level2/**").hasRole("VIP2") //允许VIP角色2访问/level2/**请求
    .antMatchers("/level3/**").hasRole("VIP3") //允许VIP角色3访问/level3/**请求
    .and().formLogin() //开启基于登录表单的认证
    ; }

    此时访问localhost:8080/level/1请求,就会要求进行身份验证:

    输入用户名和密码,会发现进入错误页面:

    查询官方文档可知,现在的版本(Spring Security 5)需要指定密码加密的格式:

      @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // super.configure(auth);
    auth.inMemoryAuthentication() // 添加基于内存的身份验证
    .passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("z123")).roles("VIP1") //将用户张三认证成VIP1角色
    .and()
    .passwordEncoder(new BCryptPasswordEncoder()).withUser("lisi").password(new BCryptPasswordEncoder().encode("l123")).roles("VIP2") //将用户李四认证成VIP2角色
    .and()
    .passwordEncoder(new BCryptPasswordEncoder()).withUser("wangwu").password(new BCryptPasswordEncoder().encode("w123")).roles("VIP3") //将用户王五认证成VIP3角色
    ;
    }

    随意点击一个武林秘籍阅读,输入相应角色的账号,密码,登录成功后会自动进入相应的页面。(注意,此时如果访问该角色无权访问的页面会得到一个403 forbidden)。

接下来添加一个点击按钮注销用户的功能:

  1. 在授权规则里添加如下代码:

    //开启自动注销的功能,默认规则,通过发送 /logout请求,来注销用户并清空session
    http.logout().logoutSuccessUrl("/"); //注销后来到首页
  2. 编写form表单用于发送注销请求:

    welcome.html:

    <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
    
    <form th:action="@{/logout}" method="post">
    <input type="submit" value="注销">
    </form>
    <hr>

此时就完成了注销功能。接下来,再来实现 2 个功能:

  1. 用户登录后才显示注销按钮,未登录显示登录按钮。
  2. 用户登录成功,显示 xxx用户你好,并根据用户角色的权限显示不同的首页。

首先,我们已经引入了thymeleaf 和 security 的整合依赖,然后为welcome.html 加上 xmlns:sec="http://www.thymeleaf.org/extras/spring-security",这样当我们输入sec 时(security 的标签)会有自动提示。

修改好welcome.html 如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<!--未验证才显示该元素-->
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div> <!--验证后才显示该元素-->
<div sec:authorize="isAuthenticated()">
<!--使用 principal.username取出用户名 -->
<h1 align="center">用户<span sec:authentication="principal.username"></span>,您好~
<!--使用 principal.authorities 取出用户的角色-->
<br>您的角色是:<span sec:authentication="principal.authorities"></span>
</h1> <form th:action="@{/logout}" method="post" >
<input type="submit" value="注销" >
</form>
</div> <hr> <!--当用户属于 VIP1角色时才显示该元素-->
<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> <div sec:authorize="hasRole('VIP2')">
<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>
</div> <div sec:authorize="hasRole('VIP3')">
<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</div> </body>
</html>

还可以添加上 记住我功能,再这之前,我们需要自定义登录页面,使用我们自己的登录页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎登陆武林秘籍管理系统</h1>
<hr>
<div align="center">
<form action="" method="post">
用户名:<input name=""/><br>
密码:<input name=""><br/>
<input type="submit" value="登陆">
</form>
</div>
</body>
</html>

在 security 授权策略中,加上:

http.formLogin().loginPage("/userlogin"); //登录页为发送/userlogin 后返回的页面

并将原来链接中的login 替换为 userlogin

<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎登陆武林秘籍管理系统</h1>
<hr>
<div align="center">
<form th:action="@{/userlogin}"method="post">
用户名:<input name="username"/><br>
密码:<input name="password"><br/>
<input type="checkbox" name="remember"> 记住我<br/>
<input type="submit" value="登陆">
</form>
</div>
</body>
</html>
//开启记住我功能,如果能够接收到 name 为 remember 的表单元素, 默认过期时间为14天
http.rememberMe().rememberMeParameter("remember");

三、参考资料

尚硅谷.Spring Boot 高级

Spring Security 介绍与Demo的更多相关文章

  1. Spring Security 介绍

    Spring Security介绍 开源 提供企业级的安全认证和授权 Spring安全拦截器 认证管理器 认证模式 Basic HTTP 1.0中使用的认证方法,使用用户名和密码Base64编码的方式 ...

  2. springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)

    项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖  ...

  3. [spring security] spring security 4 基础Demo

    依赖包: <properties> <junit.version>4.11</junit.version> <spring.version>4.1.6. ...

  4. Spring Security OAuth2 Demo —— 密码模式(Password)

    前情回顾 前几节分享了OAuth2的流程与授权码模式和隐式授权模式两种的Demo,我们了解到授权码模式是OAuth2四种模式流程最复杂模式,复杂程度由大至小:授权码模式 > 隐式授权模式 > ...

  5. Spring Security OAuth2 Demo —— 客户端模式(ClientCredentials)

    前情回顾 前几节分享了OAuth2的流程与其它三种授权模式,这几种授权模式复杂程度由大至小:授权码模式 > 隐式授权模式 > 密码模式 > 客户端模式 本文要讲的是最后一种也是最简单 ...

  6. Spring Security + JWT学习

    开胃:Oauth2认证流程分析 现在第三方登录已经很普遍了,随便哪个App都会有使用微信登录,使用手机号码登录,或者使用支付宝登录等功能... 下面我们就以使用微信登录,做一个简单的流程分析分析 开胃 ...

  7. Java安全框架(一)Spring Security

    Java安全框架(一)Spring Security ​ 文章主要分三部分 1.Spring Security的架构及核心组件:(1)认证:(2)权限拦截:(3)数据库管理:(4)权限缓存:(5)自定 ...

  8. Spring Security安全框架入门篇

    一.Spring Security相关概念 1.1..Spring Security介绍: Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安 ...

  9. Spring Security 安全框架

    一 简介:Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spr ...

随机推荐

  1. 解决Hibernate4执行update操作,不更新数据的问题

    后台封装java对象,使用hibernate4再带的update,执行不更新数据,不报错. 下面贴出解决方法: 失败的方法 hibernate自带update代码:(失效) Session sessi ...

  2. shell 爬虫 从日志分析到数据采集与分析

    [root@VM_61_158_centos ~]# curl http://ip.chinaz.com/220.112.233.179 |grep -e Whwtdhalf.*span.*span. ...

  3. werkzeug 详解

    首先,先向大家介绍一下什么是 werkzeug,Werkzeug是一个WSGI工具包,他可以作为一个Web框架的底层库.这里稍微说一下, werkzeug 不是一个web服务器,也不是一个web框架, ...

  4. nginx配置改变默认访问路径

    在安装完nginx服务后,url访问的默认路径是安装的路径html文件夹下的内容,如果需要指定自定义的路径,需要配置nginx.conf文件内容,这样通过url访问就可以了,比如: http://12 ...

  5. 百度上传组件 WebUploader

    WebUploader http://fex.baidu.com/webuploader/doc/index.html WebUploader API 文档详细解读 源码以及示例:https://gi ...

  6. bzoj 1634: [Usaco2007 Jan]Protecting the Flowers 护花【贪心】

    因为交换相邻两头牛对其他牛没有影响,所以可以通过交换相邻两头来使答案变小.按照a.t*b.f排降序,模拟着计算答案 #include<iostream> #include<cstdi ...

  7. 洛谷 P1233 木棍加工

    题目描述 一堆木头棍子共有n根,每根棍子的长度和宽度都是已知的.棍子可以被一台机器一个接一个地加工.机器处理一根棍子之前需要准备时间.准备时间是这样定义的: 第一根棍子的准备时间为1分钟: 如果刚处理 ...

  8. macbookpro安装Ubuntu16.04.1 LTS爬坑之旅。亲测有效(集众家之长)。安装时间为2017-11-19。

    1.格式化U盘 要求:(1)切换分区格式为Mac OS扩展 (日志型):(2)方案(scheme)设置为:GUID Partition Map:如图(使用mac自带磁盘工具) 2.给Ubuntu划分磁 ...

  9. WMI 技术

    什么是WMI? Windows Management Instrumentation (WMI)是可伸缩的系统管理结构,该规范采用一个统一.基于标准且可扩展的面向对象接口.它提供与系统管理员信息和基础 ...

  10. [转]c++中的string常用函数用法总结

    标准c++中string类函数介绍 注意不是CString之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必 担心内存是否足够.字符串长度等等,而且作为 ...