AngularJs Post 请求的基本身份验证

AngularJs Basic Auth for Post Request

是否可以通过以下代码段使用基本身份验证来向本地站点 运行 发出简单的 post 请求?

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)
});

}); 

当你说基本身份验证时,你指的是 HTTP 基本身份验证吗?

如果那是你的意思:那么不。 HTTP 基本身份验证要求您的客户端(在本例中为您的 Web 浏览器)需要知道您的 API 密钥并能够通过网络将它们发送到您的服务器。由于您在 Web 浏览器中 运行 Angular,这意味着理论上任何访问您网站的用户都可以通过检查浏览器的 Javascript控制台。

这是一个巨大的安全风险。

您想要做的是使用像 OAuth2 这样的协议和密码授予(更多信息在这里:https://stormpath.com/blog/token-auth-spa/)。

OAuth2 基本上允许您这样做:

  • 让用户使用 username/password.
  • 登录您的应用程序
  • 登录成功后,将返回一个令牌并将其存储在隐藏于 JAVASCRIPT 的网络浏览器 cookie 中。
  • 然后您可以使用 Angular 到 POST 到您的 API 服务,因为浏览器会自动在 HTTP 授权 header自动。
  • 然后您的服务器可以从 HTTP 授权中获取令牌 header,并以这种方式验证凭据。

这是从浏览器访问经过身份验证的API服务的唯一安全方式。