我试图从 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})
}
其他帖子提到这可能是标题中的错误 - 但它现在让我一无所知。
最佳答案
在挠头和无数次谷歌搜索之后,我是这样做的。
请允许我做一些假设
- 假设您的后端服务器工作正常,并且所有端点均受到保护。
假设当您访问端点时出现错误
"detail": "Authentication credentials were not provided."
假设您可以通过 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/