AngularJS - 存储在登录基本身份验证 [英] AngularJS - store basic authentication on login

查看:185
本文介绍了AngularJS - 存储在登录基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敲打这个墙上我的头 - 我是比较新的使用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.

我卡与发送POST请求的API。用于创建内容片段的端点是:

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
   },

我遇到的问题是与授权。我在这里指定的基本,然后连接codeD字符串,它是我的管理员登录。所以,当硬$ C $的CD,我可以张贴。

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.

我的问题 - 在正确的用户登录时,我需要的头被设置,以便未来所有的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?

我试图传递一个动态生成的code:

I have tried passing a dynamically generated code:

"Authorization": "Basic " + auth,

其中的权威性是一个base64连接codeD用户:通过,但这并不工作。我的想法是,这个值需要检索存储在某个地方,每当一个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?

推荐答案

调用此一旦你有一个令牌:

Call this once you have a token:

$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆