Spring Security 是什么?
Spring Security是一个提供身份验证、授权和针对常见攻击的保护的框架。
创建 Spring Security项目
首先创建Maven项目,用于引入Spring Security依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringSecurityDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
</project>
在上面的pom中,我们引入了Spring web依赖和Security依赖,并且作为spring的子项目。
不知道有没有注意到一个细节,我的pom中security依赖并没有指定版本号就可以引入。
这是因为我们使用soring-boot-starter作为父项目,内部就已经事先指定了security的版本号了。
启动测试
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Security";
}
}
在启动后,控制台会生成password
我们去访问刚写好的服务接口/hello
,会自动拦截跳转到登录界面
账号名是user
,密码就是控制台生成的密码,登录即可,登陆成功后,我们再次访问/hello服务接口,就被授权了。
配置账户密码
一、application.properties配置
可以通过application.properties去配置自定义的账户和密码
server.port=2003
spring.security.user.name=wyh
spring.security.user.password=123456
在启动后,后台不会再为我们生成密码。
同样,一样的流程,通过登录,即可完成基本的授权。
二、通过Config配置
这种方式需要写一个继承WebSecurityConfigurerAdapter的配置类,并重写configure方法,这里我们与WebSecurityConfigurerAdapter先混个脸熟,以后很多配置都会经由它来配置。
/**
* @author 阳光大男孩!!!
*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
final String password = bCryptPasswordEncoder.encode("sunnyboy");
final String username = "sunnyboy";
auth.inMemoryAuthentication()
.withUser(username)
.password(password)
.roles("admin");
}
@Bean
PasswordEncoder password()
{
return new BCryptPasswordEncoder();
}
}
在上面的代码中,思路是配置用户名、密码,但这里密码需要进行加密,并且选择了Spring Security自带的BCryptPasswordEncoder来进行加密,所以向spring容器提供了这样一个Bean。
并且调用auth的inMemoryAuthentication()方法进行配置,通过名字我们不难发现,事实上就是将这对用户名、密码存储在内存中,进行认证。
三、自定义逻辑进行认证
事实上,在服务非常小非常小时,上面的两种方式可能会够,但大多数都是通过查数据库来实现认证的。
篇幅原因,将在下一篇进行自定义逻辑,使用数据库联动实现用户认证与授权。
总结
本篇博文完成了对Spring Security 实战的初步入门。