我尝试从我的django-rest-framework api和angularjs客户端获取令牌。
这就是我使用get token access的方式:
var payload = {
username: 'seb',
password: 'aa',
grant_type: 'password',
client_id: consumerKey,
client_secret: consumerSecret
};
var r = $http.post('http://localhost:8000/oauth2/access_token',
payload);
r.success(function(response){
console.log(response.token);
});
我已更新我的标题:
$ httpProvider.defaults.headers.post ['Content-Type'] ='application / x-www-form-urlencoded';
不幸的是它让我{"error_description": "No 'grant_type' included in the request.", "error": "invalid_request"}
玩curl给我带来了所需的标记:(
答案 0 :(得分:3)
可以预期有效负载能够作为Json对象存在......但是它需要formData类型的内容。线索在你的行中
'应用/ X WWW的窗体-urlencoded';
因此,OAuth提供商期望数据基于表单。所以你的有效载荷必须是这样的:
payload = "grant_type=password" + "&username=seb" + "&password=aa" +
"&client_id=" + consumerKey +
"&client_secret=" + consumerSecret;
答案 1 :(得分:0)
这是我放在一起的一个简单的HttpService实现。
angular.module("services").factory("HttpService", ["$q", "$http", function ($q, $http) {
var httpSvc = {};
httpSvc.Url = "";
httpSvc.ContentType = "application/x-www-form-urlencoded";
httpSvc.JsonPayload = {};
//execute login
httpSvc.HttpPost = function () {
var deferred = $q.defer();
appLogger.conlog(httpSvc.JsonPayload);
//Http Post method
$http({
method: "POST",
url: httpSvc.Url,
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
"Content-Type": httpSvc.ContentType
},
data: httpSvc.JsonPayload //post data
}).success(function (data, status, headers, config) {
deferred.resolve({ data: data, status: status, headers: headers, config: config }); //result
}).error(function (data, status, headers, config) {
deferred.reject({ data: data, status: status, headers: headers, config: config }); //result
});
appLogger.conlog(deferred.promise);
//return the callback promise
return deferred.promise;
};
return httpSvc;
}]);
只需将其注入模块即可使用
var oauth2Payload = {
grant_type: "password",
username: userName,
password: password,
client_id: appConfig.clientId
};
httpSvc.JsonPayload = oauth2Payload;
httpSvc.Url = sysConfig.tokenUrl;
httpSvc.HttpPost().then(function (response) {
var data = response.data;
appLogger.conlog("access_token:\r\n" + data.access_token);
appLogger.conlog("refresh_token:\r\n" + data.refresh_token);
$cookies.refresh_token = data.refresh_token;
appLogger.conlog(data);
deferred.resolve("ok");
}, function (errResponse) {
var data = errResponse.data;
appLogger.conlog(data);
deferred.resolve("error");
});