W
W
whiteleaf2017-10-16 12:18:25
Angular
whiteleaf, 2017-10-16 12:18:25

How to do secure authorization in Angular 4?

Please help me understand the mechanism of how the authorization process itself works in Node.js (express) + Angular 4 bundles.
As I understand it, it is most reliable to do authorization using sessions, where I plan to use express-session and mongoDB as session storage .
Up to this stage, everything seems to be clear, but how to implement everything further? The session was announced and registered in the database. But you need to somehow check and if there is no session, redirect to /login, and if everything is in order, transfer to Angular.
Here is what I have at the moment. What is the best way and where to implement it?
server.js

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);

// Get our API routes
const api = require('./server/routes/api');

//const session = require('./server/routes/session');

const app = express();

var store = new MongoDBStore(
  {
    uri: 'mongodb://localhost:27017/buildcore',
    collection: 'sessions'
  });

// Catch errors
store.on('error', function(error) {
  assert.ifError(error);
  assert.ok(false);
});

app.use(require('express-session')({
  secret: 'This is a secret',
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
  },
  store: store,
  // Boilerplate options, see:
  // * https://www.npmjs.com/package/express-session#resave
  // * https://www.npmjs.com/package/express-session#saveuninitialized
  resave: true,
  saveUninitialized: true
}));


// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
//app.use('/*', session);
app.use('/api', api);



// Catch all other routes and return the index file
app.get('*', (req, res) => {

  var session = req.session;

  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

api.js
const express = require('express');
const router = express.Router();

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

module.exports = router;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question