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) 如果用户具备给定角色就允许访问。否则出现 403
  • hasAnyRole(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 介绍(基于内存的验证)的更多相关文章

  1. SpringSecurity实战记录(一)开胃菜:基于内存的表单登录小Demo搭建

    Ps:本次搭建基于Maven管理工具的版本,Gradle版本可以通过gradle init --type pom命令在pom.xml路径下转化为Gradle版本(如下图) (1)构建工具IDEA In ...

  2. Spark 介绍(基于内存计算的大数据并行计算框架)

    Spark 介绍(基于内存计算的大数据并行计算框架)  Hadoop与Spark 行业广泛使用Hadoop来分析他们的数据集.原因是Hadoop框架基于一个简单的编程模型(MapReduce),它支持 ...

  3. SpringBoot使用SpringSecurity搭建基于非对称加密的JWT及前后端分离的搭建

    SpringBoot使用SpringSecurity搭建基于非对称加密的JWT及前后端分离的搭建 - lhc0512的博客 - CSDN博客 https://blog.csdn.net/lhc0512 ...

  4. 高性能、高容错、基于内存的开源分布式存储系统Tachyon的简单介绍

    Tachyon是什么? Tachyon是一个高性能.高容错.基于内存的开源分布式存储系统,并具有类Java的文件API.插件式的底层文件系统.兼容Hadoop MapReduce和Apache Spa ...

  5. Impala基于内存的SQL引擎的详细介绍

    一.简介 1.概述 Impala是Cloudera公司推出,提供对HDFS.Hbase数据的高性能.低延迟的交互式SQL查询功能. •基于Hive使用内存计算,兼顾数据仓库.具有实时.批处理.多并发等 ...

  6. SpringBoot + SpringSecurity + Quartz + Layui实现系统权限控制和定时任务

    1. 简介   Spring Security是一个功能强大且易于扩展的安全框架,主要用于为Java程序提供用户认证(Authentication)和用户授权(Authorization)功能.    ...

  7. SpringBoot + SpringSecurity + Mybatis-Plus + JWT + Redis 实现分布式系统认证和授权(刷新Token和Token黑名单)

    1. 前提   本文在基于SpringBoot整合SpringSecurity实现JWT的前提中添加刷新Token以及添加Token黑名单.在浏览之前,请查看博客:   SpringBoot + Sp ...

  8. #研发解决方案介绍#基于ES的搜索+筛选+排序解决方案

    郑昀 基于胡耀华和王超的设计文档 最后更新于2014/12/3 关键词:ElasticSearch.Lucene.solr.搜索.facet.高可用.可伸缩.mongodb.SearchHub.商品中 ...

  9. RDD:基于内存的集群计算容错抽象(转)

    原文:http://shiyanjun.cn/archives/744.html 该论文来自Berkeley实验室,英文标题为:Resilient Distributed Datasets: A Fa ...

  10. 基于easyui的验证扩展

    基于easyui的验证扩展 ##前言 自己做项目也有好几年的时间了,一直没有时间整理自己的代码,趁春节比较闲,把自己以前的代码整理了一篇.这是基于easyui1.2.6的一些验证扩展,2012年就开始 ...

随机推荐

  1. Typora配置本地图片自动上传阿里云OSS

    一.下载Typora ​ Gitee下载地址 二.下载Picgo.app ​ Github下载地址 三.配置Picgo 打开Typora,格式→图像→图像全局设置: 四.图床设置 注册阿里云账号 打开 ...

  2. 自行封装JDBCUtils

    自己封装JDBCUtils package com.javasm.util; import com.javasm.bean.Emp; import com.javasm.constants.JDBCC ...

  3. 2.IDEA的快捷键

    1.IDEA代码等式两边自动加空格:ctrl+alt+L

  4. 2.javaweb-begin

    1.回顾前端知识 1.CSS 1) CSS的角色:页面显示的美观风格 2) CSS的基础语法:标签样式:类样式:ID样式:组合样式:嵌入式样式表:内部样式表:外部样式表 3) 盒子模型:border. ...

  5. C#中冒号:使用场景

    1. 继承类.实现接口与继承构造函数 ① 继承类 /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public p ...

  6. mybatis_19

    id username birthday sex address 1 王五 2 10 张三 2014-07-10 1 北京市 16 张小明 1 河南郑州 22 陈小明 1 河南郑州 24 张三丰 1 ...

  7. 漫谈Python魔术方法,见过的没见过的都在这里了

    漫谈Python魔术方法,见过的没见过的都在这里了 就说一下,不深入 假的一览 提到魔术方法,学过python都应该知道一些.至少你得会__init__吧. 在我之前写的博文中有很多都涉及魔术方法.比 ...

  8. VsCode新建Java、SpringBoot、Python、JavaWeb项目的基本步骤

    新建Java项目 选中正上方的搜索框,按下F1快捷键,输入create Java,即可出现这样的一个命令: 选中这个: 然后为新创建的项目选择一个合适的位置就好啦! 新建SpringBoot项目 选中 ...

  9. Day04笔记

    01.explicit的作用(了解) class Maker { public: //explicit只能放在构造函数前面,构造函数只有一个参数或其他参数有默认值时 explicit Maker(in ...

  10. 从开源模型、框架到自研,声网 Web 端虚拟背景算法正式发布

    根据研究发现,在平均 38 分钟的视频会议里面,大概会有 13 分钟左右的时间用于处理和干扰相关的事情.同时研究也表明在参加在线会议的时候,人们更加倾向于语音会议,其中一个关键原因就是大家不希望个人隐 ...