首页 > 解决方案 > 在 React-native 应用程序中使用 Axios 访问此资源错误消息需要完全身份验证

问题描述

尝试从 Restful API(带有 React-native 的 Axios)获取 accesstoken,但是,只得到错误消息:

"error": "unauthorized","error_description": "访问此资源需要完全身份验证"

function accessToken(){

    axios({
        method: 'post',
        url: 'myurl',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            //'Access-Control-Allow-Origin': '*',
        },

        data: {
            client_id: 'myid',
            client_secret: 'mysecret',
            grant_type: 'client_credentials'
        },


    })
        .then(function(res){

            console.log(res);
            console.log(res.data);

        })
        .catch(function(err) {

            console.log(err);
            console.log(err.response.data);
            console.log(err.response.status);
            console.log(err.response.headers);
            console.log(err.request);
            console.log(err.message);
            console.log(err.config);
        });
}

 Object {

   "error": "unauthorized",

   "error_description": "Full authentication is required to access this resource",

}

401

我试图从由 Oauth 制成的 Restful API 获取访问令牌。但是我只得到错误 401

“访问此资源需要完全身份验证”。

我已经尝试过

   add 'Access-Control-Allow-Origin': '*' in headers,  
   base64 encode id and pw,
   add withCredential : true and false,
   create instance with axios.create.

这是 API 的示例用法。我在 React-native 中使用 Axios 制作的其他功能运行良好,但是只有这个应该获取 accesstoken 的功能不起作用。

curl -X POST \

http://api_domain:port/oauth/token \

-H 'Cache-Control: no-cache' \

-H 'Content-Type: application/x-www-form-urlencoded' \

-d 'client_id=00002&client_secret=gateway-api-secret&grant_type=client_credentials'

先感谢您。

标签: node.jsreact-nativeoauthaxios

解决方案


您必须在 auth 标头中指定用户名和密码,例如

 method: "post",
  url: `myurl`,
  data: data,
  auth: {
    username: "myid",
    password: "mysecret"
  }

数据将具有其他字段,例如 grant_type 等。


推荐阅读