简体   繁体   English

如何从 JWT 获取用户角色

[英]How to get user role from JWT

In my application I have 3 different roles, ADMIN, USER, TEACHER.在我的应用程序中,我有 3 个不同的角色,ADMIN、USER、TEACHER。 I log in and the REST API returns me the token.我登录,REST API 将令牌返回给我。 The problem is that I want to get the type of user it is, for example, if it is admin, but it is not working and I don't understand why.问题是我想获取它的用户类型,例如,如果它是管理员,但它不起作用,我不明白为什么。 The code i hace to detect if is an admin is我必须检测是否是管理员的代码是

public isAdmin(): boolean{
    if(!this.isLogged()){
      return false;
    }
    const token = this.getToken();
    const payload = token.split('.')[1];
    const decoded = window.atob(payload)
    const values = JSON.parse(decoded);
    const roles = values.sub;
    if(roles.indexOf('ROLE_ADMIN') < 0){
      return false;
    }
    return true;
  }

After this, what I want to do is to redirect to one route or another according to this role.在此之后,我想要做的是根据这个角色重定向到一个或另一个路由。 In addition to hide elements in the view with *ngIf(.isAdmin), I don't know if you can help me.除了用*ngIf(.isAdmin)隐藏视图中的元素,不知道你能不能帮帮我。 thanks.谢谢。

This is the header component这是 header 组件

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TokenService } from '../services/token.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {


  isAuthenticated = false;
  isAdmin = false;

  constructor(
    private tokenService: TokenService,
    private router: Router
  ) { }

  ngOnInit() {
    this.isLogged();
    this.isAdmin = this.tokenService.isAdmin();
  }

  onLogOut(): void{
    this.tokenService.logOut();
    this.router.navigate(['/']);
  }

  isLogged(): boolean{
    return this.isAuthenticated = this.tokenService.isLogged();
  }



}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">KanbanSense 2.0.</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent" *ngIf="isAdmin">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Inicio</a>
          </li>
          <li class="nav-item" >
            <a class="nav-link" href="#">Almacenes</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              Material
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="#">Buscar</a></li>
              <li><a class="dropdown-item" href="#">Stocks</a></li>
              <li><a class="dropdown-item" href="#">Informes</a></li>
            </ul>
          </li>
        </ul>
        <form class="d-flex me-2">
          <div *ngIf="!isLogged()">
            <button class="btn btn-primary" routerLink="/login">Login</button>
          </div>
          <div *ngIf="isLogged()">
            <button class="btn btn-danger" (click)="onLogOut()">Logout</button>
          </div>
        </form>
      </div>
    </div>
  </nav>

Thanks谢谢

I have a code error... In isAdmin doesn't exists sub.... I put roles and naw works.我有一个代码错误......在 isAdmin 中不存在子......我把角色和 naw 作品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM