1.导入pom依赖
<!--security起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.创建SecurityConfig类
创建SecurityConfig类 继承 WebSecurityConfigurerAdapter 类并加上 @EnableWebSecurity 注解
package com.lyx.config;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
@EnableWebSecurity 的用处
1.加载了WebSecurityConfiguration配置类, 配置安全认证策略。
2: 加载了AuthenticationConfiguration, 配置了认证信息
3.重写WebSecurityConfigurerAdapter
重写WebSecurityConfigurerAdapter 类的
configure(HttpSecurity http)
configure(AuthenticationManagerBuilder auth) 方法
configure()是一个重载方法
@Override
protected void configure(HttpSecurity http) throws Exception {
//授权规则
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//认证规则
}
4.在 configure(HttpSecurity http)方法中定制自己的规则
使用链式编程
authorizeRequests() 认证请求
formLogin() 登录窗口 没有权限会默认到窗口 (自带一个login页面)
antMatchers(String... antPatterns ) 添加一个地址
and() 拼接下一个
permitAll() 准许所有访问
hasRole(String role) 指定哪些角色可以访问
loginPage(String loginPage) 指定登录窗口地址
例子1 . 所有人都可以访问 "/" 下的网页
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
}
例子2. 如果访问/level1下的地址角色必须是vip1 如果访问/level2下的地址角色必须是vip2
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
;
}
例子3.没有权限地址返回/toLogin
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/toLogin");
}
5.在 configure(AuthenticationManagerBuilder auth)方法中定制自己的规则
inMemoryAuthentication() 内存认证
jdbcAuthentication() jdbc认证
withUser(String username) 认证的用户名
password(String password) 认证的密码
roles(String... roles) 认证的角色
passwordEncoder(PasswordEncoder passwordEncoder) 设置编码 格式
示例
/**
* springboot 2.1.x 可以直接使用
* 新版本 会报 密码编码:passwordEncoder 错误
* 在 springboot 5+ 新增了很多加密方式
* 认证
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().
passwordEncoder(new BCryptPasswordEncoder())
.withUser("lyx")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip1","vip2","vip3")
.and()
.withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip1","vip2")
.and()
.withUser("user")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip1")
;
}
6.