在我的角度应用程序中,我向后端服务器的端点/ api / token发送一个http GET请求,如下所示,并接收该令牌。
backend.service.ts
authenticate(userName: String, passwd: String){
this.myHttpclient.get(AppSettings.API_ENDPOINT + "token", {responseType: 'text'}).subscribe(res=>{
this.isLoggedIn = true;
this.receivedJWT = res;
localStorage.setItem('access_token', res);
console.log("Token saved = " + localStorage.getItem('access_token'));
this.router.navigate(['home'])
},
errorResponse=>{
console.log("token err= " + JSON.stringify(errorResponse));
this.serverError = errorResponse["error"];
setTimeout(() => {
this.serverError = null;
}, 3000);
this.router.navigate([''])
})
}
登录时,我看到带有令牌的“令牌已保存=”日志。
在以下方法中,我将在登录后进行一次HTTP POST
backend.service.ts
createNewPage(title:string, content:string){
this.myHttpclient.post('http://127.0.0.1:8080/api/pages',
{
name : title,
markdown : content
}
).subscribe(res=>{
if (res['success'] === true)
{
this.saveResult = "Saved Successfully";
this.router.navigate(['home']);
}
else
{
this.saveResult = "Save Failed";
}
});
}
我的 app.module.ts 具有以下导入内容,以支持angular-jwt
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
HttpClientModule,
MaterialModule,
FlexLayoutModule,
FormsModule,
MatInputModule,
JwtModule.forRoot({
config: {
tokenGetter: function tokenGetter() {
console.log("tokenGetter called = " + localStorage.getItem('access_token') )
return localStorage.getItem('access_token');
},
whitelistedDomains: ['http://127.0.0.1:8080'],
blacklistedRoutes:['http://127.0.0.1:8080/api/token/']
}
})
]
尽管端点在白名单中,但我的POST并没有在标头中标记JWT令牌。
它给出以下错误
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://127.0.0.1:8080/api/pages", ok: false, …}
error: "Unauthorized"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://127.0.0.1:8080/api/pages: 401 Unauthorized"
name: "HttpErrorResponse"
ok: false
status: 401
statusText: "Unauthorized"
url: "http://127.0.0.1:8080/api/pages"
__proto__: HttpResponseBase
并且请求标头包含以下字段,但不包含“授权”
Accept: application/json, text/plain, */*
Content-Type: application/json
Origin: http://localhost:4200
Referer: http://localhost:4200/createPage?title=title%201&new=true
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Mobile Safari/537.36
我不知道这里出了什么问题。即使JWT也会按照日志进行接收和存储,据我了解,要使令牌打包在请求中,我已经完成了所有必需的操作。但仍然没有。
在这里我想念什么吗?请帮助
我正在使用的angular-jwt版本是@ auth0 / angular-jwt @ 2.1.0
答案 0 :(得分:1)
在白名单中添加没有http://或https://
的网址