Role based login

Hi all, I need a little help as I’m trying to achieve a role-based authentication and unable to figure it out. I’m confused on how will I post the username and password to the backend i.e a php api and get the status and if the status gives me role==0 then the login will go to the admin otherwise if the role==1 it will navigate to the user page.
Below is the code I’m using:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = '';
export interface User {
  name: string;
  role: number;
  Generated class for the AuthProvider provider.

  See for more info on providers
  and Angular DI.
export class AuthProvider {
  currentUser: User;
  constructor(public http: Http) { }
  login(name: string, pw: string) : Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (name === 'admin' && pw === 'admin') {
        this.currentUser = {
          name: name,
          role: 0
      } else if (name === 'user' && pw === 'user') {
        this.currentUser = {
          name: name,
          role: 1
      } else {
  isLoggedIn() {
    return this.currentUser != null;
  isAdmin() {
    return this.currentUser.role === 0;
  logout() {
    this.currentUser = null;

There isn’t a universal answer to how to deal with roles in an Ionic application, but JWTs (JSON Web Tokens) can be extremely useful for this. You will need to decide on some kind of implementation for the backend (and I would highly recommend using an existing solution rather than writing your own system), but you might like to choose a solution that allows for the use of a JWT.

You can’t do something like you are describing above because you are setting the “role” value in the client side code. Any user could easily just change that value to make themselves an admin. The benefit of a JWT is that you have a chunk of data stored locally that you can verify hasn’t been modified. That means you could store the users role inside of the JWT, verify its authenticity with your server, and then rely on whatever information is in there (knowing that it isn’t possible for a user to modify that JWT to give themselves admin privileges for example). An important thing to note is that JWTs just have basic encoding, the point isn’t to store sensitive informations like passwords in them, the point is that the data can’t be changed/forged by the user.

I wrote this blog post a long time ago, but it still has a lot of relevant information should you choose to go down the JWT route:

1 Like