1、引入spring security
spring boot环境下,pom.xml需要加入spring security相关依赖即可启动spring security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
此时spring security使用默认配置,使用spring security默认登录页
此时默认用户名为:user,密码则输出来在启动时的命令行中
2、三种用户配置的方式
2.1、配置文件配置用户
在spring boot配置文件application.yml中配置:
spring
即可使用自定义用户登录,其中name为用户名,password为密码,roles为角色名,多个角色名用英文字符:,分割
2.2、使用将用户列表写入内存方式登录
此方法需要重新编写一个类,继承org.springframework.security.config.annotation.web.configuration中的WebSecurityConfigurerAdapter,并重写configure(AuthenticationManagerBuilder auth)方法
上面代码定义了用户名为:admin,密码为:123,角色为admin 和 用户名为:user,密码为:123,角色为:vip和user的两个用户
此方法会在程序开始运行时就将用户列表写入内存,如需连接数据库,可以将所有用户查询出来后都写入内存,不过用户多的话这种方式比较耗内存,不推荐使用
@Autowired
private UsersService usersService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
List<Users> listUser = usersService.findAll();
for (Users users : listUser) {
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser(users.getAccountName()).password(new BCryptPasswordEncoder().encode(users.getPassword())).roles("admin","vip");
}
}
这里因为测试没有关联出来角色权限,所以统一给admin和vip角色,可以也从数据库中查出来赋值角色,如赋值权限,可以用.authorities代替roles
2.3、使用AuthenticationManagerBuilder自带数据库方法登录
此方法使用sql直接查找数据库中的账号密码权限,如果不设置sql语句,默认查找账号语句是select username,password,enabled from users where username = ?,查找权限语句是select username,authority from authorities where username = ?,如果数据库结构不一致,就需要自己设置sql语句。由于sql的入参只有username,一般会比较麻烦。同时数据库中密码字段需要保存已加密数据。
2.4、使用实现UserDetailService接口方法设置用户
此方法需实现org.springframework.security.core.userdetails.UserDetailsService并重写loadUserByUsername方法,此方法需要返回一个org.springframework.security.core.userdetails.UserDetails,此处返回的org.springframework.security.core.userdetails.User类是UserDetails的实现类。此方法会在每次用户登录的时候传入username并一定程度上自定义登录逻辑。此方法仍需重写WebSecurityConfigurerAdapter的configure(AuthenticationManagerBuilder auth)方法。
3、登录配置
重写WebSecurityConfigurerAdapter的configure(HttpSecurity http)方法,根据自己的需求配置好,这里只是基础配置。