【问题标题】:Accessing protected route访问受保护的路由
【发布时间】:2018-05-17 05:57:18
【问题描述】:

我刚开始使用 JWT。我进行 login 并将 token 作为 JSON 响应 发送到 client成功登录后,我将其存储到 sessionStorage,然后我使用该令牌通过另一个 ajax 调用的标头访问 protected route (GET) 成功后将重定向到该页面。

我开始直接保护我也重定向路由,并且没有 /验证用户 路由,但由于在重定向 标头 未发送 我发现了这个解决方案仅用于验证令牌。但是我不知道这是否是好方法。

你怎么看?

我的在客户端登录

   // Login POST 
    $('#frm-login').submit(function (e) {
        event.preventDefault()
        $('button').text('Please wait ...').prop('disabled')
        $.ajax({
            url: "/login-user",
            type: "POST",
            data: $('#frm-login').serialize(),
            dataType: "json"
        }).always(function (response) {
            $('button').text('Logging in').prop('disabled')
            console.log("Login", response)
            if (response.status == "error") {
                $('button').removeClass('lime').addClass('red').text('Log in failed. Try again.');
                return
            }
            localStorage.setItem('token', response.token);
            console.log(localStorage.token)
            $.ajax({
                type: "GET",
                url: "/verify-user",
                headers: {
                    'Authorization': 'Bearer ' + localStorage.token
                }
            }).always(function (response) {
                console.log("Access", response)
                if (response.status == "error") {
                    $('button').removeClass('lime').addClass('red').text('Log in failed. Try again.');
                    return
                }
                if (response.status == 301) {
                    $(location).attr('pathname', '/LIMELine/chatroom/');
                    //$('img#profile-img').attr('src', response.responseText.authData.user.avatar)
                    console.log(response)
                }
            });
        })
    })

我的在服务器上登录

/********************* LOGIN *********************/

app.post('/login-user', (req, res) => {
    user.loginUser(req.body, (err, jResult) => {
        if (err) {
            return res.send(jResult)
        }
        let token = jwt.sign({
            user: jResult,
        }, "supersecret")
        console.log(token);
        return res.json({
            token: token
        })
        //add other headers here...
    })
})

/********************* VERIFY USER *********************/

app.get('/verify-user', verifyToken, (req, res) => {

    jwt.verify(req.token, "supersecret", (err, authData) => {
        if (err) {
            return res.status(403).json({
                message: "No token found"
            });
        }
        return res.status(301).json({
            authData
        });
    })
})

受保护的路由,用户登录时应该看到的

// *********************   MAIN PAGE *********************************************

app.get('/LimeLINE/chatroom' (req, res) => {
            try {
            // CODE FOR CONTENT OF THE PAGE
            return res.json({
                authData
            });
        }
    })
})

【问题讨论】:

    标签: jquery node.js ajax redirect jwt


    【解决方案1】:

    如果您要进行整页重定向(不是通过 ajax,而是通过浏览器自动进行,例如单击未调整的锚标记时),浏览器不会自动发送 Authorization HTTP 标头。

    您可以使用 cookie 开始发送 JWT 令牌(这种方式不太标准,将客户端与浏览器联系起来,但会在所有完整页面和 AJAX 调用中自动发生)或通过 ajax 调用自己处理重定向。 另一个“混合”解决方案是启用 Authorization 标头和 cookie 作为有效的授权方法。

    IMO 这完全取决于您的服务器是否应该在当前或不久的将来接受非浏览器客户端。

    【讨论】:

    • 如何通过 ajax 调用处理 ridirect?这不就是我现在正在做的吗?
    • @July333 如果我错了,请纠正我,但是在获得重定向代码 (301 - 303) 后,您会执行更改 location 对象之类的操作吗?如果没有,请提供有关如何进行重定向的信息
    • 您的意思是来自服务器的重定向代码?现在我只从服务器发送令牌并重定向。
    • 哦.. 现在看,您使用window.location.pathname = '/LIMELine/chatroom' 进行重定向,当浏览器运行此代码时,它会执行完整的页面加载,而不会发送Authorization 标头。
    • 那么如何执行非全页加载呢?
    猜你喜欢
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2020-02-10
    • 2022-11-16
    • 1970-01-01
    • 2020-10-26
    • 2019-05-31
    相关资源
    最近更新 更多