使用Javascript进行HTTP POST身份验证基本请求

Gia*_*ini 12 html javascript authentication http owin

我想使用JavaScript来使用常见的"Authorization:Basic"方法执行POST请求.服务器托管一个OWIN C#App,成功验证后,它应该给我一个JSON格式的令牌.

这是wireshark等同于我想用纯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"}
Run Code Online (Sandbox Code Playgroud)

有可能这样做吗?如果是这样,怎么样?

Lef*_*tyX 22

这是javascript请求:

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

这是jQuery版本:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我已经编码clientIdclientSecret使用jQuery的字符串的base64 插件.我很确定你可以在普通的javascript中找到类似的东西.

这是一个项目,您可以在控制台和项目中运行Owin Web Api,您可以使用jQuery或普通的jilla javascript在网页中测试您的请求.您可能需要更改请求的URL.

  • 看起来普通的`window.btoa`应该为`$ .base64.btoa`工作...... (4认同)