簡體   English   中英

使用jQuery / ajax進行基本身份驗證

[英]Basic Authentication using jQuery/ajax

我正在嘗試創建基本身份驗證頁面,其中我的表單有三個字段

  1. 用戶名
  2. 密碼
  3. 授權類型

在提交表單時,我只想在JSON格式的HTML上顯示來自服務器的返回響應。 我對Web服務的AJAX調用還需要設置Authorization標頭。 但不知何故標題沒有設置。 我在嘗試

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

但是當我在控制台中調試代碼時,似乎斷點永遠不會進入這個功能。 我是Ajax的新手,並通過在互聯網上搜索下面的代碼。 我在下面發布完整的代碼。

碼:

$(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();
    });

});

它導致不在我的代碼中設置標頭的原因。 請指正。

在網絡標簽的控制台(谷歌瀏覽器)中,我可以看到下面的請求標題

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

控制台中出現以下錯誤。 在此輸入圖像描述

當從Google Chrome的Advanced Rest Client擴展程序調用相同的API時,它會顯示所有標題

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

我只是使用文件協議運行我的網頁。

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

我不確定這是否會導致問題。

我通常會添加這樣的Headers(代碼來自“在Sharepoint中使用Web代理查詢遠程服務”, 這里 ):

    $.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
});

讓我知道事情的后續

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM