在我们开发web应用时,很重要的一环也慢慢的浮现出来,他就是我们今天的主角 security
;
什么是 security
,它能干什么?
官方给出的解释为:
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的事实上的标准。
Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。像所有Spring项目一样,Spring Security的真正强大之处在于它可以轻松扩展以满足定制需求的能力。
在这里编者还是建议想有更多了解的小伙伴去查看官方文档
闲话不多说,开始编写代码
1、创建 maven 工程
相信能来翻我的你,对这个应该是不在话下的
下面直接附上的我的 pom.xml
文件,导入所需要的依赖
// 划重点,这个只是 pom.xml 主要的部分,并不完整
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
修改 application.yml
文件
这里只需要添加 server-port 和 mysql 所需的 datasource 即可
2、创建 config/SecurityConfig.java 文件
这里我们要自己去配置用户及密码,因此 SecurityConfig
类要继承WebSecurityConfigurerAdapter
类,
当然也忘了加上 @Configuration
注解和 @EnableWebSecurity
注解,
这里 @Configuration @EnableWebSecurity 两个注解还不明白的同学请自行百度
3、重写 configure
方法,注意参数
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
// 指定密码加密方式
.passwordEncoder(passwordEncoder())
.withUser("jamie")
.password(passwordEncoder().encode("min"))
.authorities("user")
.and()
.withUser("min")
.password(passwordEncoder().encode("123"))
.authorities("admin");
}
// 配置加密方式
private PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
以上分别将两个账户存放到内存当中了,启动项目登录即可
admin角色:min—123
user角色: jamie—min
很显然这照片那个方法是最快的,但是在实际项目当中是不可取的,因为每当用户更变时都需要修改源代码,及其不方便
下期在分享自定义用户存储及安全规则
源码地址 戳这里