简介:
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
- WebSecurityConfigurerAdapter:自定义Security策略.
- AuthenticationManagerBuilder:自定义认证策略.
- @EnableWebSecurity:开启WebSecurity模式
spring Security的两个主要目标是“认证"和“授权”(访问控制)。
- “认证”(Authentication)
- “授权”(Authorization)
这个概念是通用的,而不是只在Spring security中存在。
参考官网: https://spring.iolprojects/spring-security,查看我们自己项目中的版本,找到对应的帮助文档:https://docs.spring.io/spring-security/site/docs/5.2.0.RELEASE/reference/htmlsingle
插入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
在config包下新建ScurityConfig,继承WebSecurityConfigurerAdapter
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
super.configure(http);
}
}
授权认证无权限跳转注销代码 :
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception{
// super.configure(http);
//首页所有人可以访问,功能页只有对应有权限的人才能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2");
//没有权限会默认跳到登录页,默认路径为 "/login"
http.formLogin();
//注销, 开启了注销功能
http.logout();//删除cookies,session 或 自定义注销url
}
//认证 springboot 2.1.x 可以直接使用
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// //这些数据正常应该从数据库中读取
// auth.inMemoryAuthentication()
// .withUser("user").password("123456").roles("vip1")
// .and()
// .withUser("root").password("111111").roles("vip1","vip2");
// }
//密码编码:PasswordEncoder
// 在spring Secutiry 5.0+ 新增了很多加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
//这些数据正常应该从数据库中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("user").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2");
}
}
Thymeleaf 和 security 整合
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
具体在HTML页面中的应用:
- 引入"sec"
- url:xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
<div sec:suthorize"isAuthenticated()"> <!--如果登录成功后显示-->
<span sec:authentication="name"></span> <!--获取用户名字-->
</div>
- csrf 关闭防止网站攻击相关(注销失败可能的原因):
http.csrf().disable();