簡體   English   中英

如何使用 Express.js 和 Passport.js 重置 Oauth 身份驗證批准

[英]How to reset Oauth authentication approval with Express.js and Passport.js

我不確定如何重置 Oauth 身份驗證批准。 我將 Passport 與 Google Oauth2 策略一起使用。 在我的 /logout 路線中,我調用req.logOut() 但是,當我 go 到認證路由之后,Oauth 認證屏幕不再出現; 以前的身份驗證被重用,我自動登錄。 我該如何防止這種情況?

對於上下文,這是我的中間件:

    app.use(morgan('tiny', { skip: (req, res) => req.baseUrl === "/static" })) 
    app.use(express.urlencoded())
    app.use(express.json({ limit: "20mb" }))
    app.use(cookieParser())
    app.use(session({
        resave: false,
        store: new session.MemoryStore(),
        secret: process.env.SESSION_SECRET || "abcd",
        cookie: { secure: false, maxAge: 1000 /*, httpOnly: false*/ },
        saveUninitialized: false
    }))

    const passport = configureAuthentication()
    app.use(passport.initialize(), passport.session())

這是我當前的身份驗證和注銷路線:

    app.get('/auth/google', passport.authenticate('google', { scope: ["profile", "email"] }))
    app.get('/auth/google/callback',
        // function (req, res, next) { console.log(`Callback handling, req.user = ${req.user}`) },
        passport.authenticate('google'/*, { failureRedirect: '/auth/google' }*/),
        function (req, res) {
            // Successful authentication, redirect home.
            console.log(`Successful authentication,req.user = ${req.user}, redirecting to '/'`)
            res.redirect('/')
        }
    )

    app.get("/logout", (req, res, next) => {
        req.session.destroy(function (err) {
            if (err) console.error(err)
            return res.redirect('/')
        })
    })

這是我的護照配置:

function configureAuthentication/*<U>*/(/*authProvider: AuthProvider<U>*/) {
    passport.serializeUser(((user: User, done: (err: any, user: User) => any) => {
        // console.log(`Serializing user ${JSON.stringify(user, undefined, 2)}`)
        done(null, user)
    }) as any)
    passport.deserializeUser((obj: User, done) => {
        console.log(`DeSerializing user ${JSON.stringify(obj, undefined, 2)}`)
        done(null, obj as any)
    })

    passport.use("google", new passportGoogleOauth20.Strategy(
        {
            clientID: process.env.GOOGLE_CLIENT_ID!,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
            // callbackURL: `https://vytals.herokuapp.com/auth/google/callback`,
            // callbackURL: `http://localhost:${process.env.PORT || "49720"}/auth/google/callback`,
            callbackURL: '/auth/google/callback',
            scope: [
                // Per-file access to files created or opened by the app. 
                // File authorization is granted on a per-user basis and is revoked when the user deauthorizes the app.
                // scope: ``,
                'https://www.googleapis.com/auth/drive.file',

                // Allows access to the Application Data folder.
                'https://www.googleapis.com/auth/drive.appdata'

                // scope: ['https://www.googleapis.com/auth/drive'],
            ]
        },

        function (accessToken, refreshToken, profile, done) {
            console.log(`User access token: "${accessToken}`)
            console.log(`User refresh token: "${refreshToken}`)
            console.log(`User profile: ${JSON.stringify(profile, undefined, 2)}`)

            // User.findOrCreate({ driveId: profile.id }, function (err: any, user: any) {
            //  return done(err, user)
            // })

            const user: User = {
                id: profile.id,
                displayName: profile.displayName,
                emailAddress: profile.emails && profile.emails.length > 0 ? profile.emails[0].value : undefined,
                imageUrl: profile.photos && profile.photos.length > 0 ? profile.photos[0].value : undefined,
                provider: "google",
                refreshToken,
                accessToken
            }
            return done(null, user)
        }
    ))

    return passport
}

你可以試試這個:

app.get('/logout', function (req, res){
    req.session.destroy(function() {
        res.clearCookie('connect.sid');
        res.redirect('/');
    });
});

或者您可以創建一個 function:

const eraseCookie = (name) => {
    document.cookie = `${name}=; Max-Age=-99999999;`;
};

並像這樣使用它:

eraseCookie('cookie-name')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM