18

I want to use JavaScript to perform a POST request using the common "Authorization: Basic" method. The server hosts an OWIN C# App and on successful authentication it should give me a token in JSON format.

This is the wireshark equivalent of what I want to 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 it possible to do so? If so, how?

3

3 Answers 3

30

This is the javascript request:

var clientId = "MyApp";
var clientSecret = "MySecret";

// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
var authorizationBasic = window.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 this is the jQuery version:

var clientId = "MyApp";
var clientSecret = "MySecret";

// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
var authorizationBasic = window.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 the clientId and the clientSecret in a string base64 using a jquery plugin. I am pretty sure you can find something similar in plain javascript.

This is a project where you have a Owin Web Api running in a console and a project where you can test your request in a web page using jQuery or the plain vanilla javascript. You might need to change the urls for the requests.

Sign up to request clarification or add additional context in comments.

3 Comments

Looks like plain window.btoa should do the job for $.base64.btoa...
What is the difference between clientId and username in the code?
@Nuhman: ClientId identifies your client application: it could be a mobile app, desktop or another web app. You could provide different configurations for each one of those.
2

This is a quite old question but I think there is no problem to update answer.

Here FETCH api in JavaScript to post in JavaScript

fetch("https://tugrulyildirim.com/api/post-some-data-uri", {
    method: 'POST',
    headers: new Headers({
        "Authorization": localStorage.getItem('token'),
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
        "X-Requested-With": "XMLHttpRequest",
    }),
    body: {
        "name": "John",
        "surname": "Doe"
    }
}).then((response) => response.json()).then(responseData => {/* do something with responseData*/}).catch(error => {console.log(error);});

Comments

-1

This method works for me.

   var authorizationHeader = 'Basic ' + btoa('pk_test_code');

   var reqData = {}; var obj = {}; var obj2a = {}; var obj2b = {}; var obj3 = {};
   obj3['card_number'] = '4343434343434345'; obj3['exp_month'] = 5; obj3['exp_year'] = 26; obj3['cvc'] = '111';
   obj2b['details'] = obj3; obj2a['type'] = 'card';
   obj['attributes'] = {}; Object.assign(obj['attributes'], obj2a, obj2b);
   reqData['data'] = {}; Object.assign(reqData['data'], obj);

   var xmlHTTPReq = new XMLHttpRequest(); xmlHTTPReq.open('POST', 'https://api.paymongo.com/v1/payment_methods', true);
   xmlHTTPReq.setRequestHeader('Authorization', authorizationHeader); xmlHTTPReq.setRequestHeader('Content-Type', 'application/json'); xmlHTTPReq.setRequestHeader('Accept', 'application/json');
   xmlHTTPReq.send(JSON.stringify(reqData));
   xmlHTTPReq.onreadystatechange = function(){
      if(xmlHTTPReq.readyState === 4){
         if(xmlHTTPReq['status'] == '200'){
            alert(xmlHTTPReq.responseText);

         }
         else{
            var errRes = JSON.parse(xmlHTTPReq.responseText); var errMsg = errRes['error'];
            alert(errMsg);
         }
      }
   };

$.ajax also works for me but this convert numeric data into string. I recommend new XMLHttpRequest()

$.post and fetch does not work for me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.