一、起步
在SpringBoot工程中pom.xml 添加依赖(最好在idea创建SpringBoot工程的时候就把这些打勾就好了)
我这里用的版本是 5.1.6.RELEASE(注意!!!)
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
当然还有SpringBoot的一些依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、例子
把上面的依赖引入的时候security基础部分就完成了,然后我们通过一个例子来看一下效果。
- 创建一个SecurityConfig类,要继承 WebSecurityConfigurerAdapter 类进行配置
注意:password这里不能直接写密码,要把密码通过new BCryptPasswordEncoder().encode()加密
/**
* 1.@EnableWebSecurity是Spring Security用于启用Web安全的注解
*
* @author CH
* @date 2021-08-05 10:54
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("root")
.password(new BCryptPasswordEncoder().encode("root"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
}
- 创建一个控制类IndexController
/**
* @author CH
* @date 2021-08-05 10:43
*/
@RestController
public class IndexController {
@RequestMapping(value = "/")
public String test(){
return LocalDateTime.now().toString();
}
}
然后输入地址访问则会转到默认登录页面。
待完善。。。