Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery HTTP authentication

With jQuery I am calling Version One Rest API and need to authenticate user in HTTP header.

I tried

$.ajax({
        dataType: "jsonp",
        beforeSend: function(xhr){
            xhr.setRequestHeader("Authorization", "Basic xyz"); // xyz usr:pwd Base64 encoded
        },
        url: "https://www10.v1host.com/.../VersionOne/rest-1.v1/...",
        success: function(data, status, xhr) {
            alert("Load was performed.");
        }
    });

and

$.ajax({
    dataType: "jsonp",
    username:"usr",
    password:"pwd",
    url: "https://www10.v1host.com/.../VersionOne/rest-1.v1/...",
    success: function(data, status, xhr) {
        alert("Load was performed.");
    }
});

But I always get pop up asking for my credentials (I use Chrome). Even when I type credentials in the pop up, I am not authenticated and the window keeps showing.

  1. How to authenticate user with jQuery in HTTP headers?
  2. Is there any way how make password attribute encrypted invisible? Or Base64 is the only way. I want to access server via only one account but do not want users on client side to see the password (or find it in javascripts).
like image 458
padis Avatar asked Jan 06 '11 22:01

padis


1 Answers

This isn't exactly impossible, just a little bit awkward. You can proxy all the AJAX through your own server like this:

  • Your JavaScript contacts your server via AJAX.
  • Your server sets up the request to https://www10.v1host.com/.../VersionOne/rest-1.v1/... with the appropriate basic auth headers (or whatever authentication you need to use).
  • Your server sends the response back to your script exactly as www10.v1host.com sent it to your server.

This way the password stays invisible and under your control on the server and the client code gets the same API as it would from www10.v1host.com. There might be a little bit of lag introduced with this approach but that should be manageable.

Of course, you still have to consider the authorization process between the browser and your server but you should be able to use whatever authorization you already have for that (probably cookies and plain old logins).

You'll also want to check this technique against the API terms of service to make sure you're playing nice.

like image 119
mu is too short Avatar answered Sep 28 '22 22:09

mu is too short