Home > Back-end >  Angular - AuthService Claiming Admin Role
Angular - AuthService Claiming Admin Role

Time:11-17

Im trying add administration menu for my Angular project. When Im doing that I wan't to check the user is an admin or not? So i have a method for that such as;

 isAdmin() {
    
    if (!this.loggedIn()) return false;

    let decodedToken = this.getDecodedToken;

    let roleString = Object.keys(decodedToken).filter((t) =>
      t.endsWith('/role')
    )[0];

    if (roleString)
      for (let i = 0; i < decodedToken[roleString].length; i  )
        if (decodedToken[roleString][i] === AdminRole) return true;

    return false;
  }

AdminRole is an const string so Its equals 'admin'

get getDecodedToken() {
    let token = this.getToken;
    return this.jwtHelperService.decodeToken(token);
  }

But as i understand problem is this method won't see AdminRole in my JWT Token, it looks like this;

"eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTUxMiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjUwMDIiLCJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJhZG1pbiBhZG1pbiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6ImFkbWluIiwibmJmIjoxNjY4MzU4MDM3LCJleHAiOjE2NjgzNTk4MzcsImlzcyI6ImZhdGloQGZhdGloLmNvbSIsImF1ZCI6ImZhdGloQGZhdGloLmNvbSJ9.eRgpq_zlflyk4s3AaUZtx88atr8hPIV0VHRRRqKRM5V_mTqAVmDAl-v4euFmIyDjKWLSgzQXXamOThsfwwUTjg"

But to check if this key is working or not, Its working well...

if (
  this.getToken ==
  "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTUxMiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjUwMDIiLCJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJhZG1pbiBhZG1pbiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6ImFkbWluIiwibmJmIjoxNjY4MzU4MDM3LCJleHAiOjE2NjgzNTk4MzcsImlzcyI6ImZhdGloQGZhdGloLmNvbSIsImF1ZCI6ImZhdGloQGZhdGloLmNvbSJ9.eRgpq_zlflyk4s3AaUZtx88atr8hPIV0VHRRRqKRM5V_mTqAVmDAl-v4euFmIyDjKWLSgzQXXamOThsfwwUTjg"
) {
  return true;
} else {
  return false;
}

I apologize Im new at Angular, Im trying to learn that technology.

Im trying to figure out how can i make my Jwt service to see that admin role.

Thanks...

CodePudding user response:

I think its due to the for loop can you change it like below?

isAdmin() {
    if (!this.loggedIn()) return false;
    const decodedToken = this.getDecodedToken;
    const roleString = Object.keys(decodedToken).filter((t) =>
      t.endsWith('/role')
    )[0];
    if (roleString) {
        return decodedToken[roleString].includes('admin'); // <--- changed here
    }
    return false;
  }
  • Related