Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Set Authorization headers at HTML Form or at A href

I have this code:

            $.ajax({
                url: "http://localhost:15797/api/values",
                type: 'get',
                contentType: 'application/json',
                headers: {
                    "Authorization": "Bearer " + token
                }
            })

works fine, but I want to do that without using Ajax, I want something like that:

        <form action="http://localhost:15797/api/values" method="get">
            <input type="hidden" name="headers[Authorization]" value="Bearer token" />
            <input type="submit" />
        </form>

Is it possible? Or just do something like that without XMLHttpRequest? How?

like image 542
Andre Avatar asked Jul 17 '16 14:07

Andre


1 Answers

You need to send the Authorization argument in the HTTP request header, it's imposed by OAuth flows. Of course you can change it by making changes in OAuth server's code but if you've got no control on the OAuth server's code it's not possible.

So answering your question, no you can't send them with the form's posted data. However, obviously you can put them in the hidden field and write a JS code to read it from the field and put it in the request header.

e.g.

HTML:

<input id="tokenField" type="hidden" />
<input id="submitButton" type="button" />

Javascript:

$('#submitButton').on('click',function(){
    $.ajax({
          url: "http://localhost:15797/api/values",
          type: 'GET',
          contentType: 'application/json',
          headers: {
                    "Authorization": "Bearer " + $('#tokenField').val()
                 },
          async: false
            }});

Notice the async: false makes your call synchronous, just like a submit. And if you need to post other data to the server you can change the type: 'GET' to type: 'POST' and add another field named data and pass your form data through its value :

<input id="firstName" type="text" />
<input id="lastName" type="text" />
<input id="tokenField" type="hidden" />
<input id="submitButton" type="button" />

$('#submitButton').on('click',function(){
    $.ajax({
          url: "http://localhost:15797/api/values",
          type: 'POST',
          data: { 
                  firstName: $('#firstName').val(),
                  lastName: $('#lastName').val()
                },
          contentType: 'application/json',
          headers: {
                    "Authorization": "Bearer " + $('#tokenField').val()
                 },
          async: false
            })
});
like image 89
akardon Avatar answered Oct 29 '22 14:10

akardon