使用 AuthHttp 时出现错误,但身份验证返回一个好的令牌。我在https://jwt.io/上验证了它,它很好。
我正在使用 Angular 4。我的代码如下:
登录代码
signIn(login: string, password: string) {
this.UserLogin.name = login;
this.UserLogin.password = password;
this.http.post(this.baselink + '.json', this.UserLogin, { headers: contentHeaders })
.subscribe(
response => {
localStorage.setItem('id_toke', response.json().token);
this.jwt = localStorage.getItem('id_toke');
this.decodedJwt = this.jwtHelper.decodeToken(this.jwt);
this.userRole = this.decodedJwt.roles;
console.log(this.userRole);
this.useJwtHelper();
this.router.navigate(['/']);
},
error => {
console.log('Http Error ' + error.text());
this.router.navigate(['http-error']);
}
);
}
token ![enter image description here] 1 :"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInJvbGVzIjpbInJlYWQtb25seSIsInJlYWQtd3JpdGUiXSwiaWF0IjoxNDk2MTkxNDg4LCJleHAiOjE0OTYyMDAwODh9.qPCQY3yHujuCLb9g-F5b0MUQO3tyTr_Y5YRoMOQ0DBA"
然而获取数据抛出错误
getPayments() {
return this.authHttp.get(this.baselink + '/getPayments', { headers: contentHeaders })
.map(
(response: Response) => {
const data = response.json();
return data;
}
)
.catch(
(error: Response) => {
console.log('Error getPayments: ' + error);
return Observable.throw('Something went wrong: ' + error.text);
}
);
}
并得到
错误 getPayments:错误:JWT 必须有 3 个部分
话虽如此,如果我return this.http.get(this.baselink + '/getPayments')
改用它,它会起作用。AuthHttp 的连接没有到达服务器。该特定控制器暂时不受服务器限制,但目的是保护它,可能令牌不包含在 AuthHttp 标头中
@NgModule({
providers: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
]
})
export class AuthorizationModule { }
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'bearer',
tokenName: 'token',
tokenGetter: (() => localStorage.getItem('id_token')),
globalHeaders: [{ 'Content-Type': 'application/json' }],
noJwtError: true
}), http, options);
}
和全局标题
export const contentHeaders = new Headers();
contentHeaders.append('Accept', 'application/json');
contentHeaders.append('Content-Type', 'application/json');