Oauth2
oauth2采用令牌的方式让用户灵活地对第三方应用授权访问资源或者撤销权限
授权流程
- 客户端像用户请求授权
- 用户同意后服务器返回一个授权凭证
- 客户端可以拿着凭证访问授权服务器,申请令牌
- 授权服务器确认无误后,发放令牌
- 客户端可以拿着令牌访问资源服务器上的资源
- 资源服务器确认后发放资源
授权模式有四种:
- 授权码模式:最完整,最严谨,第三方登录基本使用这种模式
- 简化模式:不需要客户端参与,直接在浏览器中向授权服务器申请令牌
- 密码模式:用户直接把用户名密码告诉客户端,客户端根据这些信息申请令牌
- 客户端模式:客户端以自己的名义向授权服务器申请令牌
案例
添加依赖
- web
- redis
- springsecurity
- oauth2
第一步:配置redis服务器
# 配置redis
spring.redis.database=0
spring.redis.host=39.105.34.128
spring.redis.port=6379
spring.redis.password=123456
第二步:配置 授权服务器
继承AuthorizationServerConfigurerAdapter类,@EnableAuthorizationServer注解开启授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager; //支持password模式
@Autowired
RedisConnectionFactory redisConnectionFactory;//完成令牌在redis的缓存
@Autowired
UserDetailsService userDetailsService; //支持刷新token
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder(); //加密
}
/**
* 配置授权模式
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("passwo