'Integrate existing Login Infrastructure from Node JS in Angular
I have in my backend server, which was built with Node JS, an authentication with the package "passport-azure-ad". I put the important elements of the code here in the post. Basically, the process is that when I call the URI "localhost:3000/login", I start the authentication and (if you are not already logged in) the login window I get from Azure pops up. After the login, it routes to the callback URI.
I.e. I have the complete "login infrastructure" I need for my use case. However, now I built a frontend with Angular and unfortunately I have absolutely no idea how to best proceed to integrate the authentication I built in Node JS into my frontend (Angular)? I want to check if there is a login when calling my frontend (localhost:4200), if not I want to route to 3000/login to trigger the Microsoft login window. I do this check in the backend with the ensureAuthenticated function. Now I wonder how to call all this from the frontend? It would be nice if someone could support me on this, any tips or any suitable sources would be greatly appreciated - thanks!
// session management
app.use(session({
resave: true,
saveUninitialized: true,
secret: process.env.COOKIE_SECRET
}));
app.use(passport.initialize());
app.use(passport.session());
// check if logged in
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
};
// call azures login page
app.get('/login',
passport.authenticate('azuread-openidconnect')
);
// callback uri after authentication
app.post('/auth/oauth/callback',
function (req, res, next) {
passport.authenticate('azuread-openidconnect',
{
failureRedirect: '/failure',
}
)(req, res, next);
},
function (req, res) {
res.redirect('/account');
});
// protected ressource
app.get('/account', ensureAuthenticated, function (req, res) {
res.redirect('Login succesfull!');
});
// logout
app.get('/logout', function (req, res) {
req.logout();
req.session.destroy();
res.send('Ausgeloggt!');
});
Solution 1:[1]
When using an SPA like Angular, you can't no longer use this kind of authentication flow by using passport strategies to authenticate to third party endpoints like Microsoft/Google.
Instead, you start the OAuth2.0 flow from your Angular application straight to the Microsoft authentication endpoint. Tokens will be used for further authentication.
Some links:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
