如何将授权 Header 添加到 Angular http 请求?
How to add Authorization Header to Angular http request?
这是我的第一个post。
我刚刚开始学习 Go 和 Angular,我正在尝试将 angular 应用程序连接到 Go api。我已经写了两个并且无法确定问题的根源。我认为这是一个 CORS 问题,但如果我不在我的 Angular http 请求中包含 headers 代码行,它就可以正常工作。此时我只是想添加 header。授权码尚未实现。
这两个应用程序都是 运行 本地的,Go 应用程序在端口 5000 上,Angular 在 4200 上
Angular 无效的 http 请求:
this.http.get<ProjectedBalance>(requestUrl, {headers: new HttpHeaders().set('Authorization', 'my-auth-token')})
.subscribe(data => {
this.projBalance = data.projBalance;
}
Angular 有效的 http 请求:
this.http.get<ProjectedBalance>(requestUrl)
.subscribe(data => {
this.projBalance = data.projBalance;
}
我收到此错误:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access. The response had HTTP status code 403
我在 go 代码中使用 gorilla/mux 和 gorilla/handlers
router := mux.NewRouter()
router.HandleFunc("/home/{endDate}", GetProjBalance).Methods("GET", "OPTIONS")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With, Content-Type, Authorization"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
//start server on port
log.Fatal(http.ListenAndServe(":5000", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
Headers 来自 Chrome 开发工具
Request URL:http://localhost:5000/home/2020-12-21
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:[::1]:5000
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Content-Length:0
Content-Type:text/plain; charset=utf-8
Date:Mon, 20 Nov 2017 21:39:43 GMT
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,uz;q=0.8
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:5000
Origin:http://localhost:4200
这是一个例子:
this.http
.get(url, return new RequestOptions({
headers: new Headers({
Authorization: `Bearer ${authtoken}`
}),
}))
.map(res => res.json());
关于在 Angular 中处理身份验证的最佳方式 headers > 4 最好使用
Http Interceptors
将它们添加到每个请求中,然后使用
Guards
用于保护您的路线。
这是我在我的应用程序中使用的 AuthInterceptor
的完整示例:
auth.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
'Authorization': `Bearer ${AuthService.getToken()}`,
},
});
return next.handle(req);
}
}
您需要在 app.module
中将您的拦截器注册为提供商:
app.module.ts
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptor } from '../auth/auth.interceptor';
...
imports: [
HttpClientModule,
...
],
providers: [
{
provide : HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi : true,
},
...
],
...
您可以在 post 中进一步了解此方法。
关于 Go 方面,这很可能是
之间不匹配的情况
请求 Headers 您正在发送并且 headers CORS 允许。
您应该尝试的第一件事是允许所有这些:
headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
如果问题消失,请尝试仔细构建您的 CORS 一个一个到您的客户发送的内容。
如果你不想添加拦截器,这对我有用:
var header = {
headers: new HttpHeaders()
.set('Authorization', `Basic ${btoa(AuthService.getToken())}`)
}
this.http.get(url, header)
对于 Bearer,
set('Authorization', `Bearer ${AuthService.getToken()}`)
Angular 6 ==> 带授权的 HTTP Get 请求示例 Header
public IsClientCreditCardExits(companyId: string, token: any) {
let header = new Headers({ 'Authorization': `Bearer ${token}` });
const options = new RequestOptions({
headers: header,
});
return this._http.get(this.ApiURL + "api/Subscriptions/IsClientCreditCardExits/" + companyId + "/", options);
}
以下示例适用于您只希望在访问需要授权的资源时添加一些 headers 的情况,请参阅下面的代码。请注意,您需要在 authentication.service.ts.
中创建 getToken 方法
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { AuthenticationService } from '../services/authentication.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticationInterceptorService implements HttpInterceptor {
constructor(public authenticationService: AuthenticationService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const accessToken: string = this.authenticationService.getToken();
// set global application headers.
request = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
'X-AppName': environment.xAppName,
'X-Locale': 'en'
}
});
// Set headers for requests that require authorization.
if (accessToken) {
const authenticatedRequest = request.clone({
headers: request.headers.set(
'Authorization',
`Token token=${accessToken}`
)
});
// Request with authorization headers
return next.handle(authenticatedRequest);
} else {
// Request without authorization header
return next.handle(request);
}
}
}
在app.module.ts中注册拦截器,如下所示:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AuthenticationInterceptorService } from './services/authentication-interceptor.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
这是我的第一个post。
我刚刚开始学习 Go 和 Angular,我正在尝试将 angular 应用程序连接到 Go api。我已经写了两个并且无法确定问题的根源。我认为这是一个 CORS 问题,但如果我不在我的 Angular http 请求中包含 headers 代码行,它就可以正常工作。此时我只是想添加 header。授权码尚未实现。
这两个应用程序都是 运行 本地的,Go 应用程序在端口 5000 上,Angular 在 4200 上
Angular 无效的 http 请求:
this.http.get<ProjectedBalance>(requestUrl, {headers: new HttpHeaders().set('Authorization', 'my-auth-token')})
.subscribe(data => {
this.projBalance = data.projBalance;
}
Angular 有效的 http 请求:
this.http.get<ProjectedBalance>(requestUrl)
.subscribe(data => {
this.projBalance = data.projBalance;
}
我收到此错误:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403
我在 go 代码中使用 gorilla/mux 和 gorilla/handlers
router := mux.NewRouter()
router.HandleFunc("/home/{endDate}", GetProjBalance).Methods("GET", "OPTIONS")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With, Content-Type, Authorization"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
//start server on port
log.Fatal(http.ListenAndServe(":5000", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
Headers 来自 Chrome 开发工具
Request URL:http://localhost:5000/home/2020-12-21
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:[::1]:5000
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Content-Length:0
Content-Type:text/plain; charset=utf-8
Date:Mon, 20 Nov 2017 21:39:43 GMT
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,uz;q=0.8
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:5000
Origin:http://localhost:4200
这是一个例子:
this.http
.get(url, return new RequestOptions({
headers: new Headers({
Authorization: `Bearer ${authtoken}`
}),
}))
.map(res => res.json());
关于在 Angular 中处理身份验证的最佳方式 headers > 4 最好使用
Http Interceptors
将它们添加到每个请求中,然后使用
Guards
用于保护您的路线。
这是我在我的应用程序中使用的 AuthInterceptor
的完整示例:
auth.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
'Authorization': `Bearer ${AuthService.getToken()}`,
},
});
return next.handle(req);
}
}
您需要在 app.module
中将您的拦截器注册为提供商:
app.module.ts
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptor } from '../auth/auth.interceptor';
...
imports: [
HttpClientModule,
...
],
providers: [
{
provide : HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi : true,
},
...
],
...
您可以在 post 中进一步了解此方法。
关于 Go 方面,这很可能是
之间不匹配的情况
请求 Headers 您正在发送并且 headers CORS 允许。
您应该尝试的第一件事是允许所有这些:
headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
如果问题消失,请尝试仔细构建您的 CORS 一个一个到您的客户发送的内容。
如果你不想添加拦截器,这对我有用:
var header = {
headers: new HttpHeaders()
.set('Authorization', `Basic ${btoa(AuthService.getToken())}`)
}
this.http.get(url, header)
对于 Bearer,
set('Authorization', `Bearer ${AuthService.getToken()}`)
Angular 6 ==> 带授权的 HTTP Get 请求示例 Header
public IsClientCreditCardExits(companyId: string, token: any) {
let header = new Headers({ 'Authorization': `Bearer ${token}` });
const options = new RequestOptions({
headers: header,
});
return this._http.get(this.ApiURL + "api/Subscriptions/IsClientCreditCardExits/" + companyId + "/", options);
}
以下示例适用于您只希望在访问需要授权的资源时添加一些 headers 的情况,请参阅下面的代码。请注意,您需要在 authentication.service.ts.
中创建 getToken 方法import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { AuthenticationService } from '../services/authentication.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticationInterceptorService implements HttpInterceptor {
constructor(public authenticationService: AuthenticationService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const accessToken: string = this.authenticationService.getToken();
// set global application headers.
request = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
'X-AppName': environment.xAppName,
'X-Locale': 'en'
}
});
// Set headers for requests that require authorization.
if (accessToken) {
const authenticatedRequest = request.clone({
headers: request.headers.set(
'Authorization',
`Token token=${accessToken}`
)
});
// Request with authorization headers
return next.handle(authenticatedRequest);
} else {
// Request without authorization header
return next.handle(request);
}
}
}
在app.module.ts中注册拦截器,如下所示:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AuthenticationInterceptorService } from './services/authentication-interceptor.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}