Angular 2 Authorization

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Angular 2.0.1
Show requirements

Many identity providers will supply access claims (such as roles or groups) with the user. You can request these in the token by setting scope: openid roles or scope: openid groups. However, not every identity provider supplies this type of information. Fortunately, Auth0 has an alternative, which is to create a rule for assigning different roles to different users.

NOTE: This tutorial assumes that you have already completed the rules tutorial and that you know how to implement a basic rule in your app.

Create a Rule to Assign Roles

First, create a rule that assigns users to either an admin role or a single user role. Go to the New Rule page in the Auth0 dashboard and select the Set Roles to a User template under Access Control.

By default, this rule will assign the user an admin role if the user’s email contains @example.com. Otherwise, the user will be assigned a regular user role.

You can modify this line in the default script to change the domain name to one suitable for your setup:

if (user.email.indexOf('@example.com') > -1)

NOTE: You can set roles other than admin and user and you may customize the rule as needed.

Restrict a Route Based on User's Roles

To restrict access to certain routes, Angular's CanActivate guard can be used.

First, add a new AuthGuard to the /admin route:

// app/app.routes.ts

import { ModuleWithProviders }         from '@angular/core';
import { Routes, RouterModule }        from '@angular/router';

import { HomeComponent }               from './home.component';
import { AdminComponent }              from './admin.component';
import { UnauthorizedComponent }       from './unauthorized.component';
import { AuthGuard }                   from './auth.guard';

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] },
  { path: 'unauthorized', component: UnauthorizedComponent },
  { path: '**', redirectTo: '' }
];

export const appRoutingProviders: any[] = [
  AuthGuard
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

To only allow users who have admin roles to access this route, check their status in the guard:

// app/auth.guard.ts

import { Injectable }             from '@angular/core';
import { Router,
         ActivatedRouteSnapshot,
         RouterStateSnapshot }    from '@angular/router';
import { CanActivate }            from '@angular/router';
import { Auth }                   from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private auth: Auth, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if(this.auth.authenticated()){
      if(this.auth.isAdmin()){
        return true;
      } else {
        this.router.navigate(['unauthorized']);
        return false;
      }
    } else {
      // Save URL to redirect to after login and fetching profile to get roles
      localStorage.setItem('redirect_url', state.url);
      this.auth.login();
      this.router.navigate(['']);
      return false;
    }
  }
}

The canActivate method checks if the user is authenticated and then checks if they are an admin using a new isAdmin function added to the Auth service. This method checks if the roles attribute of app_metadata added by the rule contains admin:

// app/auth.service.ts

public isAdmin() {
  return this.userProfile && this.userProfile.app_metadata
    && this.userProfile.app_metadata.roles
    && this.userProfile.app_metadata.roles.indexOf('admin') > -1;
}

Since the user's app_metadata is read-only for users, checking for their role in this fashion is secure.

After logging in successfully, the user will be redirected to the saved URL:

// app/auth.service.ts

// Fetch profile information
this.lock.getProfile(authResult.idToken, (error, profile) => {
  // ...

  // Redirect to the saved URL, if present.
  var redirectUrl: string = localStorage.getItem('redirect_url');
  if(redirectUrl != undefined){
    this.router.navigate([redirectUrl]);
    localStorage.removeItem('redirect_url');
  }
});

Now, if a user logs in with an email that contains @example, they will be allowed access to the /admin route.

Previous Tutorial
7. Rules
Next Tutorial
9. Calling APIs
Use Auth0 for FREECreate free Account