LoginSignup
21
22

More than 5 years have passed since last update.

rubyのoauth2(gem)について

Last updated at Posted at 2016-10-03

gemのoauth2を使う機会があったので、ざっとみてみたメモ。

oauth2
https://github.com/intridea/oauth2

サンプルコード
require 'oauth2'

client = OAuth2::Client.new('client_id', 'client_secret', :site => 'https://example.org')

client.auth_code.authorize_url(:redirect_uri => 'http://localhost:8080/oauth2/callback')

token = client.auth_code.get_token('authorization_code_value', :redirect_uri => 'http://localhost:8080/oauth2/callback', :headers => {'Authorization' => 'Basic some_password'})

response = token.get('/api/resource', :params => { 'query_foo' => 'bar' })


どうなってるのかgemの中を除いてみる

client = OAuth2::Client.new('client_id', 'client_secret', :site => 'https://example.org')

client_id、client_secret、apiのurlをセット
:siteは指定せずに、「:authorize_url」「:token_url」の指定でもOKっぽい

client.auth_code.authorize_url(:redirect_uri => 'http://localhost:8080/oauth2/callback')

auth_code.rb
      def authorize_url(params = {})
        @client.authorize_url(authorize_params.merge(params))
      end

      def authorize_params(params = {})
        params.merge('response_type' => 'code', 'client_id' => @client.id)
      end
client.rb
    def authorize_url(params = nil)
      connection.build_url(options[:authorize_url], params).to_s
    end

以下をつなげているだけ
* options[:authorize_url]:「:site」に/oauth/authorizeを足したもの
* response_type
* client_id
* 渡した引数

  1. 生成したurlにredirectさせると、各プロバイダ(yahooとか)の認証画面に遷移する
  2. 認証OKになると指定したredirect_urlにリダイレクト。codeも付与される


token = client.auth_code.get_token('authorization_code_value', :redirect_uri => 'http://localhost:8080/oauth2/callback', :headers => {'Authorization' => 'Basic some_password'})

auth_code.rb
      def get_token(code, params = {}, opts = {})
        params = {'grant_type' => 'authorization_code', 'code' => code}.merge(client_params).merge(params)
        @client.get_token(params, opts)
      end

以下をmergeしてる
* clint_params:client_idとclient_secretの配列
* grant_type
* code:redirect時に帰ってきた値を指定(認証がcodeの場合)

client.rb
    def get_token(params, access_token_opts = {}, access_token_class = AccessToken) # rubocop:disable Metrics/AbcSize
      opts = {:raise_errors => options[:raise_errors], :parse => params.delete(:parse)}
      if options[:token_method] == :post
        headers = params.delete(:headers)
        opts[:body] = params
        opts[:headers] = {'Content-Type' => 'application/x-www-form-urlencoded'}
        opts[:headers].merge!(headers) if headers
      else
        opts[:params] = params
      end
      response = request(options[:token_method], token_url, opts)
      error = Error.new(response)
      raise(error) if options[:raise_errors] && !(response.parsed.is_a?(Hash) && response.parsed['access_token'])
      access_token_class.from_hash(self, response.parsed.merge(access_token_opts))
    end

postの場合、:headersの指定があれば、設定してrequestなげる
access_tokenを取得する

response = token.get('/api/resource', :params => { 'query_foo' => 'bar' })

access_token.rb
    def get(path, opts = {}, &block)
      request(:get, path, opts, &block)
    end
    def request(verb, path, opts = {}, &block)
      self.token = opts
      @client.request(verb, path, opts, &block)
    end

第1引数:使用するapiのpath
第2引数:apiを使用する際に使用するパラメータ(あれば)

responseにプロバイダから取得した情報が格納される。

関連記事

rubyのoauth2(gem)について2_google認証やってみる


21
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
22