[英]Angular5 Authentication to Api with jwt
我有一個可通過 jwt 令牌訪問的 api。
我有郵遞員和 curl 的預期結果( curl -X POST http://localhost/api/login_check -d _username=login -d _password=pass
)但不是 angular。
郵遞員成功的標頭請求:
POST /api/login_check
cache-control: no-cache
postman-token: 2b4a6be8-5c3d-4c66-99f9-daa49572d4bf
user-agent: PostmanRuntime/7.1.1
accept: */*
host: localhost
cookie: PHPSESSID=06u39ri0rr2i2sgdkjr451d6tj
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------825758704558259093486061
content-length: 287
這是我的配置:
Angular CLI: 1.5.5
Node: 9.2.0
OS: linux x64
Angular: 5.1.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.5.5
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.5
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.11
typescript: 2.4.2
webpack: 3.8.1
這是我的服務:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const API_URL = 'http://localhost/api';
@Injectable()
export class SecurityService {
constructor(private http: HttpClient) {
}
login(username: string, password: string) {
let url = `${API_URL}/login_check`;
return this.http.post(
url,
{_username: username, _password: password },
).subscribe(
(response) => {
console.log(response);
}
);
}
}
此調用返回 401 錯誤,憑據無效。 我曾嘗試使用 contentType: 'application/x-www-form-urlencoded' 添加標題,但仍然出現相同的錯誤。
我是 Angular 的新手,不明白如何進行這個身份驗證調用。
謝謝
這可能是因為 http.post 將內容發布為 json,但您的服務器期待 x-www-form-urlencoded (這就是您使用 CURL -d 選項所做的)
您需要設置正確的標題
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
你需要設置正確的身體。
您可以手動完成,也可以使用URLSearchParams
let body = new URLSearchParams();
body.set('_username', username);
body.set('_password', password);
this.http.post(this.loginUrl, body.toString(), options)
如果要手動設置主體,請使用
let body = '_username=username&_password=password';
this.http.post(this.loginUrl, body, options)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.