oauth-2.0 在React Native中将授权头与Fetch一起使用

velaa5lx  于 2022-10-31  发布在  React
关注(0)|答案(5)|浏览(210)

我正在尝试使用React Native中的fetch从Product Hunt API获取信息。我已经获得了正确的访问令牌并将其保存到State中,但似乎无法在GET请求的Authorization头中传递它。
以下是我目前掌握的情况:

  1. var Products = React.createClass({
  2. getInitialState: function() {
  3. return {
  4. clientToken: false,
  5. loaded: false
  6. }
  7. },
  8. componentWillMount: function () {
  9. fetch(api.token.link, api.token.object)
  10. .then((response) => response.json())
  11. .then((responseData) => {
  12. console.log(responseData);
  13. this.setState({
  14. clientToken: responseData.access_token,
  15. });
  16. })
  17. .then(() => {
  18. this.getPosts();
  19. })
  20. .done();
  21. },
  22. getPosts: function() {
  23. var obj = {
  24. link: 'https://api.producthunt.com/v1/posts',
  25. object: {
  26. method: 'GET',
  27. headers: {
  28. 'Accept': 'application/json',
  29. 'Content-Type': 'application/json',
  30. 'Authorization': 'Bearer ' + this.state.clientToken,
  31. 'Host': 'api.producthunt.com'
  32. }
  33. }
  34. }
  35. fetch(api.posts.link, obj)
  36. .then((response) => response.json())
  37. .then((responseData) => {
  38. console.log(responseData);
  39. })
  40. .done();
  41. },

我对我的代码的期望如下:
1.首先,我将使用导入的API模块中的数据fetch一个访问令牌
1.之后,我将设置this.stateclientToken属性,使其等于接收到的访问令牌。
1.然后,我将运行getPosts,它将返回一个响应,其中包含Product Hunt的当前帖子数组。
我可以验证是否正在接收访问令牌,以及this.state是否正在将其作为其clientToken属性接收。我还可以验证getPosts是否正在运行。
我收到的错误如下:
{“error”:“unauthorized_oauth”,“error_description”:“请提供有效的访问标记。有关如何对API请求进行授权的信息,请参阅我们的API文档。另外,请确保您需要正确的作用域。例如,\“private public\”用于访问私有端点。"}
我一直在努力消除这样一种假设,即我在授权头中没有正确沿着访问令牌,但似乎无法找出确切的原因。

9bfwbjaz

9bfwbjaz1#

结果是我错误地使用了fetch方法。
fetch接受两个参数:一个API的端点,以及一个可包含主体和标头的可选对象。
我把想要的对象 Package 在第二个对象中,这并没有给我带来任何想要的结果。
下面是它的高级外观:

  1. fetch('API_ENDPOINT', options)
  2. .then(function(res) {
  3. return res.json();
  4. })
  5. .then(function(resJson) {
  6. return resJson;
  7. })

我的选项对象的结构如下:

  1. var options = {
  2. method: 'POST',
  3. headers: {
  4. 'Accept': 'application/json',
  5. 'Content-Type': 'application/json',
  6. 'Origin': '',
  7. 'Host': 'api.producthunt.com'
  8. },
  9. body: JSON.stringify({
  10. 'client_id': '(API KEY)',
  11. 'client_secret': '(API SECRET)',
  12. 'grant_type': 'client_credentials'
  13. })
  14. }
展开查看全部
xuo3flqw

xuo3flqw2#

我也遇到了同样的问题,我使用django-rest-knox作为身份验证令牌。结果我的fetch方法没有任何问题,看起来像这样:

  1. ...
  2. let headers = {"Content-Type": "application/json"};
  3. if (token) {
  4. headers["Authorization"] = `Token ${token}`;
  5. }
  6. return fetch("/api/instruments/", {headers,})
  7. .then(res => {
  8. ...

我在运行Apache。
对我来说解决这个问题的是在wsgi.conf中将WSGIPassAuthorization更改为'On'
我在AWS EC2上部署了一个Django应用程序,我使用Elastic Beanstalk来管理我的应用程序,所以在django.config中,我这样做:

  1. container_commands:
  2. 01wsgipass:
  3. command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
展开查看全部
2ekbmq32

2ekbmq323#

如果您使用的是不记名令牌,下面的代码片段应该可以正常工作:

  1. const token = localStorage.getItem('token')
  2. const response = await fetch(apiURL, {
  3. method: 'POST',
  4. headers: {
  5. 'Content-type': 'application/json',
  6. 'Authorization': `Bearer ${token}`, // notice the Bearer before your token
  7. },
  8. body: JSON.stringify(yourNewData)
  9. })
drkbr07n

drkbr07n4#

  1. completed = (id) => {
  2. var details = {
  3. 'id': id,
  4. };
  5. var formBody = [];
  6. for (var property in details) {
  7. var encodedKey = encodeURIComponent(property);
  8. var encodedValue = encodeURIComponent(details[property]);
  9. formBody.push(encodedKey + "=" + encodedValue);
  10. }
  11. formBody = formBody.join("&");
  12. fetch(markcompleted, {
  13. method: 'POST',
  14. headers: {
  15. 'Accept': 'application/json',
  16. 'Content-Type': 'application/x-www-form-urlencoded'
  17. },
  18. body: formBody
  19. })
  20. .then((response) => response.json())
  21. .then((responseJson) => {
  22. console.log(responseJson, 'res JSON');
  23. if (responseJson.status == "success") {
  24. console.log(this.state);
  25. alert("your todolist is completed!!");
  26. }
  27. })
  28. .catch((error) => {
  29. console.error(error);
  30. });
  31. };
展开查看全部
laik7k3q

laik7k3q5#

使用授权标头提取的示例:

  1. fetch('URL_GOES_HERE', {
  2. method: 'post',
  3. headers: new Headers({
  4. 'Authorization': 'Basic '+btoa('username:password'),
  5. 'Content-Type': 'application/x-www-form-urlencoded'
  6. }),
  7. body: 'A=1&B=2'
  8. });

相关问题