Auth0の設定をauth0-deploy-cliでexportしてバージョン管理する

auth

認証プラットフォームAuth0の設定をバージョン管理する。

Cognitoでは複数のIdPの名寄せを行うのにUserPoolのsubを自力でマッピングしたり、IdentityPoolを用いる必要があったりするが、 Auth0ではそのあたりをRuleによって行えたりと多機能で、ドキュメントやライブラリ、サンプルコードも充実している。 その分、コストが高めだが、重要だがコアではない認証回りを任せられるのは助かる。

まずTenantにAuth0 Management APIの必要なPermissionを付けたMachine to Machine Applicationを作成する。

Auth0 Management APIのPermissionを付与

Applicationのclient_id/secretで、APIを呼ぶ際に Authorization:Bearer *** Headerで渡すアクセストークンを取得して正しいPermissionがscopeに含まれていることを確認する。

$ curl --request POST \
  --url https://sambaiz-test.jp.auth0.com/oauth/token \
  --header 'content-type: application/json' \
  --data '{"client_id":"Kd4e04vgdXfYf69ZcrKLLH3wDYQyxAcU","client_secret":"****","audience":"https://sambaiz-test.jp.auth0.com/api/v2/","grant_type":"client_credentials"}' \
  | jq '.access_token | split(".") | .[1] | @base64d | fromjson'
{
  "iss": "https://sambaiz-test.jp.auth0.com/",
  "sub": "Kd4e04vgdXfYf69ZcrKLLH3wDYQyxAcU@clients",
  "aud": "https://sambaiz-test.jp.auth0.com/api/v2/",
  "iat": 1623482883,
  "exp": 1623569283,
  "azp": "Kd4e04vgdXfYf69ZcrKLLH3wDYQyxAcU",
  "scope": "read:client_grants create:client_grants delete:client_grants ...",
  "gty": "client-credentials"
}

auth0-deploy-cliをインストールする。

$ npm i -g auth0-deploy-cli
$ a0deploy --version
5.5.7

a0deploy export すると現在の設定の tenant.yaml が出力されるのでこれをバージョン管理する。

$ cat config.json
{
  "AUTH0_DOMAIN": "sambaiz-test.jp.auth0.com",
  "AUTH0_CLIENT_ID": "Kd4e04vgdXfYf69ZcrKLLH3wDYQyxAcU",
  "AUTH0_ALLOW_DELETE": false,
  "EXCLUDED_PROPS": {
    "clients": ["client_secret"],
    "connections": ["options.client_secret"]
  }
}

$ export AUTH0_CLIENT_SECRET=*****
$ a0deploy export -c config.json --strip --format yaml --output_folder .

中身はこんな感じ。

$ cat tenant.yaml
clientGrants: []
rules: []
hooks: []
pages: []
resourceServers: []
clients:
  - name: Default App
    callbacks: []
    cross_origin_auth: false
    custom_login_page_on: true
    grant_types:
      - authorization_code
      - implicit
      - refresh_token
      - client_credentials
...

a0deploy import すると更新されるので、GitHub Actionsなどでpush時に実行すれば同期できる。

- name: Import changes to the Auth0 account
  env:
    AUTH0_CLIENT_SECRET: ${{ secrets.AUTH0_CLIENT_SECRET }}
  run: a0deploy import -c config.json --input_file tenant.yaml