带护照蒸汽的koa护照:ctx.isAuthenticated()始终为false

时间:2020-09-29 02:27:02

标签: authentication passport.js koa

我正在将koa-passport与带护照的蒸汽一起使用,以通过SteamID对用户进行身份验证。尽管已通过Steam正确登录,但ctx.isAuthenticated()始终为false。我一直在看很多其他的SO问题和指南以及google结果,这个问题很普遍,但总是由于某人代码中的特有错误而不适用于我的。还有其他一些特有的问题困扰着我的代码,但我找不到它。 实际上,大多数与护照相关的代码都是从tutorials / docs / examples复制粘贴而成的。我的中间件排序正确,据我所知不是会话配置问题。

const Koa = require("koa");
const session = require("koa-session");
const Router = require("@koa/router");
const views = require("koa-views");
const passport = require("koa-passport");
const SteamStrategy = require("passport-steam").Strategy;
const bodyparser = require("koa-bodyparser");

const root = "http://localhost:3000";
const app = new Koa();
const router = new Router();

passport.serializeUser((user, done) => {
    console.log("Serializing:", user);
  done(null, user);
});

passport.deserializeUser((obj, done) => {
    console.log("Deserializing:", obj);
  done(null, obj);
});

passport.use("steam", new SteamStrategy({
        returnURL: root + "/auth/steam/return",
        realm: root,
        apiKey: "---"
    },
    function(identifier, profile, done) {
        process.nextTick(function () {
            let identifie = identifier.match(/\/id\/(\d+)/)[1];
            profile.id = identifie
            console.log("Returned from Steam:", profile);
            return done(null, profile);
        });
    })
);

app.on("ready", () => {
    console.log('ready');
});

app.on("error", (err, ctx) => {
    console.log("ERR:", err);
});

const CONFIG = {
    key: 'koa.sess',
    maxAge: 10000,
    secure: true
} 
//I have tried tons of cookie settings including using default
//because a lot of people in the koa-passport issues seem to have solved
//their similar problem by changing session settings, but I've had no such luck
app.keys = ['session_secret'];
app.use(session(CONFIG, app));
app.use(bodyparser());
app.use(passport.initialize());
app.use(passport.session());

app.use(views("views", { 
            map: { 
                ejs: "ejs" 
            }
        })
);

//A shoddy attempt at middleware just to test. But ctx.isAuthenticated always returns false.
app.use(async (ctx, next) => {
    if (ctx.isAuthenticated()) {
        console.log("Hey! You're authenticated");
    }
    return next()
});

app.use(router.routes());


router.get("/", async (ctx, next) => {
    await ctx.render("howdy.ejs");
});

router.get("/auth/steam", async (ctx, next) => {
    console.log("Trying to auth");  
    return passport.authenticate('steam', { failureRedirect: "/fail" })(ctx);
});

router.get("/auth/steam/return", async (ctx, next) => {
    passport.authenticate('steam', { failureRedirect: "/fail", successRedirect: "/text" })(ctx);
    ctx.redirect("/text");
});

router.get("/fail", async (ctx, next) => {
    await ctx.render("fail.ejs");
});

router.get("/text", async (ctx, next) => {
    console.log(`
    Auth: ${ctx.isAuthenticated()},
    Unauth: ${ctx.isUnauthenticated()},
    User:
    `);
    console.log(ctx.state.user);
    console.log(ctx.req.user);
    if (ctx.state.user) {
        await ctx.render("success.ejs");
    } else {
        await ctx.render("fail.ejs");
    }
});


app.listen(3000);

让我们看一下一个示例交互: 您单击索引上的一个按钮即可进入/ auth / steam。在我的控制台中打印Trying to auth,您将被重定向到Steam。您登录(登录后,您将被重定向到/ text)。

Trying to auth
   
    Auth: false,
    Unauth: true,
    User:
    
undefined //ctx.state.user, this is how koa-passport should expose the authenticated user.
undefined //ctx.req.user, as a test. I don't expect it to be defined but I see it mentioned in some docs.
Returned from Steam: {YOUR PROFILE!}
Serializing: {YOUR PROFILE!}

我的显示Auth / Unauth / User信息的测试打印文件已在配置文件之前打印,我认为这是由于某种异步竞赛造成的。 可以肯定的是,您将重新加载页面(/文本)以再次获得此类信息:

    Auth: false,
    Unauth: true,
    User:
    
undefined
undefined

没有变化!

1 个答案:

答案 0 :(得分:2)

您现在可能已经从这里开始了,但是您的问题给了我让 Steam 身份验证在我的项目中工作所需的条件,所以我想我会分享我的发现。

我没有直接运行您的代码示例,但我认为这是两个问题。

首先,您的 /auth/steam/return 端点需要更新。它应该是这样的:

router.get("/auth/steam/return", async (ctx, next) => {
    return passport.authenticate('steam', { failureRedirect: "/fail", successRedirect: "/text" })(ctx);
});

其次,我在会话配置方面遇到了问题。特别是 secure: true 对我不起作用,因为我正在通过不安全的连接 (http) 进行测试。本地主机可能有例外,但如果没有,更改 CONFIG 对我有用。我还更改了 maxAge,因为它设置为 10 秒或 10,000 毫秒。

const CONFIG = {
    key: 'koa.sess',
    maxAge: 86400000,
    secure: false
}