Javascript 在 angularjs 中向此 HTTP GET 添加 HTTP 基本身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34413732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:18:27  来源:igfitidea点击:

Add HTTP basic authentication to this HTTP GET in angularjs

javascriptangularjshttphttp-getbasic-authentication

提问by user781486

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

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

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

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

我想向 HTTP GET 添加 HTTP 基本身份验证。用户名是foo,密码是bar。如何才能做到这一点?

回答by user5698801

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.

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

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

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

After that, load base64into your app and config headers.

之后,加载base64到您的应用程序和配置标头中。

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

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

get如果您愿意,您还可以提供身份验证标头以单独运行。

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

回答by ryan.wise

Rather than using a library to encode your auth by base 64, you could just use:

您可以使用:而不是使用库通过 base 64 对您的身份验证进行编码:

window.btoa("user:pass")

window.btoa("user:pass")

it's supported by most browsers.

大多数浏览器都支持它。

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa