2015-07-09 34 views
5

Tôi đang thực hiện yêu cầu ajax trong Javascript để lấy JWT từ Trình xác thực WebAPI của tôi. Đây là tôi js chức năng:Yêu cầu Mã thông báo với JQuery từ API Web

function authenticateUser(credentials) { 
    var body = { 
     grant_type: 'password', 
     client_id: 'myClientId', 
     client_secret: 'myClientSecret', 
     username: credentials.name, 
     password: credentials.password 
    }; 

    $.ajax({ 
     url: 'http://localhost:9000/token', 
     type: 'POST', 
     dataType: 'json', 
     contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
     /* data: JSON.stringify(body), /* wrong */ 
     data: body, /* right */ 
     complete: function(result) { 
      //called when complete 
      alert(result); 
     }, 

     success: function(result) { 
      //called when successful 
      alert(result); 
     }, 

     error: function(result) { 
      //called when there is an error 
      alert(result); 
     }, 
    }); 
    session.isAuthenticated(true); 
    return true; 
} 

Mặc dù nội dung được gửi đúng cách trong mắt tôi, OAuthValidateClientAuthenticationContext có giá trị chỉ null.

dữ liệu biểu mẫu của tôi sao chép từ giao diện điều khiển:

{ "grant_type": "password", "client_id": "myClientId", "client_secret": "myClientSecret", "username": "demo" , "mật khẩu": "123"}

+0

Yêu cầu Ajax của bạn trông tương tự như yêu cầu tôi đã sử dụng. Sự khác biệt chính tôi nhận thấy là xâu chuỗi dữ liệu tải trọng. Bạn có phải làm điều này? Tôi không bao giờ có. –

+0

Đó là vấn đề. Cảm ơn bạn David. –

+0

không sao cả. Vui vì nó là một sự thay đổi đơn giản bởi vì nó có vẻ như thế này đã đi đúng hướng :) –

Trả lời

2

Có vẻ như bạn có thể đã giải quyết xong nhưng, điều này đã xảy ra với tôi. Sử dụng phần trên và thiết lập cơ thể để làm việc này.

var body = { 
    grant_type: 'password', 
    username: credentials.name, 
    password: credentials.password 
}; 
Các vấn đề liên quan