# springboot-09-security
**Repository Path**: mjkapps/springboot-09-security
## Basic Information
- **Project Name**: springboot-09-security
- **Description**: Security5的简单使用
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 0
- **Created**: 2019-02-15
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# springboot-security
#### 介绍
springboot2.12 使用security安全框架来进行权限过滤
#### 操作步骤
1. 引入依赖
```
org.springframework.boot
spring-boot-starter-security
org.thymeleaf.extras
thymeleaf-extras-springsecurity5
3.0.4.RELEASE
```
2. 编写Security配置类
@EnableWebSecurity 配置类extends WebSecurityConfigurerAdapter
3. 重写configure(HttpSecurity http)(定制请求的授权规则)与configure(AuthenticationManagerBuilder auth)(定义认证规则)
```
protected void configure(HttpSecurity http) throws Exception {
/**
* 定制请求的授权规则
*/
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
/**
* 开启自动配置的登录功能
* http.formLogin() 1./login来到登录页面
* 2.重定向到/login?error表示登录失败
* 3.默认post形式
* 4.
*/
http.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/userlogin");
/**
* 开启自动配置注销功能
* logoutSuccessUrl("/")注销成功后来到首页
*/
http.logout().logoutSuccessUrl("/");
/**
* 开启记住账号的功能
* 登录成功后将cookie发给浏览器保存,达到免登陆的效果
* 点击注销会清除cookie
*/
http.rememberMe().rememberMeParameter("rembme");
}
```
```
/**
* 定义认证规则
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/**
*因为Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
* Spring Security中密码的存储格式是“{id}…………”。前面的id是加密方式,
* id可以是bcrypt、sha256等,后面跟着的是加密后的密码
*
* 如果不这么写就会出现There is no PasswordEncoder mapped for the id “null”错误
*
* 在inMemoryAuthentication()后面多了".passwordEncoder(new BCryptPasswordEncoder())",
* 这相当于登陆时用BCrypt加密方式对用户密码进行处理。
*
* 以前的".password("123456")" 变成了
* ".password(new BCryptPasswordEncoder().encode("123456"))"
* ,这相当于对内存中的密码进行Bcrypt编码加密。
*/
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhs")
.password(new BCryptPasswordEncoder().encode("123"))
.roles("VIP1","VIP2")
.and()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("lisi")
.password(new BCryptPasswordEncoder().encode("123"))
.roles("VIP1","VIP3")
.and()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("wangwu")
.password(new BCryptPasswordEncoder().encode("123"))
.roles("VIP2","VIP3");
}
```
4. 在thymeleaf中使用sec标签
```
sec:authorize="isAuthenticated()"
sec:authentication="name" 获得当前用户的用户名
sec:authorize=“hasRole(‘ADMIN’)” 当前用户必须拥有ADMIN权限时才会显示标签内容
```