我们如何在 React js 中使用 axios 发送 OAuth2.0 [英] How can we send OAuth2.0 with axios in React js

查看:14
本文介绍了我们如何在 React js 中使用 axios 发送 OAuth2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个身份验证问题,我必须为我的 React 应用程序实施 OAuth2.0 身份验证.有什么方法可以让我在基于 Axios Promise 的库中使用该身份验证???

I am working on one authentication problem where i have to implement OAuth2.0 authentication for my React App. Is there any way that i can use that authentication with Axios Promise based library???

推荐答案

您必须在标题中传递您的令牌.

You will have to pass your Token in the header.

见下文;

const instance = axios.create({
  baseURL: 'http://localhost/api/',
  headers: {'Authorization': 'basic '+ token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

获得令牌后,请在浏览器中设置授权 cookie.浏览器将始终在向服务器发出的每个请求中发送授权 cookie.您不必通过 Axios get/post 传递它.

Set an Authorization cookie in the browser once you get your token. The browser will always send the Authorization cookie in each request made to the server. You won't have to pass it through Axios get/post.

更新:

为了从oAuth服务器获取访问令牌,如下传递client_id、client_secret、scope和grant_type;

In order to get the access token from the oAuth server, pass the client_id, client_secret, scope and grant_type as follows;

var axios = require("axios");

axios.request({
  url: "/oauth/token",
  method: "post",
  baseURL: "http://sample.oauth.server.com/",
  auth: {
    username: "myUsername", // This is the client_id
    password: "myPassword" // This is the client_secret
  },
  data: {
    "grant_type": "client_credentials",
    "scope": "public"    
  }
}).then(respose => {
  console.log(respose);  
}); 

我假设您使用的是grant_type = "client_credentials",如果不是,则根据您使用的grant_type,您还必须相应地更改请求参数.

I am assuming that you are using grant_type = "client_credentials", if not, then based on the grant_type you use, you will have to also change the request parameters accordingly.

这篇关于我们如何在 React js 中使用 axios 发送 OAuth2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆