对Drupal的Axios身份验证请求-invalid_grant

时间:2019-08-30 08:27:03

标签: drupal oauth oauth-2.0 axios

我正在尝试使用axios从JS应用程序向Drupal进行身份验证。

我可以通过Postman和带有curl的终端进行身份验证,但是我似乎无法使用axios进行身份验证。

这就是我在做什么:

const uri = 'https://test.com/oauth/token'

const data = new FormData();
data.append("client_id", "xxxxxx");
data.append("client_secret", "secret");
data.append("grant_type", "password");
data.append("username", "user");
data.append("password", "secret");
data.append("scope", "");

axios({
  method: 'POST',
  url: uri,
  headers: {}, 
  data: data
})
.then(res => {
  console.log("res", message);
})
.catch(err => {
  console.log("error in request", err);
});

这是我在控制台中得到的:

 data:
  { error: 'invalid_grant',
    error_description:
     'The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.',
    hint: 'Check the configuration to see if the grant is enabled.',
    message:
     'The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.' } } }

这是我在Drupal中得到的:

League\OAuth2\Server\Exception\OAuthServerException: The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.

1 个答案:

答案 0 :(得分:1)

使用axios也有同样的问题,下面是我最终对Drupal 8中的simple_oauth端点进行身份验证的结果。

 import * as axios from 'axios';

 const axiosAPI = axios.create();
 axiosAPI.defaults.baseURL = 'http://localhost/';
 axiosAPI.defaults.timeout = 30000;

 async authenticate(username, password){
   const params = new URLSearchParams();
   params.append('grant_type',  'password');
   params.append('client_id',  'xxx-yyy-zzz');
   params.append('client_secret', 'somesupersecret');
   params.append('username', username);
   params.append('password', password);

   try{
     let response = await axiosAPI.post('/oauth/token', params);

     console.log(response.data);

   } catch(e){
     console.error(e);
   }
}

所以关键是使用URLSearchParams编码参数,而不是对数据进行形式编码。一旦我发现我不应该只是发布表单,实际上在https://github.com/axios/axios的文档中标题为“使用application / x-www-form-urlencoded格式”中已提到过。