如何通过AngularJS $ http从ASP.Net Web API 2获取Access Token?

我试着这样:

$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password, grant_type: 'password' } }).success(function (data, status, headers, config) { $scope.output = data; }).error(function (data, status, headers, config) { $scope.output = data; }); 

然后尝试将grant_type更改为param:

 $http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password }, params: { grant_type: 'password' } }).success(function (data, status, headers, config) { $scope.output = data; }).error(function (data, status, headers, config) { $scope.output = data; }); 

仍然可怕: {"error":"unsupported_grant_type"}

所以我做了AngularJS开发人员应该做的事情,使用jQuery:

 var data = $('#regForm').serialize() + "&grant_type=password"; $.post('/token', data).always(showResponse); function showResponse(object) { $scope.output = JSON.stringify(object, null, 4); $scope.$apply(); }; 

这就像一个冠军……所以我的问题是:我们如何使用AngularJS $http()复制上面的jQuery $.post()调用,这样我们就可以从ASP中的基于OWIN中间件/令牌端点获取访问令牌。 Net Web API 2?

做这个:

 $http({ url: '/token', method: 'POST', data: "userName=" + $scope.username + "&password=" + $scope.password + "&grant_type=password" }) 

我认为,将标题{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }到您的post请求中就可以了。 它应该是这样的:

 $http.post(loginAPIUrl, data, {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}) 

您收到该错误是因为OWIN OAuth提供程序的默认实现期望对“/ Token”服务的post进行表单编码而不是json编码。 这里有一个更详细的答案如何设置katana-project以允许json格式的令牌请求?

但你仍然可以使用AngularJs,你只需要改变$ httppost的制作方式。 如果您不介意使用jquery更改参数,可以尝试这里的答案如何将数据作为表单数据而不是请求有效负载发布? 希望有所帮助。

您始终可以在浏览器中查看使用开发人员控制台发出的请求,并查看请求中的差异。

但通过查看你的jquery代码&grant_type=password是在正文中传递而不是查询字符串所以$http调用应该是

$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password ,grant_type:password} }).success(function (data, status, headers, config) {

类似于achinth,但你仍然可以使用$http.post方法(+数据被转义)

 $http.post(loginUrl, "userName=" + encodeURIComponent(email) + "&password=" + encodeURIComponent(password) + "&grant_type=password" ).success(function (data) { //... 

1)注意URL:“localhost:55828 / token”(不是“localhost:55828 / API / token”)

2)记下请求数据。 它不是json格式,它只是没有双引号的普通数据。 “userName=xxx@gmail.com&password=Test123$&grant_type=password”

3)注意内容类型。 内容类型:’application / x-www-form-urlencoded’(不是Content-Type:’application / json’)

4)当您使用javascript发布post请求时,您可以使用以下内容:

 $http.post("localhost:55828/token", "userName=" + encodeURIComponent(email) + "&password=" + encodeURIComponent(password) + "&grant_type=password", {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }} ).success(function (data) {//... 

查看Postman下面的截图:

邮差要求

邮递员请求标题