Skip to content
Advertisement

Basic Auth Send API_KEY to php api – REACTJS

I am sending the username and password to the PHP api with the API_KEY in the .env file. How do I get the user name before the semicolon as the password after the comma in Api? I could not run it with the current code I wrote. I’m using basic auth

.env

API_KEY=...:...

REACT CODE

import {decode as atob, encode as btoa} from 'base-64'
import { API_KEY } from 'dotenv'
import axios from 'axios';

axios.get('...php', { crossdomain: true } , {

 headers: {
  "Access-Control-Allow-Origin": "*",
  'Authorization': 'Basic ' + `${btoa(`${API_KEY}`)}`           
 }
})
      .then(res => { ... })

PHP

 $AUTH_USER = '...';
 $AUTH_PASS = '...';

            if (! empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
            {
                preg_match('/^Basics+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $AUTH_PASS);
                
                $str = base64_decode($AUTH_PASS[1]);
                
                list( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) = explode(':', $str);
            }

            $has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));

            $is_not_authenticated = (
                !$has_supplied_credentials ||
                $_SERVER['PHP_AUTH_USER'] != $AUTH_USER || $_SERVER['PHP_AUTH_PW']   != $AUTH_PASS
            );

            if ($is_not_authenticated) {
                header('HTTP/1.1 401 Authorization Required');
                header('WWW-Authenticate: Basic realm="Access denied"');
                exit;
            }

Advertisement

Answer

You can either write:

const usernameAndPassword = 'a:b'
axios.get('https://some_url', {
  headers: {
    Authorization: 'Basic ' + btoa(usernameAndPassword),
  },
})

Or,

axios.get('https://some_url', {
  auth: {
    username: 'a',
    password: 'b',
  },
})

Both are same; will send exact same request headers:

headers

To read the API_KEY i.e. username password from env file, you should name it as REACT_APP_API_KEY and then you can use it in your code as process.env.REACT_APP_API_KEY.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement