- 创建springboot,引入以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
- 自定义配置登录用户名和密码
启动该项目后访问该项目的任意接口都会重定向到登录页面,这个登录页面是spirngSecurity集成好的,默认用户名是 user,密码是控制台自动打印的,如下:
,此时,输入用户名和密码就能访问对应接口
而自定义用户名和密码则很简单,只需要在application.properties中加入下面代码,test是我随手写的,可以随便写,改完之后重启就ok了,然后你会发现控制台就不会打印之前那段随机密码了,因为我们已经配置好了
spring.security.user.name=test
spring.security.user.password=test
,yml配置方式如下
spring:
security:
user:
name: test
password: test
3.内存用户认证与授权
接下来体验一把内存用户认证与授权,内存用户是指用户的数据存放在内存中,而非是数据库
首先,定义任意类继承WebSecurityConfigurerAdapter,而后实现configure方法
package com.fengf.spirngboot2springsecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author zyf
* @date 2020/10/6 20:47
*/
@Configuration//声明该类为配置类
@EnableWebSecurity//启用spring security
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {//密码编密,高版本必须进行,不然报错
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()//添加内存用户认证,这些账号密码存放在内存中,而非数据库
.withUser("admin")//添加用户名称
.password(passwordEncoder().encode("123456"))//添加用户密码
.roles("admin");//添加用户角色
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("123456"))
.roles("user");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//表示验证请求
.antMatchers("/admin/**").hasRole("admin")//表示访问/admin路径下的接口需要admin角色
.antMatchers("/user/**").hasAnyRole("admin","user")//表示访问/user路径下的接口,有admin和user任意一个角色就行
.anyRequest().authenticated()//表示所有请求都必要验证
.and()
.formLogin()//指定支持基于表单的身份验证
.permitAll()//一切用户访问都可
.and()
.csrf().disable();//关闭csrf攻击
}
}
4.启动项目开始测试
首先登录user用户进行权限验证
登录成功后访问/user/hello是可以的
这时再访问/admin/hello,你会发现报403错误,没有权限
,然后登录admin角色进行测试,你会发现都可
然后,http://localhost:8080/hello这个接口是没有进行角色判断的,所以登录任意用户都可
,最后,对于初学者来说有时登录成功后你会发现下面错误,那是因为你没填写接口路径,而默认的接口路径你项目里也没配置,所以才会出现这种情况
可了,下个博客写基于数据库的用户登录授权