I have an Angular 7 app and an API in Java Spring with JTW. The app must at each request in the API send the token, but this is not happening, and so all requests return the 401 error.
app modules
...
@NgModule
({
declarations: [
AppComponent,
PatientComponent,
HeaderComponent,
FooterComponent,
AlertComponent,
NotFoundComponent,
UserRegisterComponent,
LoginComponent,
AuthGuardComponent
],
imports: [
BrowserModule,
FormsModule,
NgSelectModule,
ReactiveFormsModule,
HttpClientModule,
AppRoutingModule,
NgbModule,
],
providers: [
{
provide : HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi : true,
},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
AuthInterceptor
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private generalService: GeneralService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
}
});
console.log(req);
return next.handle(req);
}
}
Request
listAll() {
return this.http.get('http://localhost:8080/api/listAll');
}
async get() {
let error = null;
let response = await this.listAll()
.toPromise()
.catch(error => error = error);
console.log(response);
}
Result of console.log(req);
Looks like okay, the authorization and the token is there
The request
Dont pass the token here :c
Erros
OPTIONS 401 Access to XMLHttpRequest at'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I done the same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request.