ラベル JSONBin の投稿を表示しています。 すべての投稿を表示
ラベル JSONBin の投稿を表示しています。 すべての投稿を表示

2024年1月31日水曜日

OpenID Providerを作る)ユーザ情報をデータベースから取得する

こんにちは、富士榮です。

まだまだ実装すべき点はたくさんありますが、そろそろユーザを固定で埋め込むのではなくデータベースに保存されたユーザ情報を元にIDトークンなどを生成していきたいと思います。

ただデータベースと言っても、前回紹介したJSONBin.ioを使います。


その前にこれまでのおさらいです。


実装する内容

ユーザ情報を取得する、と言ってもまだユーザ認証画面などを作るところまでは手を出しませんので、これまで固定で埋め込んでいたユーザ情報を止めるところからです。

とりあえずはユーザのログインID(preferred_username)を指定するとJSONBinからユーザ情報を取得してくる仕組みを作り、ハードコード部分を少しだけ減らしていきたいと思います。

今回使うJSONBinのAPIは以下の2つです。

    • コレクションに入っているBinの一覧を取得するAPI
    • 最初の10個のBinを取得してくるので、本来は必要に応じてページングをしなければなりませんが、今回は10ユーザも作らないのでページングの考慮はしません
    • APIの仕様としては「https://api.jsonbin.io/v3/c/{コレクションID]/bins」をGETするだけです
    • 結果、Binの一覧がこんな感じで返却されますので、この中でsnippetMeta.nameがpreferred_usernameと一致している要素のrecordの値を持つbinの中にお目当てのユーザの情報が入っている、という仕掛けです。※このsnippetMeta.nameにユーザ名を入れるためにbinを作る際のname指定をしていたわけです

[
{
"private": true,
"snippetMeta": {
"name": "test2@example.jp"
},
"record": "65b4dfcfdc746540189c4daf",
"createdAt": "2024-01-27T10:49:51.572Z"
},
{
"private": true,
"snippetMeta": {
"name": "test@example.jp"
},
"record": "65b4dacd266cfc3fde81ca50",
"createdAt": "2024-01-27T10:28:29.692Z"
}
]
  • Read a Bin
    • 単体のBinの中身を読み取るAPI
    • 仕様としては「https://api.jsonbin.io/v3/b/{BinのID}」をGETするだけです
    • 結果、指定したBinの中身がこんな感じで返却されてきます
{
"record": {
"sub": "test",
"name": "taro test",
"given_name": "taro",
"family_name": "test",
"middle_name": "",
"nickname": "",
"preferred_username": "test@example.jp",
"profile": "https://twitter.com/phr_eidentity",
"picture": "https://1.gravatar.com/avatar/25eee85430bd0bbdcb9cff75655afa43cc9f69bc8730aec852d8538179646ef1",
"website": "hhtps://idmlab.eidentity.jp",
"gender": "male",
"birthdate": "1900-01-01",
"zoneinfo": "Japan",
"locale": "jp_JP",
"updated_at": 1704034800,
"email": "test@example.jp",
"email_verified": true,
"address": {
"formatted": "Kokyogaien, Chiyoda-ku, Tokyo 1000002 JAPAN",
"street_address": "Kokyogaien",
"locality": "Chiyoda-ku",
"region": "Tokyo",
"postal_code": "1000002",
"country": "JP"
},
"phone_number": "+81-3-1234-5678",
"phone_number_verified": true
},
"metadata": {
"id": "65b4dacd266cfc3fde81ca50",
"private": true,
"createdAt": "2024-01-27T10:28:29.692Z",
"collectionId": "65b474351f5677401f2691de",
"name": "test@example.jp"
}
}

これを上手く組み合わせて実装していきましょう。

ユーザ情報を取得する関数を定義する

utils/user.jsを前回までの実装でも用意していましたが、ここに一つ新しい関数を追加してみます。まず必要な引数はユーザ名です。これは最終的には利用者が画面で入力したユーザIDを利用することなりますが今回は呼び出し側でログインユーザ名だけはハードコードします。
また、これは前回までのコードにも書いていますがIDトークン等にどこまで情報を載せるか、についてスコープを使って制御するため、もう一つの引数はスコープとなります。

こんな関数になります。
exports.getUserIdentityByLoginId = async function(login_id, scopes) {

まずは、JSONBinを実行するための準備です。
今回はX-Master-Keyにマスターキーをセットします。環境変数などへ仕込んでおくことができます。ちなみにJSONBinではマスターキーとアクセスキーの2種類のキーを発行・管理しています。マスターキーは名前の通りなんでもできるマスターキーなので本来は用途によって権限を絞り込むことができるアクセスキーを使うべきなのかもしれません。
// JSONBin用のヘッダ
const headers = new Headers({
"X-Master-Key": process.env.JSONBIN_MASTER_KEY,
"Content-Type": "application/json"
});

いよいよJSONBinのFetch Binsを使ってbinの一覧を取得していきます。
// JSONBinのユーザCollectionからユーザbinのidを取得する
const collectionUrl = new URL(`${process.env.JSONBIN_BASEURL}/c/${process.env.JSONBIN_USERCOLLECTION_ID}/bins`);
const collectionResponse = await fetch(collectionUrl, {
headers: headers
});
const userCollection = await collectionResponse.json();

先ほどのsnippetMeta.nameが関数の引数に指定したlogin_idと一致しているものを抽出します。該当がなければエラーなのでコンソールにメッセージを出しておきます。この辺りはエラーハンドリングやページングの考慮もそのうち必要になりますが今回はスキップしておきます。
const userBin = userCollection.find(i => i.snippetMeta.name === login_id);
if(typeof userBin === "undefined"){
console.log("user not found");
}else{

ここまでで取得できた当該ユーザのBinのID(record)をベースに実際のBinの中身を取得し、userIdentityというオブジェクトにセットしておきます。一応ここまでで前回までハードコードしていたユーザの属性情報をJSONBinから取得できた状態になりました。
// 当該ユーザのBin idからBinの中身を読み出す
const userBinUrl = new URL(`${process.env.JSONBIN_BASEURL}/b/${userBin.record}`);
const userBinResponse = await fetch(userBinUrl, {
headers: headers
});
const userJson = await userBinResponse.json();
const userIdentity = userJson.record;

なお、PPIDへの対応をするためにlocal_identifierをユーザのオブジェクトに指定しておきたいので、subの値を一旦local_identifierの値に待避しておきます。
// subをlocal_identifierへセット
userIdentity.local_identifier = userIdentity.sub;

あとは、前回のスコープに応じた処理を行うという意味で全く同じコードとなります。
// スコープによって返却する属性の絞り込み
if(!scopes.includes("profile")){
delete userIdentity.name;
delete userIdentity.given_name;
delete userIdentity.family_name;
delete userIdentity.middle_name;


ユーザ情報を取得する関数を呼び出す

もともと認可エンドポイントでユーザ情報を固定で呼び出す処理を書いていたので当該部分を書き換えます。
oauth2/oauth2.js
// scopeに応じたユーザの情報を取得する
// let payload = userIdentity.getUserIdentity(scopes);
// ユーザ名を指定して属性情報を取得する
let payload = await userIdentity.getUserIdentityByLoginId("test@example.jp", scopes);

こんな感じです。元のユーザ情報をハードコードしていた関数をコールする部分をコメントアウトして、今回新しく作った関数にログインIDを指定して呼び出すように変更しています。

これで完了です。

JSONBinに入ったユーザ情報がちゃんと取れました。

ということで今回はここまでです。

2024年1月29日月曜日

JSONbin.ioを使ってユーザデータベースを作ってみる

こんにちは、富士榮です。

ちょっと前にXで局所的に話題になっていたJSONに特化したストレージサービス「JSONBin.io」が気になったので触ってみています。


何ができるサービスなのか?

トップページにも記載があるとおり、ざっくりいうと「JSONデータをクラウドに保存してREST APIで操作できるようにしたシンプルなストレージサービス」というところです。

JSONBin.io provides a simple REST interface to store & retrieve your JSON data from the cloud. It helps developers focus more on app development by taking care of their Database Infrastructure.
APIを見ると、以下のようなことができるようです。
  • JSONデータ(bin)の管理(作成・更新・読み取り・削除)
    • このサービスではbinという単位でJSONデータを読んでいます
  • コレクションの管理(作成・更新・読み取り)
    • なぜか削除がないです
    • コレクションの配下にbinを入れることでカテゴライズして管理することができます
    • また、スキーマ定義を紐づけることでbinに入れるデータのValidationもできます
  • スキーマの管理(作成・更新・読み取り・削除)
    • コレクションに紐づけるスキーマ定義です。
    • binを作成・更新する際にValidationをするために利用します

利用プラン

結構おもしろい考え方で運営されています。現状FreeとProの2つしかプランはありませんが、大きな違いはbinのバージョン管理やスキーマ定義の利用がProしか使えない、という以外はAPIコール数や容量が違うように見えます。
ここまでだと普通のクラウドサービスっぽいなぁ、と思いますがリクエスト数の考え方と課金の単位が結構面白いです。
実はFreeプランのリクエスト数に「10,000」とあるのは「Freeプランは上限(月額ではなく)として10,000リクエストまで実行可能ですよ」という意味です。つまり10,000リクエストを超えてこのサービスを利用しようとするとPro($20)にアップグレードするか、Additional Request($15)を購入する必要があります。
このProもAdditional Requestも月額ではなくリクエスト数を使い果たすまでは払いきりで使えますよ、という課金形態です。

ですので、例えばスキーマ定義は必要ないけど10,000を超えたリクエストを処理したい、という場合はFree + Additional Requests(500,000リクエスト)を購入となるので$15、スキーマ定義を使いたいが500,000リクエストはいらない、という人はFree + Pro(100,000リクエストまで) を購入するので$20、という形になります。
※どちらの場合は一旦はFreeプランについてくる10,000リクエストに加えて各プランのリクエスト数を追加することになりますので、例えばProを契約すると110,000リクエスト使えることになります。

OpenID Connect coreの標準クレームをサポートするユーザDBを作る

標準クレームをサポートする、となるとスキーマ定義をしてValidationをかけたくなるのでProを契約する必要があります。支払いはカードやPayPalでできます。私はPayPalを使いました。

以下の順番で定義をしていきます。
  1. スキーマ定義
  2. コレクションの作成とスキーマ定義の紐付け
  3. binの作成(実際のユーザデータ)
まずはスキーマ定義です。
OpenID Connectの標準スキーマはこちらに定義されているのでこれをベースに定義ファイルを作成します。
こんな感じのデータを作りました。
{
"description": "OpenID Connect core 1.0 standard claims",
"type": "object",
"properties": {
"sub": {
"description": "Subject - Identifier for the End-User at the Issuer.",
"type": "string"
},
"name": {
"description": "End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.",
"type": "string"
},
"given_name": {
"description": "Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.",
"type": "string"
},
"family_name": {
"description": "Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.",
"type": "string"
},
"middle_name": {
"description": "Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.",
"type": "string"
},
"nickname": {
"description": "Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.",
"type": "string"
},
"preferred_username": {
"description": "Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.",
"type": "string"
},
"profile": {
"description": "URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.",
"type": "string"
},
"picture": {
"description": "URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.",
"type": "string"
},
"website": {
"description": "URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.",
"type": "string"
},
"email": {
"description": "End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.",
"type": "string"
},
"email_verified": {
"description": "True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.",
"type": "boolean"
},
"gender": {
"description": "End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.",
"type": "string"
},
"birthdate": {
"description": "End-User's birthday, represented as an ISO 8601-1 [ISO8601-1] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.",
"type": "string"
},
"zoneinfo": {
"description": "String from IANA Time Zone Database [IANA.time-zones] representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.",
"type": "string"
},
"locale": {
"description": "End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639 Alpha-2 [ISO639] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.",
"type": "string"
},
"phone_number": {
"description": "End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.",
"type": "string"
},
"phone_number_verified": {
"description": "True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.",
"type": "boolean"
},
"address": {
"description": "End-User's preferred postal address. The value of the address member is a JSON [RFC8259] structure containing some or all of the members defined in Section 5.1.1.",
"type": "object"
},
"updated_at": {
"description": "Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T00:00:00Z as measured in UTC until the date/time.",
"type": "number"
}
},
"required": ["sub"]
}

API経由でスキーマ定義(Schema Doc)を作成しても良いですし、管理ポータルから作成することもできます。


次はコレクションの作成です。
作成する際にスキーマの関連付けができるので上記で作成したスキーマ定義を紐づけておきます。

これで準備は完了です。
では実際のユーザデータをbinとして作成します。
気をつけるべき点としてはカテゴリとして先ほど作成したコレクションを指定することくらいです。あとはbinに名前をつけておくと一覧を見るときに便利なのでユーザのpreferred_usernameの値などをNameに指定しておくと良いです。(これは理由があるので今後解説します)


これで利用者の情報がJSONデータとしてサービスに登録できました。
BIN IDが生成されるので、Postmanなどで実際にAPI経由で情報を参照してみます。
なお、認証のためヘッダにX-Master-Key(もしくはX-Access-Key)をつけてダッシュボードから確認できるキーの値をセットする必要があります。


OpenID Providerを作る上で簡易的なユーザDBとしては結構便利な気がしてきましたので、次回以降で組み込んでみたいと思います。