简体   繁体   English

在受保护的路由中进行身份验证登录

[英]Do auth login in Protected route

How can we do auth login in the protected route.我们如何在受保护的路由中进行身份验证登录。

For example I have a protected where I allow user to connect their social media profiles once they are logged in.例如,我有一个受保护的地方,允许用户在登录后连接他们的社交媒体资料。

Typically passport auth happens using href events ie <a href="base_url/auth/facebook"> Cick here to connect facebook </a>通常使用href事件发生护照身份验证,即<a href="base_url/auth/facebook"> Cick here to connect facebook </a>

Now, I am not sure how i can set cookie with my href (if this is the ideal way) if I want to connect user after they are logged in.现在,如果我想在用户登录后连接用户,我不确定如何使用我的href设置 cookie(如果这是理想的方式)。

Here is what my middleware looks like这是我的中间件的样子

async verifyMiddleWare(req, res, next) {
    const token = req.cookies
    if (token) {
        try {
            const userToken = token.userToken
            const tokenVerficiation = await verifyToken(userToken)
            res.locals.userId = tokenVerficiation.userId
            res.locals.acessLevel = tokenVerficiation.acessLevel
            if (tokenVerficiation.acessLevel === this.routePermission) next()
            else
                res
                    .status(AUTH_ERRORS.INVALID_ACCESS_TOKEN.status)
                    .send(AUTH_ERRORS.INVALID_ACCESS_TOKEN.message)
        } catch (error) {
            return res
                .status(AUTH_ERRORS.UNAUTHORIZED_TO_VIEW.status)
                .send(AUTH_ERRORS.UNAUTHORIZED_TO_VIEW.message)
        }
    } else {
        return res
            .status(AUTH_ERRORS.MISSING_ACCESS_TOKEN.status)
            .send(AUTH_ERRORS.MISSING_ACCESS_TOKEN.message)
    }
}

and passport code (i am not serialising and de-serialising user)和护照代码(我不是序列化和反序列化用户)

const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy
const config = require('./../../config')

passport.use(
    new FacebookStrategy(
        {
            clientID: config.FACEBOOK_APP_ID,
            clientSecret: config.FACEBOOK_APP_SECRET,
            callbackURL: config.FACEBOOK_REDIRECT_URL,
            profileFields: ['id', 'displayName', 'email', 'gender']
        },
        async (accessToken, refreshToken, profile, done) => {
            return done(null, { accessToken, refreshToken, profile })
        }
    )
)

And I am setting cookie like this during auth我在身份验证期间设置这样的cookie

app.get(`/${serviceName}/callback`, passport.authorize(serviceName), async (req, res) => {
        const facebookDetials = req.account
        // the output from passport should mandatorily have email
        const userEmail = facebookDetials.profile.emails[0].value
        // Checking if user data exsists, corresponding to email id entered
        try {
            const userData = await getSelectedThingFromTable(
                SIGNUP_TABLES.userAuth,
                `email = "${userEmail}"`
            )
            if (userData.length > 0) {
                // Means email Exist
                const { userId, acessLevel } = userData[0] //
                    const createNewAccessToken = await JWT.generateToken({ userId, acessLevel })
                    //setting cookies
                    res.cookie('userToken', createNewAccessToken)
                    return res.redirect(config.BASE_CONFIG_URL)

What have I tried yet我还试过什么

  1. Pretty dumb way but login user in my browser (localhost:8000/auth/facebook) and then going to localhost:8000/social/twitter -> Here my token is coming to be undefined相当愚蠢的方式,但在我的浏览器中登录用户(localhost:8000/auth/facebook)然后转到localhost:8000/social/twitter -> 这里我的令牌将是未定义的

I could easily be wrong but I'm guessing the cookie doesn't appear to be set because it's getting associated with the wrong domain name.我很容易出错,但我猜 cookie 似乎没有设置,因为它与错误的域名相关联。

Try changing尝试改变

res.cookie('userToken', createNewAccessToken)

to

res.cookie('userToken', createNewAccessToken, {domain: 'localhost:8000'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM