【问题标题】:Angular5 Authentication to Api with jwtAngular5 使用 jwt 对 Api 进行身份验证
【发布时间】:2018-01-07 15:53:57
【问题描述】:

我有一个可通过 jwt 令牌访问的 api。

我有 postman 和 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 新手,不明白如何进行此身份验证调用。

谢谢

【问题讨论】:

  • 您需要一个授权标头:angular.io/guide/http#headers
  • 我认为这不是问题,因为该网址不受保护。通过更深入的调试,我发现我的 Api 收到了请求,但找不到凭据。
  • 贴出你的后端代码,也许问题出在那儿。
  • 授权标头与受保护的 URL 无关。这是您将 AWT 令牌传递给 API 的方式,以便它可以使用它来授权客户端应用程序。我确定 API 正在接收请求,但没有令牌:401 未授权。
  • 我可能误解了自己,我尝试访问的网址是登录页面。所以我没有令牌。我应该放一个空的授权标头吗?

标签: angular angular-httpclient


【解决方案1】:

这可能是因为 http.post 将内容发布为 json,但您的服务器期望 x-www-form-urlencoded(这是您使用 CURL -d 选项所做的)

您需要设置正确的标题

let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};

而且你需要设置正确的body。

您可以手动操作,也可以使用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)

【讨论】:

  • 您好,感谢您的宝贵时间。不幸的是,它不起作用。邮递员也可以。使用 Postman,成功的查询是在“原始数据”中,没有附加标题
  • 我已将邮递员成功查询的标题添加到我的帖子中
  • 你是对的。使用 urlencoded 标头,并将正文设置为字符串,它正在工作!谢谢
猜你喜欢
  • 2021-08-19
  • 2016-05-18
  • 2016-04-07
  • 2020-04-22
  • 2017-03-04
  • 2021-05-17
  • 2018-07-03
  • 2023-03-27
  • 2021-05-29
相关资源
最近更新 更多