import {
HttpErrorResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { AuthServerProvider } from '../auth/auth-jwt.service';
import { LoginService } from '../service/login.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private loginService: LoginService,
private auth: AuthServerProvider
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = this.set_request_header(request);
return next.handle(request).pipe(
retry(1),
catchError((e: HttpErrorResponse) => {
this.handle_error(e);
return throwError(e);
})
);
}
private handle_error(e: HttpErrorResponse): void {
if (e.status === 401 || e.status === 0) {
this.loginService.logout();
}
}
private set_request_header(request: any): any {
if (!this.is_logar(request.url)) {
request = request.clone({
setHeaders: {
Authorization: 'bearer ' + this.auth.getToken(),
},
});
} else {
request = request.clone({
setHeaders: {
Authorization: 'bearer ' + this.auth.getToken(),
tipo_sistema: 'ROLE_CLIENTE',
},
});
}
return request;
}
private is_logar(url: any): boolean {
let validacaoUrl = url.indexOf('oauth-api/oauth/token');
return validacaoUrl != -1;
}
}
Assim dá erro
import {
HttpErrorResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { CLIENTE, SENHA } from '../api/erp.api';
import { AuthServerProvider } from '../auth/auth-jwt.service';
import { LoginService } from '../service/login.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private loginService: LoginService,
private auth: AuthServerProvider
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = this.set_request_header(request);
return next.handle(request).pipe(
retry(1),
catchError((e: HttpErrorResponse) => {
this.handle_error(e);
return throwError(e);
})
);
}
private handle_error(e: HttpErrorResponse): void {
if (e.status === 401 || e.status === 0) {
this.loginService.logout();
}
}
private set_request_header(request: any): any {
if (!this.is_logar(request.url)) {
request = request.clone({
setHeaders: {
Authorization: 'bearer ' + this.auth.getToken(),
},
});
} else {
request = request.clone({
setHeaders: {
Authorization: 'Basic ' + btoa(SENHA + ':' + CLIENTE),
},
});
}
return request;
}
private is_logar(url: any): boolean {
let validacaoUrl = url.indexOf('oauth-api/oauth/token');
return validacaoUrl != -1;
}
}
Assim não dá erro
Será que é no back ?
O que pode ser ?