Skip to content

Instantly share code, notes, and snippets.

@suwa-yuki
Last active March 5, 2020 06:31
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 suwa-yuki/91a5874354a27efa696400dcc273b14d to your computer and use it in GitHub Desktop.
Save suwa-yuki/91a5874354a27efa696400dcc273b14d to your computer and use it in GitHub Desktop.
Auth0 Webinar Scripts
// The Auth0 client, initialized in configureClient()
let auth0 = null;
/**
* Starts the authentication flow
*/
const login = async (targetUrl) => {
try {
console.log("Logging in", targetUrl);
const options = {
redirect_uri: window.location.origin,
// ログイン時にaudienceを追加
// --- START ---
audience: 'http://example.jp'
// --- END ---
};
if (targetUrl) {
options.appState = { targetUrl };
}
await auth0.loginWithRedirect(options);
} catch (err) {
console.log("Log in failed", err);
}
};
/**
* Executes the logout flow
*/
const logout = () => {
try {
console.log("Logging out");
auth0.logout({
returnTo: window.location.origin
});
} catch (err) {
console.log("Log out failed", err);
}
};
/**
* Retrieves the auth configuration from the server
*/
const fetchAuthConfig = () => fetch("/auth_config.json");
/**
* Initializes the Auth0 client
*/
const configureClient = async () => {
const response = await fetchAuthConfig();
const config = await response.json();
auth0 = await createAuth0Client({
domain: config.domain,
client_id: config.clientId
});
};
/**
* Checks to see if the user is authenticated. If so, `fn` is executed. Otherwise, the user
* is prompted to log in
* @param {*} fn The function to execute if the user is logged in
*/
const requireAuth = async (fn, targetUrl) => {
const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) {
return fn();
}
return login(targetUrl);
};
// Will run when page finishes loading
window.onload = async () => {
await configureClient();
// If unable to parse the history hash, default to the root URL
if (!showContentFromUrl(window.location.pathname)) {
showContentFromUrl("/");
window.history.replaceState({ url: "/" }, {}, "/");
}
const bodyElement = document.getElementsByTagName("body")[0];
// Listen out for clicks on any hyperlink that navigates to a #/ URL
bodyElement.addEventListener("click", (e) => {
if (isRouteLink(e.target)) {
const url = e.target.getAttribute("href");
if (showContentFromUrl(url)) {
e.preventDefault();
window.history.pushState({ url }, {}, url);
}
}
});
const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) {
console.log("> User is authenticated");
// ログイン済みの際にAccess Tokenを取得してみる
// --- START ---
const token = await auth0.getTokenSilently({
audience: 'http://example.jp'
});
console.log(token);
// --- END ---
window.history.replaceState({}, document.title, window.location.pathname);
updateUI();
return;
}
console.log("> User not authenticated");
const query = window.location.search;
const shouldParseResult = query.includes("code=") && query.includes("state=");
if (shouldParseResult) {
console.log("> Parsing redirect");
try {
const result = await auth0.handleRedirectCallback();
if (result.appState && result.appState.targetUrl) {
showContentFromUrl(result.appState.targetUrl);
}
console.log("Logged in!");
} catch (err) {
console.log("Error parsing redirect:", err);
}
window.history.replaceState({}, document.title, "/");
}
updateUI();
};
{
"AUTH0_DOMAIN": "",
"AUTH0_CLIENT_SECRET": "",
"AUTH0_CLIENT_ID": "",
"AUTH0_ALLOW_DELETE": true
}
function login(email, password, callback) {
const request = require('request');
request.post({
url: 'https://57uzc58adk.execute-api.us-east-1.amazonaws.com/prod',
json: {
id: email,
email: email,
password: password
},
headers: {
'content-type': 'application/json'
}
}, function(err, response, body) {
if (err) return callback(err);
if (response.statusCode === 401) return callback();
callback(null, {
user_id: body.id,
email: body.email
});
});
}
function (user, context, callback) {
// Access should only be granted to verified users.
if (!user.email || !user.email_verified) {
return callback(new UnauthorizedError('Access denied.'));
}
const whitelist = ['classmethod.jp']; //authorized domains
const userHasAccess = whitelist.some(
function (domain) {
const emailSplit = user.email.split('@');
return emailSplit[emailSplit.length - 1].toLowerCase() === domain;
});
if (!userHasAccess) {
return callback(new UnauthorizedError('Access denied.'));
}
return callback(null, user, context);
}
rules:
- name: Email domain whitelist
script: ./rules/Email domain whitelist.js
stage: login_success
enabled: true
order: 1
rulesConfigs: []
hooks: []
pages:
- name: login
enabled: true
html: ./pages/login.html
resourceServers:
- name: Example API
identifier: 'https://example.com'
allow_offline_access: false
enforce_policies: true
scopes:
- value: 'read:users'
description: 'read:users'
signing_alg: RS256
skip_consent_for_verifiable_first_party_clients: true
token_dialect: access_token_authz
token_lifetime: 86400
token_lifetime_for_web: 7200
clients:
- name: API Explorer Application
app_type: non_interactive
cross_origin_auth: false
custom_login_page_on: true
grant_types:
- client_credentials
is_first_party: true
is_token_endpoint_ip_header_trusted: false
jwt_configuration:
alg: RS256
lifetime_in_seconds: 36000
secret_encoded: false
oidc_conformant: true
sso_disabled: false
- name: Example API (Test Application)
app_type: non_interactive
cross_origin_auth: false
custom_login_page_on: true
grant_types:
- client_credentials
is_first_party: true
is_token_endpoint_ip_header_trusted: false
jwt_configuration:
alg: RS256
lifetime_in_seconds: 36000
secret_encoded: false
oidc_conformant: true
sso_disabled: false
- name: Sample App
allowed_clients: []
allowed_logout_urls:
- 'http://localhost:3000'
allowed_origins:
- 'http://localhost:3000'
app_type: spa
callbacks:
- 'http://localhost:3000'
client_aliases: []
cross_origin_auth: false
custom_login_page_on: true
grant_types:
- authorization_code
- implicit
- refresh_token
is_first_party: true
is_token_endpoint_ip_header_trusted: false
jwt_configuration:
alg: RS256
lifetime_in_seconds: 36000
secret_encoded: false
native_social_login:
apple:
enabled: false
facebook:
enabled: false
oidc_conformant: true
sso_disabled: false
token_endpoint_auth_method: none
web_origins:
- 'http://localhost:3000'
databases:
- name: Custom-DB
strategy: auth0
enabled_clients: []
is_domain_connection: false
options:
mfa:
active: true
return_enroll_settings: true
passwordPolicy: good
disable_signup: false
requires_username: false
strategy_version: 2
brute_force_protection: true
customScripts:
login: ./databases/Custom-DB/login.js
enabledDatabaseCustomization: true
import_mode: false
password_no_personal_info:
enable: false
password_dictionary:
enable: false
dictionary: []
password_history:
enable: false
size: 5
password_complexity_options:
min_length: 8
realms:
- Custom-DB
- name: Username-Password-Authentication
strategy: auth0
enabled_clients:
- API Explorer Application
- Sample App
- Example API (Test Application)
is_domain_connection: false
options:
mfa:
active: true
return_enroll_settings: true
passwordPolicy: good
strategy_version: 2
brute_force_protection: true
realms:
- Username-Password-Authentication
connections:
- name: Sample-AD
strategy: ad
enabled_clients: []
is_domain_connection: false
options:
certAuth: false
disable_cache: false
kerberos: false
ips: null
brute_force_protection: true
- name: google-oauth2
strategy: google-oauth2
enabled_clients:
- API Explorer Application
- Example API (Test Application)
is_domain_connection: false
options:
email: true
profile: true
scope:
- email
- profile
tenant:
enabled_locales:
- ja
flags:
new_universal_login_experience_enabled: true
universal_login: true
disable_clickjack_protection_headers: false
universal_login:
colors:
page_background: '#000000'
primary: '#0059d6'
emailProvider: {}
emailTemplates: []
clientGrants:
- client_id: Example API (Test Application)
audience: 'https://example.com'
scope: []
guardianFactors:
- name: duo
enabled: false
- name: email
enabled: false
- name: otp
enabled: false
- name: push-notification
enabled: false
- name: sms
enabled: false
guardianFactorProviders: []
guardianFactorTemplates: []
roles:
- name: Admin
description: Administrator
permissions: []
branding:
colors:
page_background: '#000000'
primary: '#0059d6'
prompts: {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment