AngularJS:401-未经授权:具有基本身份验证的HttpInterceptor

时间:2018-09-12 10:20:46

标签: angularjs http-basic-authentication

我想打电话给Rest-Service(Spring MVC)以接收发布列表。在客户端(AngularJs),我使用服务创建HttpClient调用。我还注册了HttpInterceptor来使用简单的基本身份验证。拦截器在app.modules.ts中提供,在其余调用期间被调用

不幸的是,我收到状态码401,但无法在标题中找到“身份验证”条目。缺少什么?

拦截器:

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

@Injectable()
export class BasicAuthInterceptor implements HttpInterceptor {


  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  request = request.clone({
    setHeaders: {
      Authorization: `Basic username:password`
    },
  }); 


  return next.handle(request);
  }
}

服务类别:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs/';
import { HttpClient } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { Release } from './Release';

@Injectable()
export class ReleasesService {

  constructor(
    private http: HttpClient) {}

  private releasesUrl = 'http://localhost:8080/releases/showAll';

  getReleases(): Observable<Release[]> {
    return this.http
      .get<Release[]>(this.releasesUrl)
      .pipe( tap(releases => this.log('fetched releases')),
         catchError(this.handleError('getReleases', [])));
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error); // log to console instead
      return of(result as T);
   };
  }

  private log(message: string) {
    console.info(message);
  }
}

app.modules.ts

  providers: [
      APP_PROVIDERS,
     { provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true },
  ],

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。

设置标题正确。但是我必须在HttpClient调用中添加以下参数: {withCredentials:true}

getReleases(): Observable<Release[]> {
return this.http
  .get<Release[]>(this.releasesUrl, { withCredentials: true })
  .pipe( tap(releases => this.log('fetched releases')),
     catchError(this.handleError('getReleases', [])));

}

然后将凭据传递到服务器。