LoginSignup
14
12

More than 3 years have passed since last update.

Amplifyを使って期限切れのIDトークン、アクセストークンを更新する

Last updated at Posted at 2019-11-06

概要

Amplifyを使用して期限切れのトークン(ID、アクセス、更新)を更新する。
※ちなみにトークンの有効期限は1時間

※期限切れかどうかに関わらず強制的にトークンを再発行する方法は↓を参照
Amplifyを使って任意のタイミングでIDトークン、アクセストークンを更新する

実装

下記を実行するだけ。

Auth.currentSession()
  • トークンの期限が切れている場合、自動的に更新(更新トークンの有効期限内である場合)される。
  • トークンの期限が切れていない場合、何も起きない(CignitoのAPIに対してのリクエストがない)。
  • 更新トークンの期限が切れている場合、更新されない(更新トークンの期限切れはサインインし直し)。

参考

リクエストサンプル

Auth.currentSession() 実行時のHTTPリクエストのヘッダ

POST https://cognito-idp.ap-northeast-1.amazonaws.com/ http/2.0
Sec-Fetch-Mode  : cors
Referer         : http://localhost:3000/
Origin          : http://localhost:3000
X-Amz-Target    : AWSCognitoIdentityProviderService.InitiateAuth
X-Amz-User-Agent: aws-amplify/0.1.x js
User-Agent      : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Content-Type    : application/x-amz-json-1.1

リクエストボディ

{
    "ClientId": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    "AuthFlow": "REFRESH_TOKEN_AUTH",
    "AuthParameters": {
        "REFRESH_TOKEN": "略",
        "DEVICE_KEY": null
    }
}

更新トークンが期限切れの場合

レスポンスヘッダ

status                       : 400
date                         : Wed, 06 Nov 2019 03:54:02 GMT
content-type                 : application/x-amz-json-1.1
content-length               : 78
x-amzn-requestid             : 3f9e72e9-36af-4a9e-b585-8d5f1733a173
access-control-allow-origin  : *
x-amzn-errortype             : NotAuthorizedException:
access-control-expose-headers: x-amzn-RequestId,x-amzn-ErrorType,x-amzn-ErrorMessage,Date
x-amzn-errormessage          : Refresh Token has been revoked

レスポンスボディ(↓がbase64でエンコードされたモノが返ってくる)

{"__type":"NotAuthorizedException","message":"Refresh Token has been revoked"}
14
12
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
14
12