繁体   English   中英

使用 jwt 对 Api 进行 Angular5 身份验证

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM