我正在尝试在reddit API上实现OAuth。我请求授权代码,单击链接,但是当我尝试执行POST以获取令牌时,我将“invalid_grant”作为我的错误。我在他们的文档中读到这意味着“代码已过期或已被使用”,但这是不可能的,因为我刚刚请求了代码。任何帮助表示赞赏!
这很好......
const CLIENT_ID="*****************";
const CLIENT_SECRET="**********************";
const TYPE="code";
const RANDOM_STRING="random_string";
const URI= encodeURIComponent('http://localhost:8080/api/reddit/callback');
const DURATION="temporary";
const SCOPE_STRING="identity";
const GRANT_TYPE='authorization_code';
const router = express.Router();
router.get('/login', function(req, res){
console.log(`Redirecting to: https://www.reddit.com/api/v1/authorize?client_id=${CLIENT_ID}&response_type=${TYPE}&state=${RANDOM_STRING}&redirect_uri=${URI}&duration=${DURATION}&scope=${SCOPE_STRING}`);
res.redirect(`https://www.reddit.com/api/v1/authorize?client_id=${CLIENT_ID}&response_type=${TYPE}&state=${RANDOM_STRING}&redirect_uri=${URI}&duration=${DURATION}&scope=${SCOPE_STRING}`);
});
错误就在这里......
router.get('/callback', function(req, res){
if (!req.query.code) throw new Error('NoCodeProvided');
if (req.query.state != RANDOM_STRING) throw new error('Mismatched strings');
const CODE = req.query.code;
request('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
form: {
grant_type: GRANT_TYPE,
code: CODE,
redirect_uri: URI
},
auth: {
username: CLIENT_ID,
password: CLIENT_SECRET
}
}, function (error, res, body){
if (error){
console.log("Error: " + error);
return;
}
console.log(res);
console.log(res.access_token);
console.log(CODE);
//const json = res.json();
//res.redirect(`/?token=${json.access_token}`);
});
});
答案 0 :(得分:0)
感谢reddit用户,我发现我的回调URI被编码了两次。更改为此修复...
const URI= 'http://localhost:8080/api/reddit/callback';