使用NODESSPI的公司环境中的节点 [英] Node in Corporative Environment with NODESSPI

查看:161
本文介绍了使用NODESSPI的公司环境中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个NODE API将数据提供给Angular应用.最初的想法是使用NODESSPI进行集成身份验证,因为我们计划在企业环境中运行它.由于API节点将托管在其他域中,因此需要CORS.

I developed a NODE API to serve data to Angular app. The original idea is to use NODESSPI for integrated authentication as we plan to run this on a corporative environment. CORS will be needed as the API Node will be hosted on a different domain.

我正在努力使用 NODESSPI 对$ HTTP请求进行集成身份验证.

I'm struggling to use NODESSPI for integrated authentication of the $HTTP requests.

为了在我的计算机上对其进行测试,我创建了一个简单的js文件,以使用express实例化节点服务器来运行我的有角度的应用程序(我知道可以不用express来完成,但是实现起来更快.)它在端口5001上运行.

To test it on my computer I've created a simple js file to instantiate a node server with express to run my angular app (I know it could be done without express, but it was faster to implement). It is running on Port 5001.

'use strict';

var express = require('express');
var http = require('http');
var path = require('path');
var morgan = require('morgan'); 
var errorhandler = require('errorhandler');
var app = express();

// all environments
app.set('port', process.env.PORT || 5001);
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);

app.use(morgan('dev'));

// serve up static assets
app.use(express.static(path.join(__dirname, 'app')));

// development only
if ('development' === app.get('env')) {
    app.use(errorhandler());
}

console.log('trying to start server...', path.join(__dirname, 'app'));

http.createServer(app).listen(app.get('port'), function () {
        console.log('App server listening on port ' + app.get('port'));
});

我的Angular代码尚处于早期阶段,因为其目的只是证明这一概念.注意,我没有在$ http get上指定任何类型的标头.

My Angular code is on very early stage as its purpose is just prove the concept. Note I'm not specifying any kind of headers on my $http get.

main.controller.js

'use strict';

monthApp.controller('mainPageCtrl',
    function mainPageCtrl($scope, $rootScope, $location, $rootElement, $q, $http) {
        console.log("mainPageCtrl is in control");

        $http({
            url: 'http://localhost:3000/api/',
            methof: 'GET'
        })
        .then(function(data){
            console.log(data);
        })
        .catch(function(error){
            console.log(error);
        })

    });

要运行我的NODE API以模拟服务器端,我还使用Express并在端口3000上运行它,这是代码:

To run my NODE API simulating the server side, I'm also using Express and running it at the port 3000, here is the code:

//Lib Dependecies
var cookieParser    = require("cookie-parser");
var bodyParser      = require("body-parser");
var sql             = require("seriate");
var cors            = require("cors");
var express         = require("express");
var path            = require("path");
var Q               = require("q");
var oracle          = require("oracledb");
var restClient      = require("node-rest-client").Client;
var nodeSSPI        = require('node-sspi');
var ActiveDirectory = require("activedirectory");

//API Custom Modules Dependecies
var reservoirApi    = require("./reservoirApi");
var ldapApi         = require("./ldapApi");
var energyApi       = require("./energyApi");
var PIApi           = require("./PIApi");

//Express config
var app = express();
app.use ( cors() );
app.options('*', cors() );
app.use ( bodyParser.json() );
app.use ( bodyParser.urlencoded( {extended: true} ) );
app.use ( cookieParser() );
app.use ( express.static( __dirname + '/public') );


//Server config
var serverConfig = {port: 3000};

//Sql server config
var config = {
    "server":"myserver",
    "user":"myuser",
    "password":"mypass",
    "database":"mydatabase"
};

sql.setDefaultConfig(config);

//Setup endpoint routes
var router = express.Router();

//Basic Router Config
router.use(function(req, res, next){

    //Integrated Authentication for Windows
    var nodeSSPIObj = new nodeSSPI({
        retrieveGroups: true
    });

    try{
        nodeSSPIObj.authenticate(req, res, function(err){
            res.finished || next();
        });
    }
    catch(err)
    {
        res.status(500).send(JSON.stringify({status: 500, message: "URL mal formatada, verifique sua requisição HTTP", detail: err.message}));
    }
});

router.get('/', function(req, res){
    res.json({Message: 'Data Access API.', AuthUser: req.connection.user, AuthUserGroups: req.connection.userGroups });
});

app.use('/api', router);

//Modules End-Point registration
reservoirApi.register(router);
ldapApi.register(router);
energyApi.register(router);
PIApi.register(router);

//Start Server
app.listen(serverConfig.port);
console.log("SOA API Listening port at " + serverConfig.port)

结果是:

  • 使用Chrome到达地址时: http://localhost:3000/api 这效果很好.它会检测到我的用户帐户并返回我所属的所有Windows组.

  • When using Chrome to reach the address: http://localhost:3000/api this works just fine. It detects my user account and return all windows groups I'm part of.

运行我的角度代码时,它返回: 对象{数据:",状态:401,配置:对象,状态文本:未经授权"}

When running my angular code it returns: Object {data: "", status: 401, config: Object, statusText: "Unauthorized"}

在使用Postman进行测试时,它也可以工作(授权类型='No Auth')

When testing with Postman it also works (with authorization type = 'No Auth')

从路由器中删除所有NodeSSPI代码时,我可以接收数据(我已经在我的angular应用程序上进行了其他端点测试),因此可以在服务器端正确设置CORS.

When removing all NodeSSPI code from my Routers, I can receive data (I've tested with other endpoints on my angular app) so CORS is properly set at the server side.

我在Angular侧缺少什么吗?我正在努力从这里前进.感谢任何帮助.

Is there anything I'm missing on the Angular side? I'm struggling to move forward from here. Appreciate any help.

推荐答案

好,我终于可以正常工作了.所需的更改如下:

Ok, I finally got this working. The changes needed as follow:

在客户端Angular应用中 您需要在$ http请求上将withCredentials设置为true.

At the client Angular app You need to set withCredentials to true on $http requests.

$http({
        url: 'http://localhost:3000/api',
        method: 'GET',
        withCredentials: true,
        headers : {
            'Content-Type' : 'application/json',    
            }
    })

在节点服务器上 响应中需要一些响应头.原点不能为"*",您需要允许凭据.如果需要允许动态原点,可以在 CORS文档.

At the node server Some response headers are needed in the response. Origin cannot be '*' and you need to allow credentials. If you need to allow dynamic origins you can find a way of doing it in the CORS documentation.

//Cors options
var corsOptions = {
    origin: 'http://localhost:5001',
    optionsSuccessStatus: 200, 
    credentials: true,
}

//Express config
var app = express();
app.use ( cors(corsOptions) );
app.use ( bodyParser.json() );
app.use ( bodyParser.urlencoded( {extended: true} ) );
app.use ( cookieParser() );
app.use ( express.static( __dirname + '/public') );

这篇关于使用NODESSPI的公司环境中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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