This tutorial shows how to use PlusAuth with Angular Single Page Application. If you do not have a PlusAuth account, register from here.
This tutorial follows plusauth-angular-starter sample project on Github. You can download and follow the tutorial via the sample project.
Create PlusAuth Client
After you sign up or log in to PlusAuth, you need to create a client to get the necessary configuration keys in the dashboard.
Go to Clients and create a client with the type of Single Page Application
Configure Client
Get Client Properties
You will need your Client Id for interacting with PlusAuth. You can retrieve it from the created client's details.
Configure Redirect and Logout URIs
When PlusAuth authenticates a user, it needs a URI to redirect back with access and id token. That URI must be in your client's Redirect URI
list. If your application uses a redirect URI which is not white-listed in your PlusAuth Client, you will receive an error.
The same thing applies to the logout URIs. After the user logs out, you need a URI to be redirected.
If you are following the sample project, the Redirect URL you need to add to the Redirect URIs fields are http://localhost:4200/callback and http://localhost:4200/silent-renew.
The Logout URL you need to add to the Post Logout Redirect URIs field is http://localhost:4200/.
Create an Angular Application
Install the Angular CLI globally using npm and create a new Angular project. Add a router to the project to render different views.
# Create the application using the ng new.
ng new plusauth-angular-starter --routing
# Move into the project directorycd plusauth-angular-starter
# Add bootstrap for stylingnpminstall bootstrap
The ng new command prompts you for information about features to include in the initial application project. --routing flag adds the routing by default.
Install OIDC Client
For interacting with PlusAuth it is advised to use an OpenID Connect library.
In this tutorial we will be using plusauth-oidc-client-js
but you could use any OpenID Connect library.
Install plusauth-oidc-client-js with the following command
npminstall @plusauth/plusauth-oidc-client-js
plusauth-oidc-client-js is an OpenID Connect (OIDC) and OAuth2 library for browser based JavaScript applications.
You can find source code on Github and the API documentation here.
Configure Angular Application to use PlusAuth
We will be using environment files for maintaining providing some constant values.
Edit environment.ts file
Edit the environment.ts file in src/environments with the following and modify values accordingly.
If you are following the sample project, rename environment.example.ts to environment.ts and replace the values accordingly.
Configure Angular Application
Let's start by editing our application's entry point module.
Edit app.module.ts in src/app folder. Import components and other modules that we will create later.
AuthService is provided in AppModule that makes it injectable globally. ngDoBootstrap is used to bootstrap AppComponent after AuthService is initialized.
Configure OIDC Client
We need to initialize our OIDC Client library to handle authentication-related operations.
Create auth.service.ts in src/app/services folder. Configure plusauth-oidc-client-js as following:
You may have noticed that the values defined in the Configure Client section are used here. If you have used different
values make sure to update this file accordingly.
Configure Router
Now let's define our application's router module. We are going to define the routes of our views.
Create app-routing.module.ts in src/app folder as following:
AuthGuardService guard service will ensure the related route is activated only by authenticated users.
Now create auth-guard.service.ts in src/app/services as following:
// auth-guard.service.tsimport{ Injectable }from'@angular/core'import{ CanActivate, Router }from'@angular/router'import{ AuthService }from'./auth.service'@Injectable({
providedIn:'root'})exportclassAuthGuardServiceimplementsCanActivate{constructor(private authService: AuthService,private router: Router){}// Check user if logged in for routes that requires authasynccanActivate():Promise<boolean>{if(awaitthis.authService.getIsLoggedIn()){returntrue}this.router.navigate(['/unauthorized'])returnfalse}}
Implement login, user profile, and logout
Until now, we have defined our authentication helper and routes. It is time to create the pages and interact with auth helper.
Edit Main Layout Component
Let's create a simple layout for our application. Add app-header and router-outlet to app.component.ts in src/app.
Create header.component.ts under src/app/components folder. It will be a basic header. If a user is authenticated, it will show the user's identifier and a Logout button.
If not, a Login button will be there to initiate login.
To handle authorization results after a successful login, we need
a simple page and let the library handle the authentication result.
Create auth-callback.component.ts under src/app/components folder.
Access tokens retrieved from PlusAuth have a life span.
plusauth-oidc-client-js automatically provides access_token renewal without too much hassle.
Before your access token expires, it will receive a new one in the background so that
your users will have a flawless app experience without signing in again.
Create silent-renew.component.ts under src/app/components folder as following:
We will display a page whenever a user tries to access a protected route without signing in.
Create unauthorized.component.ts under src/app/views.
// unauthorized.component.tsimport{ Component }from'@angular/core'import{ AuthService }from'../services/auth.service'@Component({
selector:'app-unauthorized',
templateUrl:`
<div class="container">
<p>You must log in to view the page</p>
<button class="btn btn-primary" (click)="authService.login()">Log in</button>
</div>
`,
styleUrls:[]})exportclassUnauthorizedComponent{constructor(public authService: AuthService){}}
See it in action
That's it. Start your app and point your browser to http://localhost:4200. Follow the Log In link to log in or sign up to your PlusAuth tenant. Upon successful login or signup, you should be redirected back to the application.