Step 1. Configuration
Your application will require certain configuration information. Before carrying on with the rest of the implementation, create anAuthConfig
interface which will contain various configuration values. Place this interface in a file called auth0-variables.ts
.
Step 2. Authorize the User
Create an Authorization Service
The best way to manage and coordinate the tasks necessary for user authentication is to create a reusable service. With the service in place, you’ll be able to call its methods throughout your application. An instance of theWebAuth
object from auth0.js can be created in the service.
- login: calls
authorize
from auth0.js which initiates - handleAuthentication: looks for an authentication result in the URL hash and processes it with the
parseHash
method from auth0.js - setSession: sets the user’s , , and a time at which the Access Token will expire
- logout: removes the user’s tokens from browser storage isAuthenticated: checks whether the expiry time for the Access Token has passed
Process the Authentication Result
When a user authenticates via Universal Login and is then redirected back to your application, their authentication information will be contained in a URL hash fragment. ThehandleAuthentication
method in the AuthService
is responsible for processing the hash.
Call handleAuthentication
in your app’s root component so that the authentication hash fragment can be processed when the app first loads after the user is redirected back to it.
Add the Callback Component
Using Universal Login means that users are taken away from your application to a page hosted by Auth0. After they successfully authenticate, they are returned to your application where a client-side session is set for them. You can choose to have users return to any URL in your application that you like; however, it is recommended that you create a dedicated callback route to serve as a central location that the user will be returned to upon successful authentication. Having a single callback route is beneficial for two main reasons:- It prevents the need to allowlist multiple (and sometimes unknown) callback URLs
- It serves as a place to show a loading indicator while your application sets the user’s client-side session
CallbackComponent
and populate it with a loading indicator.
assets
directory. See the downloadable sample for a demonstration.
After authentication, users will be taken to the /callback
route for a brief time where they will be shown a loading indicator. During this time, their client-side session will be set, after which they will be redirected to the /home
route.
Step 3. Get the User Profile
Extract info from the token
This section shows how to retrieve the user info using the Access Token and the /userinfo endpoint. Alternatively, you can just decode the ID Token using a library (make sure you validate it first). The output will be the same. If you need additional user information consider using the our Management API.
AuthService
class. Add a getProfile
function which will extract the user’s Access Token from local storage, and then pass that call the userInfo
function to retrieve the user’s information.
Step 4. Display UI Elements Conditionally Based on Scope
During the authorization process we already stored the actual scopes which a user was granted in the local storage. If thescope
returned in the authResult
is not empty, it means that a user was issued a different set of scopes than what was initially requested, and we should therefore use authResult.scope
to determine the scopes granted to the user.
If the scope
returned in authResult
is issued is empty, it means the user was granted all the scopes that were requested, and we can therefore use the requested scopes to determine the scopes granted to the user.
Here is the code we wrote earlier for the setSession
function that does that check:
AuthService
class which we can call to determine if a user was granted a specific scope:
approve:timesheets
scope. Note in the code below that we added a call to the userHasScopes
function to determine whether that link should be displayed or not.
Protect a route
We should also protect a route to not allow a route to be navigated to if a user has not been granted the correct scopes. For this we can add a newScopeGuardService
service class:
ScopeGuardService
in the definition for the approval
route below:
Step 5. Call the API
The angular2-jwt module can be used to automatically attach to requests made to your API. It does this by providing anAuthHttp
class which is a wrapper over Angular’s Http
class.
Install angular2-jwt
:
angular2-jwt
and add it to the providers
array in your application’s @NgModule
. The factory function should have a tokenGetter
function which fetches the access_token
from local storage.
angular2-jwt
is configured, you can use the AuthHttp
class to make secure calls to your API from anywhere in the application. To do so, inject AuthHttp
in any component or service where it is needed and use it just as you would use Angular’s regular Http
class.
Step 6. Renew the Access Token
Renewing the user’s Access Token requires to update the Angular SPA. Add a method to theAuthService
which calls the checkSession
method from auth0.js. If the renewal is successful, use the existing setSession
method to set the new tokens in local storage.
AuthService
class, add a method called scheduleRenewal
to set up a time at which authentication should be silently renewed. In the sample below this is set up to happen 30 seconds before the actual token expires. Also add a method called unscheduleRenewal
which will unsubscribe from the Observable.
scheduleRenewal
inside your AppComponent
which will happen when the page is loaded. This will occur after every authentication flow, either when the user explicitly logs in, or when the silent authentication happens.