简体   繁体   English

Angular 和 Laravel 如何在客户端管理用户权限

[英]Angular and Laravel how to manage user permissions on the client side

The code snippet below is an Angular service to authenticate a user using Laravel Sanctum:下面的代码片段是一个使用 Laravel Sanctum 对用户进行身份验证的 Angular 服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private baseURL = "http://localhost:8000/api";

  constructor(private http: HttpClient,public router: Router) { }

  login(username: string, password: string): Observable<boolean> {
    return this.http.post<{token: string}>(this.baseURL+'/login', {email: username, password: password})
      .pipe(
        map(result => {
          localStorage.setItem('access_token', result.token);
          return true;
        })
      );
  }

  getToken() {
    return localStorage.getItem('access_token');
  }

  logout() {
    let removeToken = localStorage.removeItem('access_token');

    if (removeToken == null) {
      this.router.navigate(['login']);
    }
  }

  public get isLoggedIn(): boolean {
    //TODO: Check token expiry and other security checks
    return (localStorage.getItem('access_token') !== null);
  }
}

My question is, if am using spatie permissions or Laravel Gates for authorization how can I store them on the frontend so that I can be able to show or hide menus based on what user is allowed to access?我的问题是,如果我使用 spatie 权限或 Laravel Gates 进行授权,我如何将它们存储在前端,以便我能够根据允许访问的用户显示或隐藏菜单?

DISCLAIMER: I'm used to developing applications using blade templates.免责声明:我习惯于使用刀片模板开发应用程序。 First time I'm switching to SPA.我第一次切换到SPA。

After authentication (successful login) you can manage your authorization (access right) via:身份验证(成功登录)后,您可以通过以下方式管理您的授权(访问权限):

If the component is accociated with a route, your need to protect the routes.如果组件与路由相关,则需要保护路由。 In this case use:在这种情况下使用:

  • Route Guards to protect accessing components under particular URL tree from unauthrized users. Route Guards以保护未经授权的用户访问特定 URL 树下的组件。

If the component is embedded in the view (like a button or section of a view under open or protected route) then you can:如果组件嵌入在视图中(例如打开或受保护路由下的按钮或视图部分),那么您可以:

  • Use property binding with [hidden]="condition" html property if you want to just hide an element from the UI but not from the DOM.如果您只想从 UI 中隐藏元素,而不是从 DOM 中隐藏元素,请使用带有[hidden]="condition" html 属性的属性绑定。
  • Use built-in Angular directive *ngIf="condition" if you want to hide or show an element in the UI and the DOM based on certain condition.如果要根据特定条件在 UI and DOM 中隐藏或显示元素,请使用内置的 Angular 指令*ngIf="condition"

Say you want to grant access to item A in menu only to Super_Admin users.假设您只想向Super_Admin用户授予对菜单中item A的访问权限。 You can do this:你可以这样做:

<ng-container *ngIf="rolePropertyFromAPI === 'Super_Admin'">Item A</ng-container>  

This is a big topic where you can find so much on-line.这是一个很大的话题,你可以在网上找到很多东西。 Check medium and Angular In-depth blog posts to know how to implement such strategies.查看中等和 Angular In-depth 博客文章以了解如何实施此类策略。 First step is of course the DOCS here第一步当然是这里的文档

For storing access credits like the 'Super_Admin' above it is a pretty straightforward.对于存储像上面的“Super_Admin”这样的访问信用非常简单。 You have three options here:您在这里有三个选择:

The optimal one from easy of access and durability is localStorage API.易于访问和持久性的最佳选择是 localStorage API。 However it is not that safe.然而,它并不那么安全。 It does the job for you though.不过,它可以为您完成工作。

The most advanced and tricky one is to store the credentials in the application state using Observables for example.最先进和最棘手的一种方法是使用 Observables 将凭据存储在应用程序状态中。

With localStorage:使用本地存储:

1- you accesss your API endpoint response 1-您访问您的 API 端点响应

2- set the property in the browser storage 2-在浏览器存储中设置属性

localStorage.setItem('Super_Admin', JSON.stringify(valueFromBackendEnd))

3- get the value by the key stored with 3-通过存储的键获取值

localStorage.getItem('Super_Admin')

4- clear the storage. 4-清除存储。

localStorage.removeItem('Super_Admin')

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

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