AngularJs Basic Auth for Post Request

Is it possible to use basic auth with the following snippet to make a simple post request to a site running locally?

app.controller('post', function($scope, $http) {


$http.post("http://localhost:8888/angular//wp-json/posts", {'title':'Posting from Angular'})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available

document.getElementById("response").innerHTML = "It worked!";
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.

document.getElementById("response").innerHTML= "It did not work!";
alert(status)
});

}); 

Related posts

1 comment

  1. When you say basic auth, do you mean HTTP Basic Authentication?

    If that’s what you mean: then NO. HTTP Basic Authentication requires that your client (in this case, your web browser) needs to know your API keys and be able to send them over the network to your server. Since you’re running Angular inside of a web browser, this means that any user visiting your site would theoretically be able to view your API credentials in plain text by inspecting the browser’s Javascript console.

    This is a HUGE security risk.

    What you want to do instead is use a protocol like OAuth2 with the Password Grant (more info here: https://stormpath.com/blog/token-auth-spa/).

    OAuth2 allows you to basically do this:

    • Have a user log into your application with a username/password.
    • When the login is successful, a token will be returned and stored in a web browser cookie that is HIDDEN FROM JAVASCRIPT.
    • Then you can use Angular to POST to your API service, as the browser will automatically attach the relevant token API credentials in the HTTP Authorization header automatically.
    • Your server can then grab the token out of the HTTP Authorization header, and validate the credentials in this way.

    This is the only safe way to access an authenticated API service from a browser.

Comments are closed.