在 angularjs 中向此 HTTP GET 添加 HTTP 基本身份验证 [英] Add HTTP basic authentication to this HTTP GET in angularjs

查看:24
本文介绍了在 angularjs 中向此 HTTP GET 添加 HTTP 基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的 angularjs 代码,它可以生成 HTTP GET.下面提取的是控制器内部的一些相关代码.

I have an existing angularjs code which makes a HTTP GET. Extracted below is some relevant code inside the controller.

    .controller('imptViewCtrl', ['$scope', '$http', 
        function ($scope, $http, ) {
                    var url = $configuration.webroot + '/impt/list?list=testlist';
                    $http.get(url).then(function (response) {
                               tableData = response.data;
                               });
        }]);

我想为 HTTP GET 添加 HTTP 基本身份验证.用户名是foo,密码是bar.这怎么办?

I would like to add HTTP basic authentication to the HTTP GET. The username is foo and the password is bar. How can this be done?

推荐答案

因为在基本认证中,用户名和密码是通过 base64 解码的.您首先需要找到一个图书馆来完成这项工作.

Because in basic authentication, the username and password are decode by base64. You need to find a library to do this work for comfortable first.

https://github.com/ninjatronic/angular-base64

之后,将 base64 加载到您的应用和配置标头中.

After that, load base64 into your app and config headers.

angular
    .module('myApp', ['base64'])
    .config(function($httpProvider, $base64) {
        var auth = $base64.encode("foo:bar");
        $httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
    })

如果您愿意,您还可以单独为 get 函数提供身份验证标头.

You can also provide the authentication header to get function seprately if you like.

var auth = $base64.encode("foo:bar"), 
    headers = {"Authorization": "Basic " + auth};
$http.get(url, {headers: headers}).then(function (response) {

这篇关于在 angularjs 中向此 HTTP GET 添加 HTTP 基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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