I'm implementing a very simple authentication scheme. Username:Password are sent (via header of an HTTPS POST request) to a PHP file on an Apache server that checks whether that combination is in a MySQL database or not and whether it has expired.

As I'm fairly new to web engineering (if you can call what I do that), I'm a little unsure how to execute the response.

Should I return true or false (or something like this that shows whether authentication worked or not) in the body of the HTTPS response - or in the header (both of which would be HTTP status code 200, I guess)? Or would it be best practice to return with status code such as 200 for successful auth and something like 401 Unauthorized in case the user:pass combination was not found/is expired?

  • Implementing your own security is a nice excersice, but I suggest you check other what advanced users have build. You are often not aware of possible problems. :)
    – Martijn
    Jul 26 '16 at 8:06
  • I wouldn't have said that processing a login request and issuing an appropriate response is necessarily "implementing your own security" (although it is naturally "part of") - it's a necessity that many developers face every day.
    – MrWhite
    Jul 26 '16 at 22:11
  • Don't roll your own authentication. Use a standard built into the framework. Something like forms or basic authentication are most common. Otherwise you'll need to consult RFC's and browser specifications to ensure your custom authentication will function. Jul 27 '16 at 20:09

It would be usual to return the appropriate HTTP status code to indicate success/failure, as you suggest. A 200 for success, 401 (or 403) for failure. However, strictly speaking, a 401 status should be accompanied by a WWW-Authenticate response header. And maybe an access token (cookie) for persistent connections (although this might just be stored in the session).

What you return in the response body is really up to you and in many ways is dependent on the type of the request. If the request is from an HTML form submission then it would be usual to send an HTML response - the user wants to see something. If you are building an API or sending an AJAX request then maybe you don't need to send any response body, or maybe a plain text error, or an XML / JSON string with a structured (error) response?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.