如何在本地存储中存储令牌并将其作为 Angular 中所有 API 中的承载者传递

问题描述 投票:0回答:1

这是我第一次构建登录,我从 API 调用获取用户数据,我需要一些帮助。

所以登录“工作流程”是这样的(我希望我描述得很好,如果需要更多说明,请发表评论)... 用户来到我的登录页面,他单击登录按钮,登录按钮转到一个外部 url,他在其中进行实际登录,并且登录并返回到我的页面,其中包含一些 JSON 数据(名称、令牌等)。 )该用户的,然后自动重定向到我的应用程序内。

所以我想要的是将这个令牌保存在本地存储中,并在应用程序内的每个其他 API 调用中发送这个令牌。

这是我的authentication.service.ts:

  isLoggedIn = false;
  redirectUrl: string | null = null;

  constructor(
    private http: HttpClient,
  ) { }

  login(): Observable<User> {
    const params = new HttpParams().append('param', 'value');
    return this.http.get<User>(`${environment.apiUrl}azure` + location.search, {params}).pipe(
      tap(() => (this.isLoggedIn = true))
    );
  }

这是我的login.component.ts:

  user: User;
  paramsObject: any;
  isLoggedIn = false;

  ngOnInit() {
    this.route.queryParamMap.subscribe(
      (params) => {
        this.paramsObject = { ...params.keys, ...params };
        console.log(this.paramsObject);
        
        if(this.route.snapshot.queryParamMap.get('code')) {
          this.authService.login().subscribe(
            data => {
              this.user = data;
              console.log('Izpis userja: ', data);
              if(this.user.token.length > 0) {
                console.log('Token exist: ', this.user.token);
                this.isLoggedIn = true;
                this.router.navigate(['/dashboard']);
              } else {
                console.log('Token does not exist');
                this.router.navigate(['/login']);
                return;
              }
            }
          )
        }
      })
  }

如果用户未在我的 auth.guard.ts 中登录,我想保护路由:

  const authService = inject(AuthenticationService);
  const router = inject(Router);

  if (authService.isLoggedIn) {
    return true;
  } else {
    return router.parseUrl('/login');
  }

这是一些数据的 API 调用,我想知道如何将其他服务中存储的令牌传递给 API 调用: 我想从 customer.service.ts 获取一些客户注释的 API 调用示例。我如何在这里传递这个令牌?

 getSingleCustomerNotes(id:number): Observable<CustomerNotes> {
    return this.httpClient.get<CustomerNotes>(`${environment.apiUrl}customer/${id}/notes`, {headers});
  }
javascript angular typescript authentication token
1个回答
0
投票

1-创建一个 auth.interceptor.ts 文件(可以将其放在 src 文件夹中)

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './services/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(
    req: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    if (req.headers.get('skip')) {
      req = req.clone({
        headers: req.headers.delete('skip'),
      });
      req = req.clone({
        setHeaders: {
          Accept: 'application/json',
          Authorization: `Bearer ${this.auth.getToken()}`,
          'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
          Pragma: 'no-cache',
          Expires: '0',
        },
      });
      return next.handle(req);
    }
    req = req.clone({
      setHeaders: {
        'Content-Type': 'application/json; charset=utf-8',
        Accept: 'application/json',
        Authorization: `Bearer ${this.auth.getToken()}`,
        'Cache-Control': 'no-cache',
        Pragma: 'no-cache',
        Expires: 'Sat, 01 Jan 2000 00:00:00 GMT',
      },
    });
    return next.handle(req);
  }
}

2- 在 app.module.ts 中 在providers数组中添加AuthInterceptor

import { AuthInterceptor } from './auth.interceptor';
import {
  HttpClientModule,
  HTTP_INTERCEPTORS,
  HttpClient,
} from '@angular/common/http';

@NgModule({
  declarations: [],
  imports: [],
  providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true,
      }],
      bootstrap: [AppComponent],
      entryComponents: [],
      exports: [],
})
export class AppModule {}

最后在您的服务中只需调用 http 服务并调用您的 api

  updateGamme(id, gamme) {
    return this.http.post(this.baseUrl + '/modifyGamme/' + id, gamme)
}

© www.soinside.com 2019 - 2024. All rights reserved.