认证功能实现(spring-oauth2)
2020-11-25 本文已影响0人
do_young
前言
前面讲述了一下spring security对认证的实现,该实现的使用场景主要是用户本人认证。
有一种场景是用户将授权给第三方应用,访问本人在该应用的资源。
站在应用的角度出发,就是经得用户授权以后,对第三方应用认证,获取访问用户资源的权限。
oauth2协议
oauth2就是一种用户对第三方应用授权,获取用户在本应用资源访问权限的协议标准。
该协议中针对第三方应用有四种认证方式。
-
授权码模式
用户认证以后,用户授权客户端访问系统资源。
客户端获取到系统授权码,换取令牌,完成客户端认证。 -
简化模式
用户认证以后,用户授权客户端访问系统资源。
客户端获取到令牌,完成客户端认证。 -
密码模式
客户端将用户提供的发给系统,完成客户端认证。 -
客户端模式
客户端提供appid及secret,完成客户端认证。
相关认证的类型选择流程如下所示:

Spring oauth2源码分析
关于Spring对oauth2的实现框架图如下所示:

其中:
- client为第三方应用
- Authorization Server为本应用的认证授权服务
- ResourceServer为本应用的资源服务
所以认证的主要逻辑都在认证授权服务上(AuthorizationServer)。
其中:
-
AuthorizationEndpoint 是一个/oauth2/authorization接口,主要是用于实现已经认证的用户通过界面确认,将相关权限授权给第三方应用的实现,其中会生成一个随机code码,并将该code码用于第三方应用发起code类型认证。
-
TokenEndPoint是一个/oauth2/token接口,主要是实现oauth2默认的4种认证方式。
image.png
-
AuthorizationServiceTokenServices 主要实现认证服务器所需要使用到的令牌服务。
关键实现类源码分析
TokenEndPoint
@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
。。。。。。
OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
if (token == null) {
throw new UnsupportedGrantTypeException("Unsupported grant type");
}
return getResponse(token);
}
其中对不同的oauth2协议的认证协议实现,主要是通过TokenGranter接口的grant方法的实现。
TokenGranter接口及相关的实现类的关系图所下所示:

AuthorizationServiceTokenServices
