一分钟带你了解下Spring Security!
一、什么是Spring Security?
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架,它是用于保护基于Spring的应用程序的实际标准。
Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring Security的真正强大之处在于可以轻松扩展以满足自定义要求。
更多信息可以查看官网:https://spring.io/projects/spring-security
二、Spring Security的主要功能
- 认证:验证用户名和密码是否合法(是否系统中用户)
- 授权:是系统用户不代表你能使用某些功能,因为你可能没有权限
- 防御会话固定,点击劫持,跨站点请求伪造等攻击
- Servlet API集成
- 与Spring Web MVC的可选集成
三、快速入门
新建一个SpringBoot的web项目spring-boot-security。
案例1:接口不添加保护
pom文件中不引入Spring Security,然后新建一个controller:
@RestController
public class AppController {
@GetMapping("/hello")
public String hello() {
return "Hello,spring security!";
}
}
然后打开浏览器访问:http://localhost:8080/hello,成功后返回:
Hello,spring security!
案例2:接口添加保护
- pom文件添加依赖
pom文件中引入Spring Security的starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 访问接口
打开浏览器再次访问http://localhost:8080/hello,会被重定向到登录页http://localhost:8080/login,截图如下:

要登录系统,我们需要知道用户名和密码,Spring Security默认的用户名是user,项目启动的时候会生成默认密码(在启动日志中可以看到),输入用户名和密码后就可以访问/hello接口了。
当然也可以自定义用户名密码,在配置文件添加如下内容即可:
spring.security.user.name=java_suisui
spring.security.user.password=123456
四、自定义认证和授权
上面说过Spring Security的功能有“认证”和“授权”,下面通过一个简单的例子实现下自定义的认证和授权。
假设系统中有两个角色:
- ADMIN 可以访问/admin下的资源
- USER 可以访问/user下的资源
按照下面步骤操作即可。
- 新建一个配置类
对于用户名、密码、登录页面、访问权限等都可以在 WebSecurityConfigurerAdapter 的实现类中配置。
WebSecurityConfig代码如下:
/**
* 配置类
* @Author java_suisui
*
*/
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//配置内存中的 用户名、密码和角色
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("user").password("123456").roles("USER");
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("admin").password("123456").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/user").hasRole("USER") //访问 /user这个接口,需要有USER角色
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated() //剩余的其他接口,登录之后就能访问
.and()
.formLogin().defaultSuccessUrl("/hello");
}
}
- 创建PasswordEncorder的实现类
内存用户验证时,Spring Boot 2.0以上版本引用的security 依赖是 spring security 5.X版本,此版本需要提供一个PasswordEncorder的实例。
MyPasswordEncoder代码如下:
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(rawPassword);
}
}
- 登录验证
浏览器打开http://localhost:8080/login,
- 使用user登录,可以访问/user
- 使用admin登录,可以访问/admin
如果使用user登录后访问/admin,会报403错误,具体错误信息如下:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 19 16:26:28 CST 2019
There was an unexpected error (type=Forbidden, status=403).
Forbidden
结果和我们预期的一致,说明简单的自定义认证和授权功能已经实现了。
完整源码地址: https://github.com/suisui2019/springboot-study
推荐阅读
1.一分钟带你学会利用mybatis-generator自动生成代码!
3.SpringBoot系列-整合Mybatis(注解方式)
4.SpringBoot系列-整合Mybatis(XML配置方式)
Java碎碎念,一个坚持原创的公众号,为您提供一系列系统架构、微服务、Java、SpringBoot、SpringCloud等高质量技术文章。
如果觉得文章不错,希望可以随手转发或者”在看“哦,非常感谢哈!
关注下方公众号后回复「1024」,有惊喜哦!

本文由博客一文多发平台 OpenWrite 发布!
一分钟带你了解下Spring Security!的更多相关文章
- 一分钟带你了解下MyBatis的动态SQL!
MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格.列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下. 一. ...
- 手把手带你实战下Spring的七种事务传播行为
目录 本文目录 一.什么是事务传播行为? 二.事务的7种传播行为 三.7种传播行为实战 本文介绍Spring的七种事务传播行为并通过代码演示下. 本文目录 一.什么是事务传播行为? 事务传播行为(pr ...
- 【项目实践】一文带你搞定Spring Security + JWT
以项目驱动学习,以实践检验真知 前言 关于认证和授权,R之前已经写了两篇文章: [项目实践]在用安全框架前,我想先让你手撸一个登陆认证 [项目实践]一文带你搞定页面权限.按钮权限以及数据权限 在这两篇 ...
- spring boot 下 spring security 自定义登录配置与form-login属性详解
package zhet.sprintBoot; import org.springframework.beans.factory.annotation.Autowired;import org.sp ...
- Spring Security笔记:登录尝试次数限制
今天在前面一节的基础之上,再增加一点新内容,默认情况下Spring Security不会对登录错误的尝试次数做限制,也就是说允许暴力尝试,这显然不够安全,下面的内容将带着大家一起学习如何限制登录尝试次 ...
- spring security之httpSecurity使用示例
如果在HttpSecurity中配置需要authenticate(),则如果没有登陆,或没有相关权限,则会无法访问 2017-01-02 23:39:32.027 DEBUG 10396 --- [n ...
- Spring Security Oauth2 的配置
使用oauth2保护你的应用,可以分为简易的分为三个步骤 配置资源服务器 配置认证服务器 配置spring security 前两点是oauth2的主体内容,但前面我已经描述过了,spring sec ...
- spring boot 之 spring security 配置
Spring Security简介 之前项目都是用shiro,但是时过境迁,spring security变得越来越流行.spring security的前身是Acegi, acegi 我也玩过,那都 ...
- Re:从零开始的Spring Security Oauth2(一)
前言 今天来聊聊一个接口对接的场景,A厂家有一套HTTP接口需要提供给B厂家使用,由于是外网环境,所以需要有一套安全机制保障,这个时候oauth2就可以作为一个方案. 关于oauth2,其实是一个规范 ...
随机推荐
- Flash XSS漏洞快速上手
0x01 Flash XSS xss一是指执行恶意js,那么为什么说flash xss呢?是因为flash有可以调用js的函数,也就是可以和js通信,因此这些函数如果使用不当就会造成xss.常见的 ...
- 在博客中增加自己的live2d纸片人模型方法
目录 在博客中增加自己的live2d纸片人模型 准备工具 使用步骤 附件 在博客中增加自己的live2d纸片人模型 准备工具 github仓库:存放live2d模型和json文件 如果你的博客支持本地 ...
- libevent::日志
LibEvent 能记录内部的错误和警告日志,如果编译进日志支持功能,也会记录调试信息.默认情况下这些消息都是输出 到 stderr,你也可以通过提供自己的日志函数的方法来覆盖这种行为. 为了覆盖 L ...
- python2与3实际中遇到的区别
1.type(1/2) python2是向下取整,0,为int:python3是正常除法,0.5,为float 2.
- EXC_BAD_ACCESS的本质详解以及僵尸模式调试原理
原文:What Is EXC_BAD_ACCESS and How to Debug It 有时候,你会遇到由EXC_BAD_ACCESS造成的崩溃. 这篇文章会告诉你什么是EXC_BAD_ACCES ...
- ThreadPoolExecutor使用方法
先看构造方法 ,ThreadPoolExecutor共4个构造方法: 直接看参数最多的7个参数分别代表: public ThreadPoolExecutor(int corePoolSize, int ...
- wpf 依赖强制回调
依赖属性的强制转换加回调,后期自己再改 using System; using System.Collections.Generic; using System.Diagnostics; using ...
- 基于Spring Boot的问答系统之一:elasticsearch 7.2的hello world入门
好久没有写代码了,最近想做一个基于spring boot + vue + elasticsearch + NLP(语义相关性)的小系统练练手,系统后面可以成为一个聊天机器人,客服系统的原型等等. 所以 ...
- Apache2的安装
Apache2的安装 1.执行:sudo apt-get install apache2. 2.sudo vim /etc/apache2/apache2.conf在最后加上:ServerName l ...
- OptimalSolution(1)--递归和动态规划(3)数组和字符串问题
一.最长递增子序列(LIS) 给定数组arr,返回arr的最长递增子序列.例如,arr={2,1,5,3,6,4,8,9,7},返回的最长递增子序列为{1,3,4,5,8,9} 1.时间复杂度为O(N ...