Authorization bearer token Angular 5

旧时模样 提交于 2019-12-02 20:36:54
Nagy Gergő

I would suggest you to use an HTTPInteceptor which would take care of adding the token. Here is a great article to achieve that: https://www.illucit.com/angular/en-angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/

----- Another Way of solving the issue. -----

import { Http, Headers, Response } from '@angular/http';

getLoggedInUser(auth_token): Observable<any> {
    const headers = new Headers({
      'Content-Type': 'application/json',
      'Authorization': auth_token
    })
    return this.http.get(apiUrl, { headers: headers })
  } 

And do not forget to call and subscribe in your Component.

Two things:

  1. headers.append(...) does not mutate the headers object, so your authorization header is not being sent. You need to do headers = headers.append(...)

  2. Try this.http.get<UserList[]>(this.mainUrl, { headers: headers });

Hassan Rahman

For get requests, I used the following code and it works

import { HttpClient, HttpHeaders } from '@angular/common/http';

getServerList(){
    var reqHeader = new HttpHeaders({ 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('mpManagerToken'))
     });
    return this.http.get<Server[]>(`${environment.apiUrl}/api/Servers/GetServerList`, { headers: reqHeader });
}

In Angular 6 and 7, this method can be used to intercept all HTTP request and add the bearer token.

Implementation tutorial is available here. Youtube, this channel has all the tutorials.

Interceptor component

import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpUserEvent,
  HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from '../shared/user.service';
import { tap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private router: Router) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (req.headers.get('No-Auth') === 'True') {
      return next.handle(req.clone());
    }

    if (localStorage.getItem('userToken') != null) {
      const clonedreq = req.clone({
        headers: req.headers.set(
          'Authorization',
          'Bearer ' + localStorage.getItem('userToken')
        )
      });
      return next.handle(clonedreq).pipe(
        tap(
          succ => {},
          err => {
            if (err.status === 401) {
              // this.router.navigateByUrl('/login');
            } else if ((err.status = 403)) {
              // this.router.navigateByUrl('/forbidden');
              // alert(err.localStorage.getItem('userToken'));
            }
          }
        )
      );
    } else {
      this.router.navigateByUrl('/login');
    }
  }
}

Guard component

import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from '../shared/user.service';
import { ToastrService } from 'ngx-toastr';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private router: Router,
    private userService: UserService,
    private toastr: ToastrService
  ) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    if (localStorage.getItem('userToken') != null) {
      const roles = next.data['roles'] as Array<string>;
      if (roles) {
        const match = this.userService.roleMatch(roles);
        if (match) {
          return true;
        } else {
          // tslint:disable-next-line: quotemark
          this.toastr.info("You don't have access to this page");
          this.router.navigate(['/login']);
          // this.router.navigate(['/forbidden']);
          return false;
        }
      } else {
        return true;
      }
    }
    this.router.navigate(['/login']);
    return false;
  }
}

Add it to app.modules.ts

providers: [
    ConfirmationDialogService,
    UserService,
    DoctorService,
    { provide: OwlDateTimeIntl, useClass: DefaultIntl },
    { provide: OWL_DATE_TIME_FORMATS, useValue: MY_MOMENT_FORMATS },
    AuthGuard,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],

Then the guard is added to route

 {
    path: 'adminPanel',
    component: AdminPanelComponent,
    canActivate: [AuthGuard],
    data: { roles: ['Admin'] }
  },

I am not very good at programming,but with a little of try and failure if found this:

  getUserList(): Observable<UserList[]> {
    let tokenParse = JSON.parse(this.token)    
    // let myHeaders = new Headers();
    // myHeaders.set('Authorization', `Bearer ${tokenParse}`);
    // let options = new RequestOptions({ headers: myHeaders});
    const users = this.http.get<UserList[]>(this.mainUrl, { headers:new HttpHeaders().append('Authorization', `Bearer ${tokenParse}`)})
    // const users = this.http.get<UserList[]>(this.mainUrl, options);
    return users
            .catch(this.handleError.handleError);         
  }

It doesn't really matter if I use .set or .append, at the end of the day, it works in both cases...

I don't really know what is happening, so, if someone wants to explain it in the comments, you are welcome...

'Authorization': 'Bearer ' + access_token,

that worked

While @HassanRahman shows it for get requests, for post requests,

import { HttpClient, HttpHeaders } from '@angular/common/http';

getServerList(){

    postData = { your data }
    var reqHeader = new HttpHeaders({ 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('mpManagerToken'))
     });
    return this.http.get<Server[]>(`${environment.apiUrl}/api/Servers/GetServerList`, postData, { headers: reqHeader });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!