gpt4 book ai didi

javascript - 使用 Javascript 发出 HTTP POST 身份验证基本请求

转载 作者:技术小花猫 更新时间:2023-10-29 12:38:16 25 4
gpt4 key购买 nike

我想使用 JavaScript 使用常见的“Authorization: Basic”方法执行 POST 请求。服务器托管一个 OWIN C# 应用程序,在成功验证后,它应该给我一个 JSON 格式的 token 。

这是 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"}

有可能吗?如果是,怎么办?

最佳答案

这是 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);
}
};

这是 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);
}
});

在这两种情况下,我都使用 jquery pluginclientIdclientSecret 编码为字符串 base64| .我很确定您可以在纯 JavaScript 中找到类似的东西。

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

关于javascript - 使用 Javascript 发出 HTTP POST 身份验证基本请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com