Angular 如何向http请求添加授权标头?
这是我的第一篇文章 我刚刚开始学习Go和Angular,我正在尝试将Angular应用程序连接到Go api。我已经写了这两篇文章,并且一直在寻找问题的根源。我认为这是一个CORS问题,但如果在我的角度http请求中不包含头行代码,它就可以正常工作。在这一点上,我只是想添加标题。授权代码尚未实现 这两个应用程序都在本地运行,Go应用程序位于端口5000,Angular应用程序位于端口4200 无法工作的角度http请求:Angular 如何向http请求添加授权标头?,angular,go,gorilla,Angular,Go,Gorilla,这是我的第一篇文章 我刚刚开始学习Go和Angular,我正在尝试将Angular应用程序连接到Go api。我已经写了这两篇文章,并且一直在寻找问题的根源。我认为这是一个CORS问题,但如果在我的角度http请求中不包含头行代码,它就可以正常工作。在这一点上,我只是想添加标题。授权代码尚未实现 这两个应用程序都在本地运行,Go应用程序位于端口5000,Angular应用程序位于端口4200 无法工作的角度http请求: this.http.get<ProjectedBalance>
this.http.get<ProjectedBalance>(requestUrl, {headers: new HttpHeaders().set('Authorization', 'my-auth-token')})
.subscribe(data => {
this.projBalance = data.projBalance;
}
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>4中处理身份验证头的最佳方法,最好使用
Http拦截器
用于将它们添加到每个请求中,然后使用防护装置
用于保护您的路线
下面是我在应用程序中使用的AuthInterceptor
的完整示例:
auth.interceptor.ts
您可以在本文中进一步了解此方法
关于《围棋》,这很可能是《围棋》与《围棋》之间的不匹配 您正在发送的请求标头以及标头CORS允许。
您应该尝试的第一件事是允许所有这些:
headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
如果问题消失了,请尝试仔细地将您的COR一个接一个地组织到您的客户发送的内容中。如果您不想添加拦截器,这对我很有用:
var header = {
headers: new HttpHeaders()
.set('Authorization', `Basic ${btoa(AuthService.getToken())}`)
}
this.http.get(url, header)
对于持票人
set('Authorization', `Bearer ${AuthService.getToken()}`)
Angular 6==>带有授权头的HTTP Get请求示例
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);
}
下面的示例适合这样一种情况:只有在访问需要授权的资源时才需要添加一些头,请参见下面的代码。请注意,您需要在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);
}
}
}
考虑以问题的形式重新整理你的帖子……我不知道为什么<代码>处理程序。CORS 不起作用,但是如果你不使用CORS,你就需要代理你的开发请求到端口5000。在生产环境中,您将在端口80上运行,因此没有冲突,但由于您使用angular的开发服务器并在本地运行go服务器,
localhost:4200
和localhost:5000
是不同的来源。我不确定“angular 5 way”是怎么做的,但是webpack dev server
在package.json
中有一个超简单的proxy
字段,您基本上想复制它。您好,gobuckeyes,您能给我一份您的客户端在请求API时发送的头列表吗(从开发工具的“网络”选项卡)。如果将所有3个COR设置为{“*”}
,问题是否仍然存在?@Mihailo我发布了开发工具中的标题。将所有3个COR更改为{“*”}将错误更改为405-不允许使用的方法。感谢您关闭AllowedMethods()
返回到原来的状态。应该有2个来自客户的请求,一个具有方法选项
,另一个应该是GET
(对于此特定情况)请求。在还原AllowedMethods
后,再次尝试发送请求,如果错误仍然存在,则使用GET
请求中的数据更新问题。这对在Angular应用程序中添加标题起到了作用。谢谢!对于Go piece,我能够使用这种方法。整洁!很高兴我能提供一些帮助:)祝你好运!
var header = {
headers: new HttpHeaders()
.set('Authorization', `Basic ${btoa(AuthService.getToken())}`)
}
this.http.get(url, header)
set('Authorization', `Bearer ${AuthService.getToken()}`)
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);
}
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);
}
}
}
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 {}