django - 通过 React-Native 从 Django OauthToolkit 获取请求 token

标签 django oauth-2.0 react-native

我试图从 Django - OauthToolkit 获取 token ,但我只收到“unsupported_grant_type”错误:

这是我在react-native中写的内容:

async getToken (client_id, client_key, username, password) {
     let response = await fetch('https://example.com/o/token/', {
         method: 'POST',
         headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
         body: JSON.stringify({
           'client_id': client_id,
           'client_secret': client_key,
           'grant_type': 'password',
           'username': username,
           'password': password,
         })
       })
       let responseJson = await response.json()
       var token = responseJson.error <- written to see the error (shoul be responseJson.acces_token)
       this.setState({token})
}

其他帖子提到这可能是标题中的错误 - 但它现在让我一无所知。

最佳答案

在挠头和无数次​​谷歌搜索之后,我是这样做的。

请允许我做一些假设

  1. 假设您的后端服务器工作正常,并且所有端点均受到保护。
  2. 假设当您访问端点时出现错误

    "detail": "Authentication credentials were not provided."

  3. 假设您可以通过 postman 或通过使用参数向/o/token 发送 POST 请求来验证/获取访问 token

    • 用户名
    • 密码
    • client_id
    • grant_type

使用 django-oauth-toolkit,将数据/正文发送为

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

注意:我的方法可能不够简洁,所以我欢迎任何建设性的批评/建议

import { AUTH_LOGIN} from 'react-admin';
var  _client_id = 'xxxxxxxxx';
var _grant_type = 'password';

export default (type, params) => {
    if (type === AUTH_LOGIN) {
        const {username, password } = params;
        let _data = "grant_type="+_grant_type+"&username="+username+"&password="+password+"&client_id="+_client_id
        const request = new Request('http://localhost:8000/api/ps/o/oauth/token/', {
            method: 'POST',
            headers: new Headers({ 
            'Content-Type': 'application/x-www-form-urlencoded',}),
             body : _data,
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
            return response.json();
        })
        .then(({ access_token }) => {
            localStorage.setItem('token', access_token);
        });
}

return Promise.resolve();

}

最后但重要的是,/o/token 返回一个带有键“access_token”而不是 token 的字典。因此,修改您的代码,如下突出显示

.then(({ access_token }) => {localStorage.setItem('token', access_token);});

关于django - 通过 React-Native 从 Django OauthToolkit 获取请求 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36344918/

相关文章:

css - 更改 native 文本项的字体​​?

html - 在网格中显示

python - 无法从 VS2015 将 Django 项目发布到 Azure Web App

django - 如何手动清除/更新 Django 中的缓存 View

symfony - 同时使用HWIOAuthBundle和LexikJWT

node.js - 实现自己的 oauth2 服务器和 api 服务器

python - Django Web 项目中用户提供的 CSV

python - Django:Queryset.union() 和 OR 运算符有什么区别?

oauth-2.0 - 如何在 Dart 中使用 Oauth2 在 Google Fusion Tables 中进行身份验证?

reactjs - Ant Design for React Native 真正的原生组件?