AngularJS - 在登录时存储基本身份验证 [英] AngularJS - store basic authentication on login
问题描述
我对此很头疼 - 我对使用 API 还比较陌生,还没有做任何需要身份验证的事情.
I'm banging my head on a wall with this - I'm relatively new to working with APIs and have yet to do anything that requires authentication.
我一直在向 API 发送 POST 请求.创建一段内容的端点是:
I'm stuck with sending a POST request to the API. The endpoint for creating a piece of content is:
/entity/node
如果我发送以下内容,我可以发送成功的 POST 请求:
I can send a successful POST request if I send the following:
headers: {
"Authorization": "Basic YWRtaW46MTIzcXdl", //admin:123qwe
},
我遇到的问题是授权.我在这里指定了 Basic,然后是一个编码字符串,这是我的管理员登录名.所以当硬编码时,我可以发布.
The problem I am having is with Authorization. I'm specifying Basic and then an encoded string here, which is my admin login. So when hardcoded, I can post.
我的问题 - 当用户正确登录时,我需要设置标头,以便所有未来的发布请求都能正常工作.我怎样才能在 AngularJS 中做到这一点?
My question - when the user logs in correctly, I need the headers to be set so that all future post requests work. How can I do this in AngularJS?
我尝试传递动态生成的代码:
I have tried passing a dynamically generated code:
"Authorization": "Basic " + auth,
其中 auth 是 base64 编码的 user:pass,但这不起作用.我的想法是,每当发出 POST 请求时,该值都需要存储在某处以供检索.但是如何?
where auth is a base64 encoded user:pass, but this does not work. My thinking is that this value needs to be stored somewhere for retrieval whenever a POST request is made. But how?
推荐答案
获得令牌后调用:
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
if (authToken !== null) {
var headers = headersGetter();
angular.extend(headers, 'Authorization: basic ' + authToken);
}
return data;
});
没有测试过,但应该是这样的:
Have not tested it, but it should be something like:
myApp.provider('authService', function() {
var authToken = null;
this.$get = ['$httpProvider', function($httpProvider) {
return {
configure: configure,
setAuthToken: setAuthToken
}
};
function configure() {
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
if (authToken !== null) {
var headers = headersGetter();
angular.extend(headers, 'Authorization: basic ' + authToken);
}
return data;
});
}
function setAuthToken(token) {
authToken = token;
}
});
然后将 authService
注入您的应用配置并调用 authService.configure()
and then inject authService
to your app config and call authService.configure()
这篇关于AngularJS - 在登录时存储基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!