📖
Amplify Gen 2でSign in with Slack
Amplifyで用意したCognitoユーザープールにSlackをIDプロバイダーとして活用する、Slackでログイン機能を実装する方法を紹介します
バックエンドにはGen2を用いていますが、Gen1でもAuthのOverrideなりで似たようなことができるはずです
Amplifyのバックエンド構築は一通りできる方を対象にした記事です
手順
Amplifyアプリのデプロイ
まずはIDプロバイダーの設定などを気にせずアプリをデプロイします
Slackアプリの作成
デプロイしたCognitoユーザープールのマネコンを開き
アプリケーションの統合タブに記載されているCognitoドメインをコピーします
そして以下のApp Manifestを使用してSlackアプリを作成します
display_information:
name: {Slackのアプリ名}
oauth_config:
redirect_urls:
- {Cognitoドメイン}/oauth2/idpresponse
settings:
org_deploy_enabled: false
socket_mode_enabled: false
token_rotation_enabled: false
Secretの追加
作成したSlackアプリのSettingのBasic Informationに記載のClient IDとClient SecretをAmplifyアプリに追加します
npx ampx sandbox secret set SLACK_CLIENT_ID
npx ampx sandbox secret set SLACK_CLIENT_SECRET
Authの設定変更
OIDCの外部IDプロバイダーとしてSlackを追加します
amplify/auth/resource.ts
-import { defineAuth } from "@aws-amplify/backend";
+import { defineAuth, secret } from "@aws-amplify/backend";
export const auth = defineAuth({
loginWith: {
email: true,
+ externalProviders: {
+ oidc: [
+ {
+ name: "Slack",
+ clientId: secret("SLACK_CLIENT_ID"),
+ clientSecret: secret("SLACK_CLIENT_SECRET"),
+ scopes: ["profile", "email", "openid"],
+ attributeMapping: {
+ email: "email",
+ preferredUsername: "name",
+ profilePicture: "picture",
+ },
+ issuerUrl: "https://slack.com",
+ },
+ ],
+ logoutUrls: ["http://localhost:3000/"],
+ callbackUrls: ["http://localhost:3000/login"],
+ },
},
});
ユーザーにSlackでログインさせる
signInWithRedirectをSlack指定で呼び出すことでSlackの認可画面に飛ばせます
import { signInWithRedirect } from "aws-amplify/auth";
signInWithRedirect({ provider: { custom: 'Slack' } });
マッピングできる情報
openid.connect.tokenのAPI仕様に記載されています
| 変数名 | サンプル値 |
|---|---|
| iss | https://slack.com |
| sub | U0R7MFMJM |
| aud | 25259531569.11152291 |
| exp | 1626874955 |
| iat | 1626874655 |
| auth_time | 1626874655 |
| nonce | abcd |
| at_hash | tUbyWGBHe0V32FJEupkgVQ |
| https://slack.com/team_id | T0RR |
| https://slack.com/user_id | U0JM |
| bront@slack-corp.com | |
| email_verified | true |
| date_email_verified | 1622128723 |
| locale | en-US |
| name | brent |
| given_name | |
| family_name | |
| https://slack.com/user_image_24 | https://secure.gravatar.com/avatar/bc.png |
| https://slack.com/user_image_32 | ... |
| https://slack.com/user_image_48 | ... |
| https://slack.com/user_image_72 | ... |
| https://slack.com/user_image_192 | ... |
| https://slack.com/user_image_512 | ... |
| https://slack.com/team_image_34 | ... |
| https://slack.com/team_image_44 | ... |
| https://slack.com/team_image_68 | ... |
| https://slack.com/team_image_88 | ... |
| https://slack.com/team_image_102 | ... |
| https://slack.com/team_image_132 | ... |
| https://slack.com/team_image_230 | ... |
| https://slack.com/team_image_default | true |
参考
この記事がめっちゃわかりやすかったです
Discussion