概述
解决我是谁的问题
AuthenticationManager
Spring Security中的认证工作主要由AuthenticationManager接口来负责,下面来看一下该接口的定义:
public interface AuthenticationManager {Authentication authenticate(Authentication authauthentication) throws AuthenticationException;}
AuthenticationManager只有一个authenticate方法可以用来做认证,该方法有三个不同的返回值:
· 返回Authentication,表示认证成功。
· 抛出AuthenticationException异常,表示用户输入了无效的凭证。
· 返回null,表示不能断定。
ProviderManager
AuthenticationManager最主要的实现类是ProviderManager,ProviderManager管理了众多的AuthenticationProvider实例,AuthenticationProvider有点类似于AuthenticationManager,但是它多了一个supports方法用来判断是否支持给定的Authentication类型。
public interface AuthenticationProvider {Authentication authenticate(Authentication authentication)throws AuthenticationException;boolean supports(Class<?> authentication);}
由于Authentication拥有众多不同的实现类,这些不同的实现类又由不同的AuthenticationProvider来处理,所以AuthenticationProvider会有一个supports方法,用来判断当前的Authentication Provider是否支持对应的Authentication。
在一次完整的认证流程中,可能会同时存在多个AuthenticationProvider(例如,项目同时支持form表单登录和短信验证码登录),多个AuthenticationProvider统一由ProviderManager来管理。同时,ProviderManager具有一个可选的parent,如果所有的AuthenticationProvider都认证失败,那么就会调用parent进行认证。parent相当于一个备用认证方式,即各个AuthenticationProvider都无法处理认证问题的时候,就由parent出场收拾残局。
快速入门
mvn 中需要引入Web和Spring Security依赖即可:
<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>
创建测试HelloController
@RestControllerpublic class HelloController {@GetMapping("/hello")public String hello() {return "hello spring security";}}
浏览器输入:http://localhost:8080/hello ,当用户访问/hello接口时,会自动跳转到http://localhost:8080/login  
用户名是user ,密码会在当前启动的日志中Using generated security password: 
或者修改配置applicaton.yml
spring:security:user:name: adminpassword: 654321roles: ADMINlogging:level:org:springframework:security: DEBUG
