Basic Authentication using jQuery/ajax

廉价感情. 提交于 2019-12-23 10:01:04

问题


I am trying to create basic authentication page where my form has three fields

  1. username
  2. password
  3. grant type

On submitting a form I just want to display returned response from a server on my HTML in JSON format. My AJAX call to web service also requires Authorization header to be set. But somehow headers are not getting set. I am trying

 beforeSend : function(xhr)
   {
       xhr.setRequestHeader('Authorization', "Basic ******");
       xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
    }

But when I debug the code in console it seems breakpoint never goes into this function. I am a newbie to Ajax and have tried below code by googling on the internet. I am posting whole code below.

CODE:

$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        // get the form data
        var formData = {
            'username': $('#username').val(),
            'password': $('#password').val(),
            'grant_type': $('#grantType').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', 
            url         : 'http://localhost:9090/oauth/token', 
            beforeSend: function (xhr)
            {
                xhr.setRequestHeader("Authorization", "Basic ******");
                xhr.setRequestHeader("contentType", "application/json;charset=UTF-8");
            },
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
                        encode          : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 
                alert(data);

                // here we will handle errors and validation messages
            })

            .fail(function (jqXHR, textStatus){
                alert('Status : ' + textStatus + '' + JSON.stringify(jqXHR));
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

What it cause not to set headers in my code. Please correct me.

In console(Google Chrome) in Network tab, I can see below request headers

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type, contenttype
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.1.128:9090
Origin:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

and below error appears in console.

And when calling same API from Advanced Rest Client extension for Google Chrome it shows me all the headers

User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
contentType: application/json;charset=UTF-8
Authorization: Basic **********
Content-Type: application/x-www-form-urlencoded 
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

I am simply running my web page using file protocol.

Ex: file:///E:/Mahendra/Practice%20Example/Test/OauthTest.html

I am not sure if this is causing a problem.


回答1:


I usually add Headers like this ( the code is from a "Query a remote service using the web proxy in Sharepoint", here ) :

    $.ajax({
    url: "../_api/SP.WebProxy.invoke",
    type: "POST",
    data: JSON.stringify(
        {
            "requestInfo": {
                "__metadata": { "type": "SP.WebRequestInfo" },
                "Url": url,
                "Method": "GET",
                "Headers": {
                    "results": [{
                        "__metadata": { "type": "SP.KeyValue" },
                        "Key": "Accept",
                        "Value": "application/json;odata=verbose",
                        "ValueType": "Edm.String"
                    }]
                }
            }
        }),
    headers: {
        "Accept": "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "Authorization": "yourkeyvalueforauthorizationEXAMPLE",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: successHandler,
    error: errorHandler
});

Let me know how it goes



来源:https://stackoverflow.com/questions/32943042/basic-authentication-using-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!