Basic authentication with fetch?

夙愿已清 提交于 2019-11-26 10:25:50

问题


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:

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()
}

回答1:


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

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



回答2:


A solution without dependencies.

Node

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

Browser

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



回答3:


You can also use btoa instead of base64.encode().

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



回答4:


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(...);



回答5:


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

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);
   });



回答6:


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




回答7:


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'


来源:https://stackoverflow.com/questions/43842793/basic-authentication-with-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!