Skip to content

Instantly share code, notes, and snippets.

@sunny4381
Last active February 13, 2023 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny4381/f0558285665cc3dcc8e68aca2a93244a to your computer and use it in GitHub Desktop.
Save sunny4381/f0558285665cc3dcc8e68aca2a93244a to your computer and use it in GitHub Desktop.
# SHIRASAGI OAuth 2.0 IdP 機能を利用したサンプルコード
# このサンプルでは authorization code flow を用います。
#
# 実行方法
# bin/rails runner oauth2_sample_with_authorization_code_flow.rb
# ドメイン
your_domain = "https://localhost:3551/"
# 認可エンドポイントの URL
authorize_url = URI.join(your_domain, "/.mypage/login/oauth2/authorize")
# トークンエンドポイントの URL
token_url = URI.join(your_domain, "/.mypage/login/oauth2/token")
# SHIRASAGI 管理画面で作成したアプリケーションのクライアントID
client_id = ENV.fetch('CLIENT_ID', 'Jfp4HnWFH7Clemq6v09wwiSj')
# SHIRASAGI 管理画面で作成したアプリケーションのクライアントシークレット
client_secret = ENV.fetch('CLIENT_SECRET', 'XHi8seR8dZ_qaplFlrkb3JOcCUXQ4QmREckoUYETCUnDvQzf')
# SHIRASAGI 管理画面で作成したアプリケーションを作成する際に登録したリダイレクト URL
redirect_uri = ENV.fetch('REDIRECT_URI', 'http://127.0.0.1/cb')
# SHIRASAGI 管理画面で作成したアプリケーションを作成する際に選択した権限
scopes = []
authorize_request = {
response_type: "code",
client_id: client_id,
redirect_uri: redirect_uri,
scope: scopes.join(" ")
}
# コンソールに表示される URL にブラウザでアクセスする
puts "#{authorize_url}?#{authorize_request.to_query}"
# コンソールに表示される URL にブラウザでアクセスすると、シラサギ側のログイン画面が表示される。
# そして、ログインに成功すると redirect_uri に戻ってくる。
# redirect_uri には code というパラメータが含まれているので、記録する
authorize_code = $stdin.readline
authorize_code.strip!
token_resp = Faraday.new(url: token_url).post do |req|
req.headers['Authorization'] = "Basic #{Base64.strict_encode64([ client_id, client_secret ].join(":"))}"
req.params['grant_type'] = 'authorization_code'
req.params['code'] = authorize_code
req.params['redirect_uri'] = redirect_uri
end
access_token = JSON.parse(token_resp.body).then { |json| json["access_token"] }
puts "access_token=#{access_token}"
# 取得したアクセストークンを用いてユーザーアカウント情報を取得する
account_resp = Faraday.new(url: URI.join(your_domain, "/.u/user_account.json")).get do |req|
req.headers['Authorization'] = "Bearer #{access_token}"
end
account_json = JSON.parse(account_resp.body)
puts "email=#{account_json['email']}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment