Created
February 13, 2023 05:22
-
-
Save sunny4381/0e6d8bfce77f24ed8eb408eb3ff0e0cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SHIRASAGI OAuth 2.0 IdP 機能を利用したサンプルプログラム | |
# このサンプルでは jwt 拡張フローを用います。 | |
# | |
# 実行方法 | |
# bin/rails runner oauth2_sample_with_jwt_flow.rb | |
# ドメイン | |
your_domain = "https://localhost:3551/" | |
# トークンエンドポイントの URL | |
token_url = URI.join(your_domain, "/.mypage/login/oauth2/token") | |
# SHIRASAGI 管理画面で作成したアプリケーションのクライアントID | |
client_id = ENV.fetch('CLIENT_ID', 'cJ96MH2FHdYjAxlE0QUCpeJ8') | |
# SHIRASAGI 管理画面で作成したアプリケーションを作成する際に登録した公開鍵のペアになる秘密鍵 | |
key = OpenSSL::PKey::RSA.new(::File.read(Rails.root.join(",memo/private_key.pem"))) | |
# SHIRASAGI 管理画面で作成したアプリケーションを作成する際に選択した権限 | |
scopes = [] | |
# 成り済ましたいユーザーのメールアドレス | |
user_email = "user1@demo.ss-proj.org" | |
jwt_assertion = JSON::JWT.new( | |
# issuer | |
iss: client_id, | |
# subject | |
sub: user_email, | |
# scope | |
scope: scopes.join(" "), | |
# audience | |
aud: token_url, | |
# expires at | |
exp: 1.hour.from_now.to_i, | |
# issued at | |
iat: Time.zone.now.to_i | |
) | |
jwt_assertion = jwt_assertion.sign(key) | |
token_resp = Faraday.new(url: token_url).post do |req| | |
req.params['grant_type'] = "urn:ietf:params:oauth:grant-type:jwt-bearer" | |
req.params['assertion'] = jwt_assertion.to_s | |
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