✭☭2018-04-23 13:39:58
Web development
✭☭, 2018-04-23 13:39:58

Where is the error in basic authorization?

Hello!
I'm trying to make the simplest basic authorization from a mobile application (phonegap) on a php server.
On the server, this is the code:

<?php

header("Access-Control-Allow-Origin: *");

if(empty($_SERVER['PHP_AUTH_USER']))           
  {	
    header('WWW-Authenticate: Basic realm="WWW-Authenticate"');    
    header ('HTTP/1.0 401 Unauthorized'); 
    exit();                                                
  }

print "1";
?>

On the client, this is the code:
var php_авторизоваться = function()
{	 
  var запрос = new XMLHttpRequest()
    	запрос.open('POST', 'http://localhost:2222/авторизоваться.php')  
    	запрос.send()
    	запрос.onreadystatechange = function()
          {
            if(запрос.readyState === 4)
              {
              	var ответ = запрос.responseText

              	if(ответ === '1')
                	{	
          alert(1)
                	}
             }
         }

The php code without the if(empty($_SERVER['PHP_AUTH_USER']))... fragment works fine, i.e. there is a connection with the server and it prints "1"
But authorization does not work.
5addbb7408e4b562759415.png
Please give the simplest working code - you need to contact the server for data through XMLHttpRequest (), entering the password and login

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hOtRush, 2018-04-23
@hOtRush

Http basic auth does not work if CORS is enabled with an asterisk, only if CORS is configured for specific hosts. Use jwt or similar

R
Rsa97, 2018-04-23
@Rsa97

What does "doesn't work" mean? Doesn't return a 401 response? Did you look at the exchange with the server in the browser console?

V
Viktor Yanyshev, 2018-04-23
@villiwalla

Doesn't it bother you that "WWW-Authenticate" is written, but you write authorization? followed by "Unauthorized"?
It's strange, isn't it true that if you remove if(empty($_SERVER['PHP_AUTH_USER'])) , as you say, then you get a response, but otherwise you don't? But it seems to me that in that and in that case everything works just someone uses exit () and does not reach the print.
When working with headings, do you generally look at them when you check them, or do you expect them to be diagnosed by calling prints and alerts? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question