使用Javascript发出HTTP身份验证后基本请求
我想使用JavaScript来执行POST请求,使用通用的“Authorization:Basic”方法。服务器托管一个OWIN C#应用程序,在成功验证后,它应该给我一个JSON格式的令牌 这与我希望使用纯Javascript实现的wireshark相当:使用Javascript发出HTTP身份验证后基本请求,javascript,html,http,authentication,owin,Javascript,Html,Http,Authentication,Owin,我想使用JavaScript来执行POST请求,使用通用的“Authorization:Basic”方法。服务器托管一个OWIN C#应用程序,在成功验证后,它应该给我一个JSON格式的令牌 这与我希望使用纯Javascript实现的wireshark相当: POST /connect/token HTTP/1.1 Authorization: Basic c2lsaWNvbjpGNjIxRjQ3MC05NzMxLTRBMjUtODBFRi02N0E2RjdDNUY0Qjg=
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将clientId
和clientSecret
编码为字符串base64。我很肯定你可以在纯javascript中找到类似的东西
这是一个在控制台中运行OWINWebAPI的项目,在这个项目中,您可以使用jQuery或普通javascript在网页中测试您的请求。您可能需要更改请求的URL。请参阅文档-Vanilla Javascript或jQuery?有关此问题的任何更新?grazie Alberto!ora lo provoPrego:-)让我知道。看起来像普通的
窗口。btoa
应该为$做这项工作。base64.btoa
…代码中的clientId
和username
有什么区别?@Nuhman:clientId识别您的客户端应用程序:它可以是移动应用程序、桌面或其他web应用程序。您可以为其中的每一个提供不同的配置。