SpringBoot SpringSecurity 介绍(基于内存的验证)
SpringBoot 集成 SpringSecurity + MySQL + JWT 附源码,废话不多直接盘
SpringBoot已经为用户采用默认配置,只需要引入pom依赖就能快速启动Spring Security。
目的:验证请求用户的身份,提供安全访问
优势:基于Spring,配置方便,减少大量代码

内置访问控制方法
permitAll()表示所匹配的 URL 任何人都允许访问。authenticated()表示所匹配的 URL 都需要被认证才能访问。anonymous()表示可以匿名访问匹配的 URL 。和 permitAll() 效果类似,只是设置为 anonymous() 的 url 会执行 filter 链中denyAll()表示所匹配的 URL 都不允许被访问。rememberMe()被“remember me”的用户允许访问 这个有点类似于很多网站的十天内免登录,登陆一次即可记住你,然后未来一段时间不用登录。fullyAuthenticated()如果用户不是被 remember me 的,才可以访问。也就是必须一步一步按部就班的登录才行。
角色权限判断
hasAuthority(String)判断用户是否具有特定的权限,用户的权限是在自定义登录逻辑hasAnyAuthority(String ...)如果用户具备给定权限中某一个,就允许访问hasRole(String)如果用户具备给定角色就允许访问。否则出现 403hasAnyRole(String ...)如果用户具备给定角色的任意一个,就允许被访问hasIpAddress(String)如果请求是指定的 IP 就运行访问。可以通过 request.getRemoteAddr() 获取 ip 地址
引用 Spring Security
Pom 文件中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
点击查看POM代码
<?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">
<parent>
<artifactId>vipsoft-parent</artifactId>
<groupId>com.vipsoft.boot</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>vipsoft-security</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
运行后会自动生成 password 默认用户名为: user

默认配置每次都启动项目都会重新生成密码,同时用户名和拦截请求也不能自定义,在实际应用中往往需要自定义配置,因此接下来对Spring Security进行自定义配置。
配置 Spring Security (入门)
在内存中(简化环节,了解逻辑)配置两个用户角色(admin和user),设置不同密码;
同时设置角色访问权限,其中admin可以访问所有路径(即/*),user只能访问/user下的所有路径。
自定义配置类,实现WebSecurityConfigurerAdapter接口,WebSecurityConfigurerAdapter接口中有两个用到的 configure()方法,其中一个配置用户身份,另一个配置用户权限:
配置用户身份的configure()方法:
SecurityConfig
package com.vipsoft.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户身份的configure()方法
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder)
.withUser("admin")
.password(passwordEncoder.encode("888"))
.roles("ADMIN")
.and()
.withUser("user")
.password(passwordEncoder.encode("666"))
.roles("USER");
}
/**
* 配置用户权限的configure()方法
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//配置拦截的路径、配置哪类角色可以访问该路径
.antMatchers("/user").hasAnyRole("USER")
.antMatchers("/*").hasAnyRole("ADMIN")
//配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面
.and().formLogin();
}
}
添加接口测试用
package com.vipsoft.web.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DefaultController {
@GetMapping("/")
@PreAuthorize("hasRole('ADMIN')")
public String demo() {
return "Welcome";
}
@GetMapping("/user/list")
@PreAuthorize("hasAnyRole('ADMIN','USER')")
public String getUserList() {
return "User List";
}
@GetMapping("/article/list")
@PreAuthorize("hasRole('ADMIN')")
public String getArticleList() {
return "Article List";
}
}

SpringBoot SpringSecurity 介绍(基于内存的验证)的更多相关文章
- SpringSecurity实战记录(一)开胃菜:基于内存的表单登录小Demo搭建
Ps:本次搭建基于Maven管理工具的版本,Gradle版本可以通过gradle init --type pom命令在pom.xml路径下转化为Gradle版本(如下图) (1)构建工具IDEA In ...
- Spark 介绍(基于内存计算的大数据并行计算框架)
Spark 介绍(基于内存计算的大数据并行计算框架) Hadoop与Spark 行业广泛使用Hadoop来分析他们的数据集.原因是Hadoop框架基于一个简单的编程模型(MapReduce),它支持 ...
- SpringBoot使用SpringSecurity搭建基于非对称加密的JWT及前后端分离的搭建
SpringBoot使用SpringSecurity搭建基于非对称加密的JWT及前后端分离的搭建 - lhc0512的博客 - CSDN博客 https://blog.csdn.net/lhc0512 ...
- 高性能、高容错、基于内存的开源分布式存储系统Tachyon的简单介绍
Tachyon是什么? Tachyon是一个高性能.高容错.基于内存的开源分布式存储系统,并具有类Java的文件API.插件式的底层文件系统.兼容Hadoop MapReduce和Apache Spa ...
- Impala基于内存的SQL引擎的详细介绍
一.简介 1.概述 Impala是Cloudera公司推出,提供对HDFS.Hbase数据的高性能.低延迟的交互式SQL查询功能. •基于Hive使用内存计算,兼顾数据仓库.具有实时.批处理.多并发等 ...
- SpringBoot + SpringSecurity + Quartz + Layui实现系统权限控制和定时任务
1. 简介 Spring Security是一个功能强大且易于扩展的安全框架,主要用于为Java程序提供用户认证(Authentication)和用户授权(Authorization)功能. ...
- SpringBoot + SpringSecurity + Mybatis-Plus + JWT + Redis 实现分布式系统认证和授权(刷新Token和Token黑名单)
1. 前提 本文在基于SpringBoot整合SpringSecurity实现JWT的前提中添加刷新Token以及添加Token黑名单.在浏览之前,请查看博客: SpringBoot + Sp ...
- #研发解决方案介绍#基于ES的搜索+筛选+排序解决方案
郑昀 基于胡耀华和王超的设计文档 最后更新于2014/12/3 关键词:ElasticSearch.Lucene.solr.搜索.facet.高可用.可伸缩.mongodb.SearchHub.商品中 ...
- RDD:基于内存的集群计算容错抽象(转)
原文:http://shiyanjun.cn/archives/744.html 该论文来自Berkeley实验室,英文标题为:Resilient Distributed Datasets: A Fa ...
- 基于easyui的验证扩展
基于easyui的验证扩展 ##前言 自己做项目也有好几年的时间了,一直没有时间整理自己的代码,趁春节比较闲,把自己以前的代码整理了一篇.这是基于easyui1.2.6的一些验证扩展,2012年就开始 ...
随机推荐
- 在 vuex 中建立一个 permission.js 文件用于合并静态和动态的路由规则
结果会获取完整的用户的路由规则 // 新建一个vuex模块来专门处理权限相关操作 import { constantRoutes, asyncRoutes } from "@/router& ...
- 8.forEach的使用
1 List<customer> list //一个类是customer的列表 2 3 /* for(int i = 0;i < list.size();i++){ 4 System ...
- beast加密
Beast: https://github.com/liexusong/php-beast?tdsourcetag=s_pctim_aiomsgbeast-安裝到/root------------- ...
- Postgresql 或GreenPlum 查询结果部分字段转json格式并保留字段名(row_to_json)
-- 一些搜索结果给出 部分字段转json保留原字段的方式是用子查询select row_to_json(t) from ( select id, text from words ) t 但是如果子查 ...
- debian 系统中安装 broadcom 无线网卡驱动
首先要修改 apt 的配置文件,允许安装 non-free 软件.即在 /etc/apt/sources.list 中生效的行的最后加上 contrib non-free,再使用 apt-get up ...
- 学习记录--C++组合+依赖+依赖倒置
组合关系:表示类之间的关系是整体与部分的关系.即has a / contains a的关系 在面向对象程序设计中,将一个复杂对象分解为简单对象的组合. 在代码中,体现为将一个或多个类的对象作为另一个类 ...
- windows2003 DHCP服务器配置
一.导入光驱 二.安装可选的windows组件 三.双击打开网路服务,安装DHCP/DNS服务器. 注:服务器地址要固定,因此安装时要规划好网络. 四.ip地址范围规划时要预留i出一些p地址.排除ip ...
- kubernetes集成GPU原理
这里以Nvidia GPU设备如何在Kubernetes中管理调度为例研究, 工作流程分为以下两个方面: 如何在容器中使用GPU Kubernetes 如何调度GPU 容器中使用GPU 想要在容器中的 ...
- (新手向)在Linux中使用VScode编写 "Hello,world"程序,并编写测试-Ubuntu20.4
本文意在帮助 Go 语言初学者在 Linux环境下编写自己的第一个Golang程序 难点主要在 VScode 中 Go 插件的下载 与 go.mod 以及编译运行和 第一个Go测试程序的使用 前提准备 ...
- 等价类计数:Burnside引理和Polya定理 阐述和相关例题
本人不确保结果正确性. 类似的题集也很多,比如 https://ac.nowcoder.com/acm/contest/27275#question 我做了部分题目的题解 https://www.cn ...