【问题标题】:How to reset Oauth authentication approval with Express.js and Passport.js如何使用 Express.js 和 Passport.js 重置 Oauth 身份验证批准
【发布时间】:2021-07-18 12:28:27
【问题描述】:

我不确定如何重置 Oauth 身份验证批准。我将 Passport 与 Google Oauth2 策略一起使用。在我的 /logout 路由中,我调用 req.logOut()。但是,当我之后转到身份验证路径时,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
}

【问题讨论】:

    标签: javascript node.js oauth-2.0 google-api passport.js


    【解决方案1】:

    你可以试试这个吗:

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

    或者你可以创建一个函数:

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

    并像这样使用它:

    eraseCookie('cookie-name')
    

    【讨论】:

    • @prmph 抱歉,我更新了代码。我想写这个。
    • @Vlahovljak 谢谢,但还是不行
    • @你能在开发工具中检查cookie的名称吗,也许不是这个名称。我也更新了答案,至少你可以实现一个删除cookie的功能。
    • @Vlahovljak cookie 确实被称为“connect.sid”,我检查了开发工具。但是没有被清除
    • @prmph 我的意思是你可以在客户端删除它吗?如果没有任何效果。
    猜你喜欢
    • 2020-12-15
    • 2014-07-01
    • 2017-03-31
    • 2015-01-09
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多