Skip to content

Instantly share code, notes, and snippets.

@TakesxiSximada
Last active October 18, 2020 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TakesxiSximada/c7a1159d61d53e22a2989fc2fcd448dc to your computer and use it in GitHub Desktop.
Save TakesxiSximada/c7a1159d61d53e22a2989fc2fcd448dc to your computer and use it in GitHub Desktop.
Auth0のクライアント実装例

Auth0のシンプルなFrontendの実装例

Auth0を用いたシンプルなフロントエンドの実装をした。

https://media.giphy.com/media/HBApqpFKOq4dkXWLc7/giphy.gif

(注意: セキュリティ的な問題は考慮していない)

ビルド

make

設定

Auth0から発行される値でpublic/auth_config.jsonを編集する。

起動

python3 -m http.server --directory public 3000

環境

Node
v14.14.0
TypeScript
4.0.3

[[

{
"domain": "YOUR AUTH0 DOMAIN",
"clientId": "YOUR CLIENT ID"
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.auth0.com/js/auth0-spa-js/1.2/auth0-spa-js.production.js"></script>
</head>
<body>
<ol>
<li><button onclick="login()">login</button></li>
<li>
<button onclick="handleRedirectCallback()">
handleRedirectCallback
</button>
</li>
<li><button onclick="isAuthenticated()">isAuthenticated</button></li>
<li><button onclick="showProfile()">show profile</button></li>
<li><button onclick="logout()">logout</button></li>
</ol>
<script src="main.js"></script>
<script>
window.onload = initialize;
</script>
</body>
</html>
declare function createAuth0Client(obj: any): any;
let auth0: any = null;
// 設定(JSON)を取得し、auth0のクライアントを生成する。
async function initialize() {
const resp = await fetch("/auth_config.json");
const config = await resp.json();
console.log(config);
auth0 = await createAuth0Client({
domain: config.domain,
client_id: config.clientId,
});
}
// ログイン画面へ移動する。
async function login() {
await auth0.loginWithRedirect({
redirect_uri: window.location.origin,
});
}
// ログイン画面から戻ってきた際にログイン処理を完了する。
async function handleRedirectCallback() {
const resp = await auth0.handleRedirectCallback();
console.log(resp);
// codeがそのままURLに残ってしまわないように履歴を置き換える。
window.history.replaceState({ url: "/" }, "", "/");
}
// ログイン済みかどうかを確認する。
async function isAuthenticated() {
const isAuthenticated = await auth0.isAuthenticated();
console.log(isAuthenticated);
}
// ユーザー情報を取得する。
async function showProfile() {
const user = await auth0.getUser();
console.log(user);
}
// ログアウトする。
async function logout() {
await auth0.logout({
returnTo: window.location.origin,
});
}
.PHONY: all
all: main.ts
tsc --outFile main.js main.ts
web: python3 -m http.server 3000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment