简体   繁体   中英

Can't access req.user in Node.js server with Auth0/Angular

I'm using auth0 to act as my admin panel's login, and it's running great. A problem that I'm having is that in node, I cannot for some reason access 'req.user' as it returns unidentified. This is a pretty basic setup here. I have console logged req.headers and an authentication header is set.

Here is the node app.js file

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var routes = require('./routes/index');
    var users = require('./routes/users');
    var app = express();
    var Parse = require('node-parse-api').Parse;

    var expressJwt = require('express-jwt');
    var jwt = require('jsonwebtoken');
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');

    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/bower_components',  express.static(__dirname + '/bower_components'));
    app.Parse = new Parse(options.app_id, options.api_key);
    app.use('/api', routes(app), expressJwt({secret: 'Mode'}));
    app.all('/*', function(req, res) {
        res.sendFile('index.html', { root: path.join(__dirname, '/public') });
    });

    module.exports = app;

Here is the AngularJS code.

var app = angular.module('EnragedGamers', ['angularMoment', 'ngRoute', 'auth0', 'angular-storage', 'angular-jwt'])
.config(function(authProvider, $routeProvider, $locationProvider, $httpProvider, jwtInterceptorProvider) {

    $routeProvider
        .when('/', {
            templateUrl: 'home.html',
            controller: 'Home'
        })
        .when('/article/:article_id', {
            templateUrl: 'article.html',
            controller: 'Article'
        })
        .when('/admin-panel/login', {
            templateUrl: 'admin-login.html',
            controller: 'Admin-Login'
        })
        .when('/admin-panel', {
            templateUrl: 'admin.html',
            controller: 'Admin',
            requiresLogin: true
        });

    authProvider.init({
        domain: 'enragedgamers.auth0.com',
        clientID: 'MpTkAl4eosjl3SB682ZGSSrJYi03QiZp',
        loginUrl: '/admin-panel/login'
    });

    jwtInterceptorProvider.tokenGetter = ['store', function(store) {
        // Return the saved token
        return store.get('token');
    }];

    $httpProvider.interceptors.push('jwtInterceptor');

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });

})
.run(function($rootScope, auth, store, jwtHelper, $location) {
    // This hooks al auth events to check everything as soon as the app starts
    $rootScope.$on('$locationChangeStart', function() {
        var token = store.get('token');
        if (token) {
          if (!jwtHelper.isTokenExpired(token)) {
            if (!auth.isAuthenticated) {
              auth.authenticate(store.get('profile'), token);
            }
          } else {
            // Either show the login page or use the refresh token to get a new idToken
            $location.path('/');
          }
        }
    });
});

Here is the routes file code

var express = require('express');
var router = express.Router();
module.exports = function(app){

    router.get('/admin/hello', function(req, res){
        console.log(req.user)
        res.status(201).json({'human': 'Hello'})
        console.log(req.body);
    });

    return router;
} 

It seems that you're missing your secret on the node side and the middle man for actually authenticating.

See https://github.com/auth0/express-jwt

var jwt = require('express-jwt');

app.use(jwt({ secret: 'your secret key here'}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM