Javascript 使用 fetch 进行基本身份验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43842793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:12:03  来源:igfitidea点击:

Basic authentication with fetch?

javascriptfetch-api

提问by daniel.lozynski

I want to write a simple basic authentication with fetch, but I keep getting a 401 error. It would be awesome if someone tells me what's wrong with the code:

我想用 fetch 编写一个简单的基本身份验证,但我一直收到 401 错误。如果有人告诉我代码有什么问题,那就太棒了:

let base64 = require('base-64');

let url = 'http://eu.httpbin.org/basic-auth/user/passwd';
let username = 'user';
let password = 'passwd';

let headers = new Headers();

//headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));

fetch(url, {method:'GET',
        headers: headers,
        //credentials: 'user:passwd'
       })
.then(response => response.json())
.then(json => console.log(json));
//.done();

function parseJSON(response) {
return response.json()
}

采纳答案by Lukasz Wiktor

You are missing a space between Basicand the encoded username and password.

您在Basic和 编码的用户名和密码之间缺少空格。

headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

回答by qoomon

A solution without dependencies.

一个没有依赖关系的解决方案。

Node

节点

headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));

Browser

浏览器

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

回答by Ilya

You can also use btoainstead of base64.encode().

您也可以使用btoa代替 base64.encode()。

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

回答by OZZIE

If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:

如果您有一个后端服务器在应用程序之前要求提供基本身份验证凭据,那么这就足够了,它将重新使用它:

fetch(url, {
  credentials: 'include',
}).then(...);

回答by Manoj Perumarath

I'll share a code which has Basic Auth Header form data request body,

我将分享一个具有 Basic Auth Header 表单数据请求正文的代码,

let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();


formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');

headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
 method: 'POST',
 headers: headers,
 body: formdata
}).then((response) => response.json())
.then((responseJson) => {
 console.log(responseJson);

 this.setState({
    data: responseJson
 })
  })
   .catch((error) => {
 console.error(error);
   });

回答by kumar kundan

NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS

节点用户(反应、表达)遵循这些步骤

  1. npm install base-64 --save
  2. import { encode } from "base-64";
  3.  const response = await fetch(URL, {
      method: 'post',
      headers: new Headers({
        'Authorization': 'Basic ' + encode(username + ":" + password),
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({
        "PassengerMobile": "xxxxxxxxxxxx",
        "Password": "xxxxxxx"
      })
    });
    const posts = await response.json();
    
  4. Don't forget to define this whole function as async

  1. npm install base-64 --save
  2. import { encode } from "base-64";
  3.  const response = await fetch(URL, {
      method: 'post',
      headers: new Headers({
        'Authorization': 'Basic ' + encode(username + ":" + password),
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({
        "PassengerMobile": "xxxxxxxxxxxx",
        "Password": "xxxxxxx"
      })
    });
    const posts = await response.json();
    
  4. 不要忘记将整个函数定义为 async

回答by kolypto

A simple example for copy-pasting into Chrome console:

复制粘贴到 Chrome 控制台的简单示例:

fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));

回答by DJ-Glock

This is not directly related to the initial issue, but probably will help somebody.

这与最初的问题没有直接关系,但可能会对某人有所帮助。

I faced same issue when was trying to send similar request using domain account. So mine issue was in not escaped character in login name.

我在尝试使用域帐户发送类似请求时遇到了同样的问题。所以我的问题是登录名中没有转义字符。

Bad example:

不好的例子:

'ABC\username'

Good example:

好的例子:

'ABC\username'