问题
做oauth2授权登录,遇到了invalid_grant
问题,流程跟之前几次一样,却出错了,查下来发现是omniauth-oauth2
的一次merge导致了很多oauth2的gem都出了同样的问题
相关链接:
- https://github.com/omniauth/omniauth-oauth2/issues/93
- https://github.com/omniauth/omniauth-oauth2/commit/26152673224aca5c3e918bcc83075dbb0659717f
相关的gem
omniauth & oauth2 & omniauth-oauth2 关系
omniauth
: 帮我们构建了一个授权登录模板的Rack middleware.oauth2
: 实现了OAuth 2.0协议omniauth-oauth2
: 用omniauth
提供的模板,结合oauth2
,实现了完整的OAuth 2.0授权流程
整个过程
omniauth原理:检查请求路径,匹配授权路径,进行相应的处理
相关代码(omniauth/lib/omniauth/strategy.rb):
1 | def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity |
1、监听/auth/skylark
(发起授权的路径)请求
1 | return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym) |
request_call
不会去调用下一个Middleware(@app.call(env)
),意味着该请求不会流向Rails Application.request_call
真正实现在omniauth-oauth2
,相关代码(omniauth-oauth2/lib/omniauth/strategies/oauth2.rb):
1 | def request_phase |
以上代码会跳转授权链接(http://oauth-server.com//oauth/authorize?params....
)
2、监听oauth-service的callback/auth/skylark/callback
请求
1 | return callback_call if on_callback_path? |
向oauth-server请求access_token
相关代码(omniauth-oauth2/lib/omniauth/strategies/oauth2.rb):
1 | def callback_phase # rubocop:disable AbcSize, CyclomaticComplexity, MethodLength, PerceivedComplexity |
omniauth会把相关信息写入request.env,调用下一个Rack Middleware,然后Rails Application就会接受到/auth/skylark/callback
的请求
相关代码:
1 | def callback_phase |
auth_hash会去设置info,
1 | hash.info = info unless skip_info? |
info获取具体的user信息,而info的具体实现在继承OmniAuth::Strategies::OAuth2
的类中实现
1 | info do |