Site Search

Okta

Octa

I tried to create an application linked with Auth0 from scratch

Introduction

Auth0 publishes the tutorials you need for each type of application and platform when working with applications.
https://auth0.com/docs/quickstarts

This time, we will target "Single Page Application" as the application type and "JavaScript" as the programming language, and follow the tutorial provided by Auth0 to create an application linked with Auth0 from scratch.

The application and Auth0 linkage operation finally realized through the procedure described on this page are as follows.

  • Top page (welcome page)
Top page (welcome page)
  • When [Log in] button is clicked (redirect to user authentication by Auth0)
When [Log in] button is clicked (redirect to user authentication by Auth0)
  • Login completion screen
Login completion screen
  • When [Log out] button is clicked (redirect to top page)
When [Log out] button is clicked (redirect to top page)

In addition, if you want to check the linkage operation with the sample application provided by Auth0, please refer to [How to set up linkage between Auth0 and sample application (link)].

premise

The information on functions and settings described on this page is current as of October​ ​2022.

Advance preparation

Please prepare the following before performing the following settings.

  • macOS or Windows PC
  • Installing Node.js, Node Package Manager
  • Issuing an Auth0 free trial account (Reference: [How to use Auth0 trial (link)])

Setting overview

The setting procedure introduced here is as follows.

  • Auth0 settings
    • Application creation and configuration in Auth0
  • Application settings
    • Application setup
    • Web server construction
    • Initializing the Auth0 SDK
    • Authentication status evaluation settings introduced
    • Introduce login behavior to the application
    • Introduced login-out behavior from the application
    • Display user information on the page after logging in to the application

From here, we will introduce specific settings and operation check procedures.

Creating and configuring an application in Auth0

In order to implement the application authentication function using Auth0, first configure the application linkage settings on the Auth0 side. This time, I will introduce the procedure for Single Page Applications using JavaScript.

(1) Log in to the Auth0 management screen and click [Create Application] in Activity
* It is also possible from [Create Applications] in Applications > Applications.
Auth0管理画面にログインし、Activityの[Create Application]をクリック
(2) Setting items for the application to be created are displayed. Set the following and click [Create].
  • Name: Set any name (can be set in Japanese, can be changed later)
  • Choose an application type: Select "Single Page Web Applications"
作成するアプリケーションの設定項目が表示されるので、以下を設定し、[Create]をクリック
(3) Confirm that the application setting was created with the arbitrary name you specified
指定した任意の名前でアプリケーション設定が作成されたことを確認
(4) Go to the Settings tab on the application settings screen and move to "Application URIs" at the bottom of the screen
アプリケーション設定画面のSettingsタブへ遷移し、画面下の「Application URIs」まで移動
(5) Set "http://localhost:3000" for all of the following setting items
  • Allowed Callback URLs (whitelist of URLs that can be redirected after logging into Auth0)
  • Allowed Logout URLs (whitelist of URLs that can be redirected after logging out of Auth0)
  • Allowed Web Origins (whitelist of origin URLs to request to Auth0 API)
以下設定項目の全てに「http://localhost:3000」を設定
(6) Click [Save Changes] at the bottom of the screen to save the settings.
画面下の[Save Changes]をクリックし、設定保存

Application setup

First, create an HTML/CSS/JavaScript file and a storage folder for the application linked with Auth0, and then create an environment information file that describes the Auth0 tenant domain and Client ID. The setting procedure is as follows.

(1) Create a root folder for saving files (folder name is arbitrary)
(2) Create an index.html file in the root folder and enter the following code
ルートフォルダへindex.htmlファイルの作成及び以下コード記載
*By adding the <script src="https://cdn.auth0.com/js/auth0-spa-js/1.20/auth0-spa-js.production.js"></script> statement, index. Get Auth0's SPA SDK by referencing the package from the CDN in your html file.
(3) Create a folder named "public" in the root folder
(4) Create a folder named "css" in the public folder, create a main.css file, and write the following code
ルートフォルダへindex.htmlファイルの作成及び以下コード記載
(5) Create a folder named "js" in the public folder and create an app.js file
* At this stage, it is not necessary to write code in app.js.
(6) Create an auth_config.json file in the root directory and include Auth0 tenant domain and Client ID information
*The Auth0 tenant domain and Client ID can be confirmed on the Settings tab of the linked application on the Auth0 management screen.
* The file structure of HTML/CSS/JavaScript is as follows.

Web server construction

Next, I will explain how to start a web server using Node.js. The setting procedure is as follows.

(1) Open a terminal and move to the folder where the index.html file was created
(2) Execute the following command to initialize the project to be managed
以下コマンドを実行し、管理するプロジェクトを初期化
(3) Execute the following command and confirm that the package.json file has been created.
以下コマンドを実行し、package.jsonファイルが作成されたことを確認
(4) Execute the following command to install Express and save it in the dependency list
以下コマンドを実行し、Expressをインストール及び依存関係リストに保存
(5) Execute the following command to install nodemon
以下コマンドを実行し、nodemonをインストール
(6) package.json file: code edit the "scripts" part as follows
package.jsonファイル:「scripts」部分を以下の通りにコード編集
*With the above settings, the application will start normally when "npm start" is executed, the application will be started using nodemon when "npm run dev" is executed, and the process will be automatically restarted when the code is changed.
(7) Create a server.js file in the same folder as the index.html file and add the following code
*This is the backend server setting for providing the SPA page.
index.htmlファイルと同じフォルダに、server.jsファイルを作成、以下コードを追記

Initializing the Auth0 SDK

Next, we introduce the initialization settings for the Auth0 SDK. The setting and operation check procedures are as follows.

(1) app.js file: add a variable to store the Auth0 client object
app.jsファイル:Auth0のクライアントオブジェクトを格納する変数を追加
(2) app.js file: set the fetchAuthConfig function to reflect the Auth0 configuration information described in the auth_config.json file
app.jsファイル:auth_config.jsonファイル記載のAuth0の設定情報を反映させるため、fetchAuthConfig関数を設定
(3) app.js file: To initialize the Auth0 tenant domain and Client ID, create a configureClient function and set to call the setting value from the fetchAuthConfig function
*The Auth0 tenant domain and Client ID are set using the createAuth0Client method.
app.jsファイル:Auth0テナントドメインとClient IDを初期化するため、configureClient関数の作成及びfetchAuthConfig関数から設定値を呼び出すように設定
(4) app.js file: Set to call the configureClient function in the window.onload function of the event handler in order to initialize the application settings.
app.jsファイル:アプリケーション設定の初期化を行うため、イベントハンドラーのwindow.onload関数にて、configureClient関数を呼び出すように設定
(5) Execute the following command to start the server
以下コマンドを実行し、サーバを起動
(6) Open http://localhost:3000 in your web browser and confirm that the welcome message is displayed.
*Currently, the button is disabled, but there is no problem.
Webブラウザにてhttp://localhost:3000を開き、ウェルカムメッセージが表示されることを確認

Authentication status evaluation settings introduced

Whether or not you are logged in to Auth0 can be checked from the auth0.isAuthenticated() method, which can be used to enable/disable the [Log in] and [Log out] buttons. The setting and operation check procedures are as follows.

(1) app.js file: add updateUI function to call auth0.isAuthenticated() to display enabled/disabled buttons, add setting to call updateUI function after initializing application settings in window.onload
app.jsファイル:auth0.isAuthenticated()を呼び出してボタンの有効/無効表示するため、updateUI関数を追加、window.onloadでアプリケーションの設定初期化後にupdateUI関数を呼び出すように設定を追加
(2) After starting the server, open http://localhost:3000 in a web browser and confirm that the welcome message is displayed and the [Log in] button is enabled and the [Log out] button is disabled.
* Since the operation after clicking the [Log in] button has not been set, nothing will happen even if the [Log in] button is clicked.
サーバ起動後、Webブラウザでhttp://localhost:3000を開き、ウェルカムメッセージが表示され、[Log in]ボタンが有効かつ[Log out]ボタンが無効であることを確認

Introduce login behavior to the application

To redirect login authentication to Auth0, use the auth0.loginWithRedirect() method. The setting and operation check procedures are as follows.

(1) app.js file: Add a login function to redirect login authentication to Auth0 when clicking the [Log in] button
*Use the window.location.origin property to redirect to the original page after login.
 app.jsファイル:[Log in]ボタンをクリックした際にAuth0へログイン認証をリダイレクトするようにlogin関数を追加
(2) After starting the server with the command below, open http://localhost:3000 in your web browser and click the [Log in] button.
以下コマンドにてサーバ起動後、Webブラウザでhttp://localhost:3000を開き、[Log in]ボタンをクリック
以下コマンドにてサーバ起動後、Webブラウザでhttp://localhost:3000を開き、[Log in]ボタンをクリック
(3) The Auth0 login screen will be displayed, so log in as a registered Auth0 user
Auth0のログイン画面が表示されるので、Auth0登録済のユーザでログインを実施
(4) Confirm that login with Auth0 is successful and you are redirected to the top page of the application
*The [Log in] button is enabled because the authentication result is not reflected on the page after login.
Auth0におけるログインが成功し、アプリケーションのトップページへリダイレクトされることを確認
(5) app.js file: Change the contents of windows.onload to add settings for post-login page processing in Auth0
*When user authentication is completed, both code and state parameters are included in the URL query. Therefore, if these two parameters are included, the authentication result from Auth0 is called by the auth0.handleRedirectCallback() method and reflected on the page.
* The URL of the page is processed so that the state and code parameters are not displayed using the window.history.replaceState () method.
app.jsファイル:Auth0におけるログイン後のページ処理を設定追加するため、windows.onloadの中身を変更
(6) Start the server again and confirm that the [Log out] button is enabled on the redirect page after user authentication in Auth0 and the URL is http://localhost:3000
再度サーバを起動し、Auth0におけるユーザ認証後のリダイレクトページで[Log out]ボタンが有効化されていること、URLがhttp://localhost:3000になっていることを確認
* Since the operation after clicking the [Log out] button has not been set, nothing will happen even if the [Log out] button is clicked.

Introduced login-out behavior from the application

Add settings for logout processing. The setting and operation check procedures are as follows.

(1) app.js file: Add a logout function and use the auth0.logout () method to perform logout processing from Auth0 in order to add operation processing when the [Log out] button is clicked.
app.jsファイル:[Log out]ボタンクリック時の動作処理を追加するため、logout関数の追加、auth0.logout ()メソッドを用いてAuth0からのログアウト処理を実施
(2) Start the server and click the [Log out] button on the redirect page after user authentication in Auth0
サーバを起動し、Auth0におけるユーザ認証後のリダイレクトページで[Log out]ボタンをクリック
(3) Confirm that the [Log in] button is enabled
[Log in]ボタンが有効化されることを確認

Display user information on the page after logging in to the application

You can get an access token and an ID token each time a user logs in. Also, the logged-in user's profile information can be extracted from the ID token. Here, set to display the login user's access token and profile information on the page redirected after user authentication in Auth0. The setting procedure and operation check are as follows.

(1) index.html file: Add the following code to body
index.htmlファイル:bodyに以下コードを追加
(2) app.js file: Add settings to updateUI() function to get and display access token and profile information
*By using the auth0.getTokenSilently() method, it is possible to obtain the access token of the user logged in to Auth0.
*By using the auth0.getUser() method, it is possible to obtain the profile information of the user logged into Auth0.
app.jsファイル:アクセストークンとプロファイル情報を取得及び表示するため、updateUI()関数に設定を追加
(3) Start the server and confirm that the login user's access token and profile information are displayed on the redirect page after user authentication in Auth0
サーバを起動し、Auth0におけるユーザ認証後のリダイレクトページにログインしたユーザのアクセストークンとプロファイル情報が表示されることを確認
(4) Confirm that the user's access token and profile information are hidden by clicking the [Log out] button
[Log out]ボタンをクリックすることで、ユーザのアクセストークンとプロファイル情報が非表示となることを確認

Summary

The Auth0 methods used in the setting procedure on this page are as follows.

method explanation Reference procedure
createAuth0Client Create an Auth0 client Initializing the Auth0 SDK
auth0.isAuthenticated Check if authenticated to Auth0 Authentication status evaluation settings introduced
auth0. loginWithRedirect Transition to Auth0 login screen Introduce login behavior to the application
auth0. handleRedirectCallback Callback authentication result from Auth0
auth0.logout Log out from Auth0 Introduced login-out behavior from the application
auth0. getTokenSilently Get access token of user logged in to Auth0 Display user information on the page after logging in to the application
auth0. getUser Get profile information of user logged in to Auth0

We hope that the explanations on this page will help you understand the settings required for linking Auth0 with your application and how Auth0 works.

Inquiry/Document request

In charge of Macnica Okta Co., Ltd.

Weekdays: 9:00-17:00