将安全的Grafana嵌入到Web应用程序中

Kla*_*aus 13 javascript basic-authentication angularjs

我想使用AngularJS将Grafana嵌入到我的Web应用程序中.目标是,当用户在我的应用程序中时,她应该能够单击按钮并加载Grafana UI.就其本身而言,这是一项简单的任务.为此,我有apache代理Grafana并返回任何必要的CORS头.apache反向代理配置如下:

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Max-Age "1000"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, Authorization, accept, client-security-token"


    RewriteEngine on
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]
    RewriteCond %{REQUEST_METHOD} OPTIONS
    ProxyPass / http://localhost:3000/
Run Code Online (Sandbox Code Playgroud)

当没有安全措施时,所有工作都完美无缺.以下代码是一个简单的HTML/Javascript,显示了我在做什么:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://requirejs.org/docs/release/2.1.11/minified/require.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<body >
<script>
    var app = angular.module('myApp', []);

    app.controller('MainCtrl', function ($scope, $http, $sce) {

    $scope.trustSrc = function(src) {
            console.log(src);
            return $sce.trustAsHtml(src);
    }

    $http({
            method : 'GET',
            url : 'http://grafana-host.com',

    }).success(function(response) {
            $("#test").attr('src', 'http://grafana-host.com')
            $("#test").contents().find('html').html(response);

    }).error(function(error) {
            console.log(error);
    });
});
</script>

<div ng-app="myApp" ng-controller="MainCtrl">

<iframe id="test" style="position: absolute; top: 50px; left: 0px; bottom: 0px; right: 0px; width: 100%; height: 100%; border: none; margin: 0; padding: 0; overflow: hidden;"></iframe>
Run Code Online (Sandbox Code Playgroud)

现在的挑战是,一旦登录到我的应用程序,用户就不必再次登录Grafana.

要解决此问题,我将Grafana设置为使用Basic Auth.我的目标是让我的网络应用程序通过浏览器将基本身份验证传递给Grafana.基本上,当用户点击按钮打开Grafana时,我会通过AngularJS发出请求.此请求将包括加载Grafana所需的Authorization标头.为此,我在url字段后面的http博客增加了上面的代码段:

            headers : {
               'Authorization' : 'Basic YWRtaW46YWRtaW4='
            }
Run Code Online (Sandbox Code Playgroud)

此外,在成功回调函数中,我将第一条指令替换为:

  $("#test").attr('src',"data:text/html;charset=utf-8," + escape(response))
Run Code Online (Sandbox Code Playgroud)

不幸的是,我似乎无法让这个工作.

我知道这应该有效,因为我可以使用Chrome浏览器的ModHeader扩展模拟此行为.如果我在ModHeader中放置以下标题:授权:基本YWRtaW46YWRtaW4 =,它无需登录即可加载Grafana.如果我删除了Authorization标头,系统会再次提示我输入登录名和密码.

grafana的变化非常简单:

[auth.basic]
enabled = true
Run Code Online (Sandbox Code Playgroud)

我错过了什么?我猜这是一个AngularJS/Javascript的东西.

小智 6

不知道在编写问题时这是否是一个选项,但我们通过注入 API 令牌进行授权(http://docs.grafana.org/http_api/auth/)非常成功地做到了这一点。