13
4

More than 3 years have passed since last update.

RubyでJWTトークンを検証する

Last updated at Posted at 2020-05-21

AWS Cognitoのウェブトークンの検証を実施したときのメモです。

JSON ウェブトークンの検証 - Amazon Cognito

Cognitoではユーザプールごとに検証用のJWKセットをダウンロードできます

https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json

使用するGem

jwt

jwt/ruby-jwt: A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.

通常のJWTトークンのデコードに使用

json-jwt

nov/json-jwt: JSON Web Token and its family (JSON Web Signature, JSON Web Encryption and JSON Web Key) in Ruby

パブリック JSON ウェブキー (JWK) から公開鍵を作成するために使用

実装

# JWKセットをダウンロード
uri = "https://cognito-idp.ap-northeast-1.amazonaws.com/example/.well-known/jwks.json"
response = Net::HTTP.get_response(URI.parse(uri))
jwks = JSON.parse(response.body)

# JWTを検証無しでデコード
token = JWT.decode(jwt, nil, false)

# JWKセットの中からkidが一致するものを取得
jwk = jwks["keys"].find { |obj| obj["kid"] == token[1]["kid"] }

# 公開鍵を作成
public_key = JSON::JWK.new(jwk).to_key

# 公開鍵を利用してデコード 検証が不正の場合は例外となる
JSON::JWT.decode(jwt, public_key)

参考になりましたら LGTM お願いします

13
4
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
13
4