SpringBoot使用Security
Spring Security是一款基于Spring的安全框架,主要包含认证和授权两大安全模块,和另外一款流行的安全框架Apache Shiro相比,它拥有更为强大的功能。Spring Security也可以轻松的自定义扩展以满足各种需求,并且对常见的Web安全攻击提供了防护支持。如果你的Web框架选择的是Spring,那么在安全方面Spring Security会是一个不错的选择。
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
创建控制器
@RestController
public class TestController {
@GetMapping("hello")
public String hello() {
return "hello spring security";
}
}
这时候我们直接启动项目,访问http://localhost:8080/hello,默认的用户名为user
,密码由Sping Security自动生成,回到IDE的控制台,可以找到密码信息:
输入用户名和密码之后,就可以访问定义的hello接口了!
表单验证
创建一个配置类BrowserSecurityConfig
继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
这个抽象类并重写configure(HttpSecurity http)
方法。WebSecurityConfigurerAdapter
是由Spring Security提供的Web应用安全配置的适配器:
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单方式
.and()
.authorizeRequests() // 授权配置
.anyRequest() // 所有请求
.authenticated(); // 都需要认证
}
}
以上是基于SpringSecurity的基本入门配置!