Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please provide an example which protects static content with express/passport #298

Open
rmey opened this issue Jul 19, 2023 · 0 comments
Open

Comments

@rmey
Copy link

rmey commented Jul 19, 2023

I have difficulties to protect static content, I get alway redirected to / after successful login, when accessing a resource below "/protected"

const express = require('express');
const app = express();
const session = require('express-session');
const passport = require('passport');
const WebAppStrategy = require('ibmcloud-appid').WebAppStrategy;

// Configure session
app.use(session({
  secret: 'your-secret',
  resave: false,
  saveUninitialized: true
}));

// Initialize passport and configure strategy
app.use(passport.initialize());
app.use(passport.session());

passport.use(new WebAppStrategy({
   tenantId: "xxx",
   clientId: "xxx",
   secret: "xxx",
   oauthServerUrl: "xxx",
   redirectUri: "http://localhost:3000/appid/callback" /*"http://localhost:3000" + CALLBACK_URL*/
}));

// Store user in session
passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((user, done) => {
  done(null, user);
});

// Middleware to protect static content
const protectContent = (req, res, next) => {
  console.log("DEADBEAF");
   if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/appid/login');
};

// Routes
app.get('/appid/login', passport.authenticate(WebAppStrategy.STRATEGY_NAME, {forceLogin: true }));
app.get('/appid/callback', passport.authenticate(WebAppStrategy.STRATEGY_NAME));

// Serve static content
app.use('/protected', protectContent, express.static('protected'));

// Start the server
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant