html - Make an HTTP POST authentication basic request using Javascript -


i want use javascript perform post request using common "authorization: basic" method. server hosts owin c# app , on successful authentication should give me token in json format.

this wireshark equivalent of want accomplish using plain javascript:

    post /connect/token http/1.1     authorization: basic c2lsawnvbjpgnjixrjq3mc05nzmxltrbmjutodbfri02n0e2rjddnuy0qjg=     content-type: application/x-www-form-urlencoded     host: localhost:44333     content-length: 40     expect: 100-continue     connection: keep-alive      http/1.1 100 continue      grant_type=client_credentials&scope=api1http/1.1 200 ok     cache-control: no-store, no-cache, max-age=0, private     pragma: no-cache     content-length: 91     content-type: application/json; charset=utf-8     server: microsoft-httpapi/2.0     date: fri, 17 jul 2015 08:52:23 gmt      {"access_token":"c1cad8180e11deceb43bc1545c863695","expires_in":3600,"token_type":"bearer"} 

is possible so? if so, how?

this javascript request:

var clientid = "myapp"; var clientsecret = "mysecret";  var authorizationbasic = $.base64.btoa(clientid + ':' + clientsecret);  var request = new xmlhttprequest(); request.open('post', oauth.authorizationserver, true); request.setrequestheader('content-type', 'application/x-www-form-urlencoded; charset=utf-8'); request.setrequestheader('authorization', 'basic ' + authorizationbasic); request.setrequestheader('accept', 'application/json'); request.send("username=john&password=smith&grant_type=password");  request.onreadystatechange = function () {     if (request.readystate === 4) {        alert(request.responsetext);     } }; 

and jquery version:

var clientid = "myapp"; var clientsecret = "mysecret";  var authorizationbasic = $.base64.btoa(clientid + ':' + clientsecret);  $.ajax({     type: 'post',     url: oauth.authorizationserver,     data: { username: 'john', password: 'smith', grant_type: 'password' },     datatype: "json",     contenttype: 'application/x-www-form-urlencoded; charset=utf-8',     xhrfields: {        withcredentials: true     },     // crossdomain: true,     headers: {        'authorization': 'basic ' + authorizationbasic     },     //beforesend: function (xhr) {     //},     success: function (result) {        var token = result;     },     //complete: function (jqxhr, textstatus) {     //},     error: function (req, status, error) {     alert(error);     } }); 

in both situation i've encoded clientid , clientsecret in string base64 using jquery plugin. pretty sure can find similar in plain javascript.

this project have owin web api running in console , project can test request in web page using jquery or plain vanilla javascript. might need change urls requests.


Comments