Phani Mahesh
Phani Mahesh

Reputation: 85

How to secure Angular 4 routes using Passport JS?

I am planning to setup Google Sign-In using Node JS, Express JS and Passport JS. In that process, I have configured Google strategy using the application credentials, created a sample .ejs page with a sign-in button and I was able to sign-in and retrieve the user profile. Later, I have removed the sample page and tried to place all the static Angular 4 files (built using angular-cli) in the Public directory and wrote the following logic,

app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
  if (req.isAuthenticated()) {
    res.redirect("/home");; // Angular route
  } else {
    // require the user to log in
    // redirects to Google Sign-in page
    res.redirect("/auth/google");
  }
});

Now, when I start the server and visit http://localhost:3000 , I don't see any redirection to the Google Sign-in page, instead the browser directly renders http://localhost:3000/home.

So, what changes should I make in order to authenticate the User and then redirect the User to the Home page. And also secure the other routes/child routes in the application ?

Upvotes: 0

Views: 1304

Answers (1)

EMX
EMX

Reputation: 6211

Check if request has a session the simple way...

app.get('/home', function(req, res) {
 if(req.session){ //session exists (requesting user has a session)
   // Angular route code goes here to prevent non-authed user access
 }else{res.redirect("/");} //or res.redirect("/auth/google");
});

...or use a module like connect-ensure-login

Ensure Authentication

app.get('/home',
  ensureLoggedIn('/auth/google'),
  function(req, res) {
    // Angular route code goes here to prevent non-authed user access
  });

If user isn't authed, the request will be redirected to /auth/google and the original request URL (/home) will be saved to the session at req.session.returnTo.

Upvotes: 1

Related Questions