Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is some code for basic authentication from one of my projects. I use it against CouchDB with and additional auth data cache, but I stripped that code.</p> <p>Wrap an authentication method around you request handling, and provide a second callback for unsuccessfull authentication. The success callback will get the username as an additional parameter. Don't forget to correctly handle requests with wrong or missing credentials in the failure callback:</p> <pre><code>/** * Authenticate a request against this authentication instance. * * @param request * @param failureCallback * @param successCallback * @return */ Auth.prototype.authenticate = function(request, failureCallback, successCallback) { var requestUsername = ""; var requestPassword = ""; if (!request.headers['authorization']) { failureCallback(); } else { var auth = this._decodeBase64(request.headers['authorization']); if (auth) { requestUsername = auth.username; requestPassword = auth.password; } else { failureCallback(); } } //TODO: Query your database (don't forget to do so async) db.query( function(result) { if (result.username == requestUsername &amp;&amp; result.password == requestPassword) { successCallback(requestUsername); } else { failureCallback(); } }); }; /** * Internal method for extracting username and password out of a Basic * Authentication header field. * * @param headerValue * @return */ Auth.prototype._decodeBase64 = function(headerValue) { var value; if (value = headerValue.match("^Basic\\s([A-Za-z0-9+/=]+)$")) { var auth = (new Buffer(value[1] || "", "base64")).toString("ascii"); return { username : auth.slice(0, auth.indexOf(':')), password : auth.slice(auth.indexOf(':') + 1, auth.length) }; } else { return null; } }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload