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

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

问题描述

我正在处理一个身份验证问题,我必须为我的React App实现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;
})

OR

获取令牌后,在浏览器中设置一个授权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天全站免登陆