如何使用express,passport-local在Node.js中使用API​​令牌进行API调用

时间:2017-03-02 02:41:12

标签: node.js express token passport.js

我是Node.js中的新手,并尝试使用API​​令牌访问Grafana。 我按照Grafana page的说明创建了一个API令牌。

但是,我不知道如何通过我的node.js代码进行API调用来访问我的grafana页面的本地服务器。此外,我有一个本地登录页面,使用mongoDB来管理用户。

如何进行Node.js API调用以访问grafana页面的本地服务器?

请帮帮我..我在这方面遇到了困难.. 如果你想让我显示代码,我可以在这里编辑..

修改 这是app.js的完整代码

var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//Adding grafana
var request = require('request');

//Connecting Database (MongoDB)
mongoose.connect("my mongoDB private address");
var db = mongoose.connection;
db.once("open",function () {
  console.log("DB connected!");
});
db.on("error",function (err) {
  console.log("DB ERROR :", err);
});

//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");

//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
  email: {type:String, required:true, unique:true},
  password: {type:String, required:true},
  createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
  var user = this;
  if(!user.isModified("password")){
    return next();
  } else {
    user.password = bcrypt.hashSync(user.password);
    return next();
  }
});

//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
  var user = this;
  return bcrypt.compareSync(password,user.password);
};

//Setting User as userSchema.
var User = mongoose.model('user',userSchema);

io = io.listen(server);

//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());

app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());

//Initializing passport.
passport.serializeUser(function(user, done) {
  //console.log('serializeUser()', user);
  done(null, user.id);
});
passport.deserializeUser(function(id, done) {
  //console.log('deserializeUser()', user);
  User.findById(id, function(err, user) {
    done(err, user);
  });
});
var username_tmp = '';
var global_username = '';         //Global variable for username to put in the address
var pass = '';
//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
  new LocalStrategy({
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true
    },
    function(req, email, password, done) {
      User.findOne({ 'email' :  email }, function(err, user) {
        if (err) return done(err);
        if (!user){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'No user found.'));
        }
        if (!user.authenticate(password)){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'Password does not Match.'));
        }
        var email_address = req.body.email;
        username_tmp = email_address;
        var username = email_address.substring(0, email_address.lastIndexOf("@"));
        global_username = username;
        pass = req.body.password;
        return done(null, user);
      });
    }
  )
);

//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html

app.get('/', loggedInCheck);

app.get('/login', function (req, res) {
  res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});

//Accessing to MongoDB to check to login or not
app.post('/login',
  function (req,res,next){
    next();
  }, passport.authenticate('local-login', {
    successRedirect : '/status',
    failureRedirect : '/login',
    failureFlash : true
  })
);

//Creating new account
app.get('/users/new', function(req,res){
  res.render('users/new', {
                            formData: req.flash('formData')[0],
                            emailError: req.flash('emailError')[0],
                            passwordError: req.flash('passwordError')[0]
                          }
  );
});


//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
  var user_temp = {user: ''};
  user_temp.user = global_username;
  res.render('status/status', user_temp);
  //res.redirect('/status.html?channel=' + global_username);
});

app.get('/grafana', isLoggedIn, function(req, res){
  console.log('Accessing to grafana');
  res.redirect('http://localhost:8080');
 });

request.get('http://localhost:8080',{
  auth: {
    bearer: 'TOKEN HERE'
  }
});


server.listen(4000);

编辑更多

app.get('/grafana', isLoggedIn, function(req, res){
  console.log('Accessing to grafana');
  var url = 'http://localhost:8080/api/dashboards/db/test';
  request.get(url,{
    auth: {
      bearer: 'API token from Grafana page'
    }
  });
  res.redirect(url);
 });

谢谢..

1 个答案:

答案 0 :(得分:1)

API调用是使用HTTP请求进行的。您可以使用npm的request包。

来自文档:

  

您在授权标头中的所有请求中使用令牌,如下所示:   获取http://your.grafana.com/api/dashboards/db/mydash HTTP / 1.1   接受:application / json   授权:bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk

示例(我正在使用request-promise,但您可以使用任何您想要的内容):

let request = require('request-promise');
let url = `http://your.grafana.com/api/dashboards/db/mydash`;
//Obviously replace this with your token
let myToken = `eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk`;
request.get(url).auth(null, null, true, myToken).then(res=> { ... });
// or
request.get(url, {
  auth: {
    bearer: myToken
  }
}).then(res=> { ... });