一: 创建工程
1.导入依赖
使用 springboot 版本 2.2.6.RELEASE ,创建工程:https://start.spring.io/
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
新增一个接口服务 /hello
@RestControllerpublic class HelloController {@RequestMapping("/hello")public String hello(){return "hello shf";}}
启动服务,访问 http://localhost:8080/hello
4. 默认跳转到 localhost:8080/login,因为当Spring项目中引入了Spring Security依赖的时候,项目会默认开启如下配置
security:basic:enabled: true
这个配置开启了一个HTTP basic类型的认证,所有服务的访问都必须先过这个认证,默认的用户名为user,密码由Sping Security自动生成,控制台有打印日志。输入用户名密码访问到 hello接口.
二: 开启基于表单认证
1.通过配置将HTTP Basic认证修改为基于表单的认证方式。
创建自定义配置类 MySecurityConfig.
继承 org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
实现 configure(HttpSecurity http) 方法。进行配置。
@Overrideprotected void configure(HttpSecurity http) throws Exception {// httpBasic 认证方式// http.httpBasic()// 表单方式登录http.formLogin().and()// 授权配置.authorizeRequests()// 所有请求.anyRequest()// 都需要认证.authenticated();}
三: 基本原理
上面我们开启了一个最简单的Spring Security安全配置,下面我们来了解下Spring Security的基本原理。通过上面的的配置,代码的执行过程可以简化为下图表示:
如上图所示,Spring Security包含了众多的过滤器,这些过滤器形成了一条链,所有请求都必须通过这些过滤器后才能成功访问到资源。其中UsernamePasswordAuthenticationFilter过滤器用于处理基于表单方式的登录认证,而BasicAuthenticationFilter用于处理基于HTTP Basic方式的登录验证,后面还可能包含一系列别的过滤器(可以通过相应配置开启)。在过滤器链的末尾是一个名为FilterSecurityInterceptor的拦截器,用于判断当前请求身份认证是否成功,是否有相应的权限,当身份认证失败或者权限不足的时候便会抛出相应的异常。ExceptionTranslateFilter捕获并处理,所以我们在ExceptionTranslateFilter过滤器用于处理了FilterSecurityInterceptor抛出的异常并进行处理,比如需要身份认证时将请求重定向到相应的认证页面,当认证失败或者权限不足时返回相应的提示信息。
源码:未登录时,直接请求资源,被拦截。
抛出异常,catch 重定向到 login 页面。登录,进入 UsernamePasswordAuthenticationFilter 过滤器。(配置)
验证成功跳转到资源API。
