serhiisol / ngx-auth

Angular 16+ Authentication Module
MIT License
234 stars 47 forks source link

Authorization: 'Bearer ' does not add to http #15

Closed nimatrazmjo closed 6 years ago

nimatrazmjo commented 6 years ago

user.service.ts

import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptions, Response } from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import "rxjs/add/operator/do";
import "rxjs/add/operator/toPromise";
import { configuration } from "../../../../environments/.env";
import { User } from "./user";
import { UserWhere } from "./user-where";
import * as _ from "underscore";
import { AuthorizedHttp } from "../authentication/authorizedHttp.service";
import { Observable } from 'rxjs/Rx';
import { TokenService } from './../authentication/token.service';
import { Token } from './../authentication/token.model';
import { share } from "rxjs/operator/share";
import { HttpClient } from "@angular/common/http";

@Injectable()
export class UserService {
  token: Token;
  serverUrl = configuration.API_BASE_URL;
  constructor(
    private authHttp: HttpClient,
    private http: Http,
    private tokenService: TokenService
  ) {
    this.token = this.tokenService.getToken();
  }
  getUsersPage(
    page: number,
    perPage: number,
    where: UserWhere
  ): Observable<User[]> {

    const start: number = (page - 1) * perPage;
    let whereStr: string = this.makeWhereStrForList(where);
    let filterStr: string = `{"limit": ${perPage}, "skip": ${start}${whereStr
      ? ", " + whereStr
      : ""}}`;
    let url = `${this.serverUrl}/user/admin?filter=${filterStr}`;
    return this.authHttp
      .get(url)
      .share()

      .catch(this.handleError);
  }

It keeps refreshing.

serhiisol commented 6 years ago

your service should return proper status back to understand that error occurred because of the expired auth token, let's say it should return not just 401 but also error code, because 401 it's very generic status code which can mean that access token is expired and also refresh token, or they both invalid etc. So in your method, refreshShouldHappend you should carefully and correctly handle this case. Here's the real-world example:

public refreshShouldHappen(response: HttpErrorResponse): boolean {
    const responseCode: number = response.error.code;

    return response.status === 401 && [10001, 10002, 10003].indexOf(responseCode) >= 0;
}

So refresh request will happened in case if request status is 401 and error code can be one of those 10001, 10002, 10003 codes.

Plus just incase check example repo and see the other possible options, and don't forget to check again README.md file