Reputation: 151
I am writing a Web Api (using asp.net Web Api) and naturally want clients to authenticate to use the service.
I was hoping to write a Javascript plugin that would make use of the Api and then make it available to be simply dropped into other web sites.
Is there a secure way I can have the plugin authenticate? I'm not sure how I could keep any information passed to the plugin confidential.
I also want the API to be used by native apps, so does that rule anything making use of cookies?
Thanks
Upvotes: 2
Views: 2429
Reputation: 17739
Is there a secure way I can have the plugin authenticate?
You are going to have to either embed the username/password in your plugin OR have some fields to get that information from the user.
Consider some code if you choose to embed the username/password:
$.ajax({
url: 'api/foo',
type: 'GET',
dataType: 'json',
success: onSuccess,
error: onError,
beforeSend: setHeader
});
note the assignment of beforeSend
to setHeader
:
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Basic YXBpX3VzZXIxOjEyMzQxMjM0');
}
Note, you will have to pre-calculate the auth string using the method below
Now if you want to pull the username/password from the user you could do this:
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', make_base_auth($("#username").val(), $("#password").val()));
}
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
Upvotes: 4