用于获取访问令牌的角度帖子失败

时间:2016-04-07 14:01:42

标签: java angularjs rest http oauth

你会帮我创建一个angularjs POST请求版本

吗?

https://drive.google.com/file/d/0B6weCtBHDZU1eUFWcHpNNE5WTVk/view?usp=sharing

这个想法是获取一个访问令牌,这样我就可以安全地消费一些其他的api。 我通过角度尝试了很多次,我分析了每个请求而我失败了,我总是发现请求体是空的。

这是我尝试的一些角度代码的示例。

    var app = angular.module("app", []);
    app
        .controller(
                "MyController",
                function($scope, $http) {
                    $scope.obtain_token = function() {
                        var payload = "grant_type=password" + "&username=roy" + "&password=spring" +
                          "&client_id=clientapp"+
                          "&client_secret=123456";
                        var r = $http.post('http://localhost:8080/oauth/token',payload);
                        r.success(function(response){
                            console.log(response.access_token);
                        });
                    };
                });

2 个答案:

答案 0 :(得分:1)

    function Hello($scope, $http) {

    var config = {
            headers : {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Basic ' +btoa('clientapp:123456654321')
            }
        }
    var payload ="password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp";

    $http.post('http://localhost:8080/oauth/token',payload, config).
    success(function(data, status, headers, config) {
        $scope.data = data;
    }).
    error(function(data, status, headers, config) {
        $scope.data = data; 
    }); 
}

答案 1 :(得分:0)

sample angular-1 code..
----------------------------------
var payload = {
"grant_type":"password",
"username"="roy",
"password"="spring",
"client_id"="clientapp"
"client_secret"="123456"
}

$http.post("http://localhost:8080/oauth/token", payload).success(function (result) {
                console.log(result);
            }).error(function(error) {
                console.log("error", error);
            });

and sample api c#
---------------------
[HttpPost]
        [Route("")]
        public HttpResponseMessage SaveArchive([FromBody] JObject saveRequest)
        {
            var log = LogManager.GetCurrentClassLogger();
            try``
            {
                return "your success message";
            }
            catch (Exception ex)
            {

                return ex;
            }
        }