【问题标题】:Bearer Authentication in ReactReact 中的承载认证
【发布时间】:2019-04-29 15:14:48
【问题描述】:

如何在 React 中将承载身份验证与 superagent 一起使用? 我不确定语法,找不到示例。

我现在做什么

   showTransactionList = () => {
        superagent
            .post('http://193.124.114.46:3001/api/protected/transactions')
            .set({'Authorization': 'Bearer ' + this.state.id_token})
            .accept('application/json')
            .then(res => {
                const posts = JSON.stringify(res.body);
                console.log(posts);
            })
            .catch((err) => {
                console.log(err);
                throw err;                    
            });
    }

谢谢!

【问题讨论】:

  • 当我 ping 没有 Auth 标头的端点时,我得到 UnauthorizedError: No Authorization header was found。使用“测试”令牌,我得到UnauthorizedError: jwt malformed。使用实际的 jwt,我得到UnauthorizedError: invalid signature。您是否能够确定是否设置了标头以及您得到了哪个响应?
  • 非常感谢!!一切都不起作用。这段代码一切正常。问题出在 id_token 中(它是空的),对不起,发送 SET 不像单个对象也很有用。非常感谢!

标签: javascript reactjs authentication ecmascript-6 superagent


【解决方案1】:

设置表头的方式是通过提供表头项名称和值,试试:

showTransactionList = () => {
    superagent
        .post('http://193.124.114.46:3001/api/protected/transactions')
        .set('Authorization', 'Bearer ' + this.state.id_token)
        .accept('application/json')
        .then(res => {
            const posts = JSON.stringify(res.body);
            console.log(posts);
        })
        .catch((err) => {
            console.log(err);
            throw err;                    
        });
}

因此,与其在标头中设置对象,不如将其作为 2 个参数(名称、值)传递。

【讨论】:

【解决方案2】:

而不是设置完整的标题

.set({'Authorization': 'Bearer ' + this.state.id_token})

你可以使用

.auth(this.state.id_token, { type: 'bearer' })

【讨论】:

    【解决方案3】:

    尝试使用.auth('Bearer', this.state.id_token) http://visionmedia.github.io/superagent/#authentication

    【讨论】:

    • 没有。它没有帮助。响应相同的错误:“未经授权”
    • 您是否能够在控制台或任何代理中看到 HTTP 请求中添加的任何 Auth?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2016-06-13
    • 2014-10-11
    • 2016-11-11
    • 2019-06-27
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多