I am trying to implement OAuth on the reddit API. I request an authorization code, click the link, but then when I try to do a POST to get the token I get "invalid_grant" as my error. I read in their docs this means "The code has expired or already been used", but that's not possible because I just requested the code. Any help is appreciated!
This works fine...
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}`);
});
error is somewhere in here...
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}`);
});
});
Aucun commentaire:
Enregistrer un commentaire