简体   繁体   English

使用 Angular 服务将基本身份验证传递给 rest api

[英]pass basic auth to rest api using angular services

I want to log in with authentication in angular but while sending data from services to an express rest API it will show a 401 unauthorized error.我想以 angular 身份验证登录,但是在将数据从服务发送到 express rest API 时,它会显示 401 未经授权的错误。

login(data) {
  console.log(data);
  const headers_object = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded');

  headers_object.append('Authorization', 'Basic ' + btoa(data.email + ':' + data.password));

  return this.Httpclient.post('http://api/auth', data, {
    headers: headers_object
  })
  .pipe(map((res: Response) => {
    return res.json();
  }));

}

I used an express passport in rest API我在rest API中使用了快速护照

Request URL: http://api/auth
Request Method: POST
Status Code: 401 Unauthorized
Remote Address:api
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: bugsnag-api-key,bugsnag-payload-version,bugsnag-sent-at,content-type
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: *
Allow: POST, GET, OPTIONS, PUT, DELETE
Connection: keep-alive
Date: Wed, 26 Dec 2018 16:13:13 GMT
Transfer-Encoding: chunked
WWW-Authenticate: Bearer realm="Users"
X-Powered-By: Express
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
Origin: http://localhost:4200
Referer: http://localhost:4200/login
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
{"email":"","password":"","access_token":""}: 

Express api Handler for login authentication of post method用于post方法登录认证的Express api Handler

import { Router } from 'express'
import { login } from './controller'
import { password, master, facebook, github, google } from '../../services/passport'

const router = new Router()

/**
 * @api {post} /auth Authenticate
 * @apiName Authenticate
 * @apiGroup Auth
 * @apiPermission master
 * @apiHeader {String} Authorization Basic authorization with email and password.
 * @apiParam {String} access_token Master access_token.
 * @apiSuccess (Success 201) {String} token User `access_token` to be passed to other requests.
 * @apiSuccess (Success 201) {Object} user Current user's data.
 * @apiError 401 Master access only or invalid credentials.
 */
router.post('/',
  master(),
  password(),
  login)

append() doesn't modify the headers. append()不会修改标题。 It creates a new HttpHeaders object and returns it.它创建一个新的HttpHeaders对象并返回它。 So you need所以你需要

let headers_object = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded');
headers_object = headers_object.append(...);

or simply或者干脆

const headers_object = new HttpHeaders().append(...)
                                        .append(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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