Oauth2.0

Oauth2.0 验证流程简单介绍(使用doorkeeper)

Oauth 2.0

  1. client 获取 provider 提供的资源

  2. 流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
+----------+
| Resource |
|   Owner  |
|          |
+----------+
     ^
     |
    (B)
+----|-----+          Client Identifier      +---------------+
|         -+----(A)-- & Redirection URI ---->|               |
|  User-   |                                 | Authorization |
|  Agent  -+----(B)-- User authenticates --->|     Server    |
|          |                                 |               |
|         -+----(C)-- Authorization Code ---<|               |
+-|----|---+                                 +---------------+
  |    |                                         ^      v
 (A)  (C)                                        |      |
  |    |                                         |      |
  ^    v                                         |      |
+---------+                                      |      |
|         |>---(D)-- Authorization Code ---------'      |
|  Client |          & Redirection URI                  |
|         |                                             |
|         |<---(E)----- Access Token -------------------'
+---------+       ( Optional Refresh Token)

A)用户访问客户端,后者将前者导向认证服务器。 B)用户选择是否给予客户端授权。 C)假设用户给予授权,认证服务器将用户导向客户端事先指定的"重定向URI"(redirection URI),同时附上一个授权码。 D)客户端收到授权码,附上早先的"重定向URI",向认证服务器申请令牌。这一步是在客户端的后台的服务器上完成的,对用户不可见。 E)认证服务器核对了授权码和重定向URI,确认无误后,向客户端发送访问令牌(access token)和更新令牌(refresh token)。

  1. Resource Owner -> devise
  2. API -> Grape
  3. Provider -> doorkeeper
1
2
3
4
  doorkeeper_for :all                 # Require access token for all actions
  doorkeeper_for :all, except: :index # All actions except index
  doorkeeper_for :index, :show        # Only for index and show action
  doorkeeper_for :create, :scopes => [:write] #Only for create action and writable
  1. client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module OmniAuth
  module Strategies
    class Doorkeeper < OmniAuth::Strategies::OAuth2
      option :name, :doorkeeper
      option :client_options, {
        :site => "http://localhost:8090/",
        :authorize_path => "/oauth/authorize"
      }
      uid do
        raw_info["id"]
      end
      info do
        {
          :email => raw_info["email"]
        }
      end
      def raw_info
        @raw_info ||= access_token.get('/api/v1/me.json').parsed
      end
    end
  end
end

生成client和access_token

1
2
3
4
5
6
7
8
9
  # get or create an client with OAuth2
  def doorkeeper_oauth_client
    @client ||= OAuth2::Client.new(DOORKEEPER_APP_ID, DOORKEEPER_APP_SECRET, :site => DOORKEEPER_APP_URL)
  end

  # get or create an AccessToken
  def doorkeeper_access_token
    @token ||= OAuth2::AccessToken.new(doorkeeper_oauth_client, current_user.doorkeeper_access_token) if current_user
  end

通过access_token来获取api数据

1
2
3
  def index
    @order = doorkeeper_access_token.get("/api/v1/orders").parsed
  end

Comments