SpringBoot集成Spring Security入门体验
一、前言
Spring Security 和 Apache Shiro 都是安全框架,为Java应用程序提供身份认证和授权。
二者区别
- Spring Security:
重量级安全框架 - Apache Shiro:
轻量级安全框架
关于shiro的权限认证与授权可参考小编的另外一篇文章 : SpringBoot集成Shiro 实现动态加载权限
二、SpringBoot集成Spring Security入门体验
基本环境 : springboot 2.1.8
1、引入Spring Security依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、新建一个controller测试访问
@RestController
public class IndexController {
@GetMapping("/index")
public String index() {
return "Hello World ~";
}
}
3、运行项目访问 http://127.0.0.1:8080/index
温馨小提示:在不进行任何配置的情况下,Spring Security 给出的默认用户名为user 密码则是项目在启动运行时随机生成的一串字符串,会打印在控制台,如下图:

当我们访问index首页的时候,系统会默认跳转到login页面进行登录认证

认证成功之后才会跳转到我们的index页面

三、Spring Security用户密码配置
除了上面Spring Security在不进行任何配置下默认给出的用户user 密码随项目启动生成随机字符串,我们还可以通过以下方式配置
1、springboot配置文件中配置
spring:
security:
user:
name: admin # 用户名
password: 123456 # 密码
2、java代码在内存中配置
新建Security 核心配置类继承WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity // 启用Spring Security的Web安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 将用户设置在内存中
* @param auth
* @throws Exception
*/
@Autowired
public void config(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置用户,配置多个用户调用`and()`方法
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder()) // 指定加密方式
.withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN")
.and()
.withUser("test").password(passwordEncoder().encode("123456")).roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
// BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速实现加密加盐
return new BCryptPasswordEncoder();
}
}
3、从数据库中获取用户账号、密码信息
这种方式也就是我们项目中通常使用的方式,这个留到后面的文章再说
四、Spring Security 登录处理 与 忽略拦截
相关代码都有注释相信很容易理解
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 登录处理
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 开启登录配置
http.authorizeRequests()
// 标识访问 `/index` 这个接口,需要具备`ADMIN`角色
.antMatchers("/index").hasRole("ADMIN")
// 允许匿名的url - 可理解为放行接口 - 多个接口使用,分割
.antMatchers("/", "/home").permitAll()
// 其余所有请求都需要认证
.anyRequest().authenticated()
.and()
// 设置登录认证页面
.formLogin().loginPage("/login")
// 登录成功后的处理接口 - 方式①
.loginProcessingUrl("/home")
// 自定义登陆用户名和密码属性名,默认为 username和password
.usernameParameter("username")
.passwordParameter("password")
// 登录成功后的处理器 - 方式②
// .successHandler((req, resp, authentication) -> {
// resp.setContentType("application/json;charset=utf-8");
// PrintWriter out = resp.getWriter();
// out.write("登录成功...");
// out.flush();
// })
// 配置登录失败的回调
.failureHandler((req, resp, exception) -> {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("登录失败...");
out.flush();
})
.permitAll()//和表单登录相关的接口统统都直接通过
.and()
.logout().logoutUrl("/logout")
// 配置注销成功的回调
.logoutSuccessHandler((req, resp, authentication) -> {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("注销成功...");
out.flush();
})
.permitAll()
.and()
.httpBasic()
.and()
// 关闭CSRF跨域
.csrf().disable();
}
/**
* 忽略拦截
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
// 设置拦截忽略url - 会直接过滤该url - 将不会经过Spring Security过滤器链
web.ignoring().antMatchers("/getUserInfo");
// 设置拦截忽略文件夹,可以对静态资源放行
web.ignoring().antMatchers("/css/**", "/js/**");
}
}
五、总结
- 项目引入Spring Security依赖
- 自定义Security核心配置类继承
WebSecurityConfigurerAdapter - 账号密码配置
- 登录处理
- 忽略拦截
案例demo源码
https://gitee.com/zhengqingya/java-workspace
SpringBoot集成Spring Security入门体验的更多相关文章
- SpringBoot集成Spring Security(6)——登录管理
文章目录 一.自定义认证成功.失败处理 1.1 CustomAuthenticationSuccessHandler 1.2 CustomAuthenticationFailureHandler 1. ...
- SpringBoot集成Spring Security(2)——自动登录
在上一章:SpringBoot集成Spring Security(1)——入门程序中,我们实现了入门程序,本篇为该程序加上自动登录的功能. 文章目录 一.修改login.html二.两种实现方式 2. ...
- SpringBoot集成Spring Security(7)——认证流程
文章目录 一.认证流程 二.多个请求共享认证信息 三.获取用户认证信息 在前面的六章中,介绍了 Spring Security 的基础使用,在继续深入向下的学习前,有必要理解清楚 Spring Sec ...
- SpringBoot集成Spring Security(5)——权限控制
在第一篇中,我们说过,用户<–>角色<–>权限三层中,暂时不考虑权限,在这一篇,是时候把它完成了. 为了方便演示,这里的权限只是对角色赋予权限,也就是说同一个角色的用户,权限是 ...
- SpringBoot集成Spring Security(4)——自定义表单登录
通过前面三篇文章,你应该大致了解了 Spring Security 的流程.你应该发现了,真正的 login 请求是由 Spring Security 帮我们处理的,那么我们如何实现自定义表单登录呢, ...
- SpringBoot 集成Spring security
Spring security作为一种安全框架,使用简单,能够很轻松的集成到springboot项目中,下面讲一下如何在SpringBoot中集成Spring Security.使用gradle项目管 ...
- SpringBoot集成Spring Security
1.Spring Security介绍 Spring security,是一个强大的和高度可定制的身份验证和访问控制框架.它是确保基于Spring的应用程序的标准 --来自官方参考手册 Spring ...
- SpringBoot集成Spring Security(1)——入门程序
因为项目需要,第一次接触 Spring Security,早就听闻 Spring Security 功能强大但上手困难,学习了几天出入门道,特整理这篇文章希望能让后来者少踩一点坑(本文附带实例程序,请 ...
- springboot集成spring security安全框架入门篇
一. :spring security的简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下 ...
随机推荐
- lua_lua与.Net互相调用
配置环境:创建C#项目,引入luainterface-1.5.3\Built下面的LuaInterface.dll文件和luanet.dll文件.引入命名空间using LuaInterface 代码 ...
- React生命周期函数理解
一.组件挂载阶段 1. componentWillMount() 该方法在首次渲染之前调用,在一个组件挂载到卸载的过程中,仅仅执行这一次.该函数内可以state初始化的工作,与constructor的 ...
- Storm 系列(二)—— Storm 核心概念详解
一.Storm核心概念 1.1 Topologies(拓扑) 一个完整的 Storm 流处理程序被称为 Storm topology(拓扑).它是一个是由 Spouts 和 Bolts 通过 Stre ...
- electron-vue-webpack引入bootstrap多实例问题Multiple instances of Vue detected!
在node modules里面找到electron-webpack目录, 修改out->main.js白名单内容,增加 whiteListedModules.add("bootstra ...
- 2019NC#1
LINK B Integration 题意: 给定$a_1,a_2,...,a_n$, 计算 $$\frac{1}{π}\int_{0}^{\infty}\frac{1}{\prod\limits_{ ...
- 洛谷P2331 [SCOI2005]最大子矩阵 DP
P2331 [SCOI2005]最大子矩阵 题意 : 这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大.注意:选出的k个子矩阵不能相互重叠. 第一行为n,m,k(1≤n≤ ...
- ZOJ - 3870-Team Formation二进制,位运算
传送门:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3870 题意:找出一个数列中的两个数,所有通过异或和使得结果同时大于 ...
- codeforces 389 D. Fox and Minimal path(构造+思维)
题目链接:https://vjudge.net/contest/175446#problem/J 题解:显然要用最多n个点构成的图要使的得到的最短路条数有1e9次个,显然要有几个数相乘容易想到2的几进 ...
- 基于 KubeSphere CI/CD 将 Spring Boot 项目发布至 Kubernetes
本示例基于开源的 KubeSphere 容器平台 演示如何通过 GitHub 仓库中的 Jenkinsfile 来创建流水线,流水线共包括 8 个阶段,最终将一个 Hello World 页面部署到 ...
- 字符串的api
一.基础 1.字符串.charAt(index) 根据下标获取字符串的某一个字符 应用: 判断字符串的首字母是否大写 任意给定的一串字母,统计字符串里面的大写字母和小写字母的个数 2.字符串.inde ...