【问题标题】:Basic Authentication Using JavaScript使用 JavaScript 的基本身份验证
【发布时间】:2016-04-23 23:35:59
【问题描述】:

我正在构建一个使用Caspio API 的应用程序。我在针对他们的 API 进行身份验证时遇到了一些问题。我花了 2-3 天试图弄清楚这一点,但这可能是由于我的一些理解。我已经阅读了无数关于stackoverflow帖子的文章,但还没有解决这个问题。下面是我的解决方案的代码示例,基于我所查看的内容,我收到了 400 状态代码消息;我在这里做错了什么? (请提供注释良好的代码示例,我希望在此处发布引用其他材料的链接,因为我已经广泛查看了这些材料。谢谢!):

我看过的一些参考资料:

1)Pure JavaScript code for HTTP Basic Authentication?

2)How to make http authentication in REST API call from javascript

我想使用下面 caspio 描述的这种身份验证方法:

作为在请求正文中包含凭据的替代方法,客户端可以使用 HTTP 基本身份验证方案。在这种情况下,将通过以下方式设置身份验证请求:

方法: POST

网址:您的令牌端点

正文:grant_type=client_credentials

标头参数:

授权:基本基本身份验证领域

以下是我的 Javascript 和 HTML 代码。

JavaScript:

var userName = "clientID";
var passWord = "secretKey";

function authenticateUser(user, password)
{
    var token = user + ":" + password;

    // Should i be encoding this value????? does it matter???
    // Base64 Encoding -> btoa
    var hash = btoa(token); 

    return "Basic " + hash;
}

function CallWebAPI() {

    // New XMLHTTPRequest
    var request = new XMLHttpRequest();
    request.open("POST", "https://xxx123.caspio.com/oauth/token", false);
    request.setRequestHeader("Authorization", authenticateUser(userName, passWord));  
    request.send();
    // view request status
    alert(request.status);
    response.innerHTML = request.responseText;
}

HTML:

<div>
<div id="response">

</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />

【问题讨论】:

    标签: javascript authentication xmlhttprequest


    【解决方案1】:

    在花了很多时间研究这个之后,我想出了解决方案;在这个解决方案中,我没有使用基本身份验证,而是使用 oAuth 身份验证协议。但是要使用基本身份验证,您应该能够在“setHeaderRequest”中指定这一点,只需对代码示例的其余部分进行最少的更改。我希望这将能够在未来对其他人有所帮助:

    var token_ // variable will store the token
    var userName = "clientID"; // app clientID
    var passWord = "secretKey"; // app clientSecret
    var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
    var request = new XMLHttpRequest(); 
    
    function getToken(url, clientID, clientSecret) {
        var key;           
        request.open("POST", url, true); 
        request.setRequestHeader("Content-type", "application/json");
        request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
        request.onreadystatechange = function () {
            if (request.readyState == request.DONE) {
                var response = request.responseText;
                var obj = JSON.parse(response); 
                key = obj.access_token; //store the value of the accesstoken
                token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
            }
        }
    }
    // Get the token
    getToken(caspioTokenUrl, userName, passWord);
    

    如果您在某些请求上使用 Caspio REST API,您可能必须对端点的某些请求的参数进行编码;请参阅有关此问题的 Caspio 文档;

    注意:encodedParams 在本示例中未使用,但在我的解决方案中使用。

    现在您已经从令牌端点存储了令牌,您应该能够成功地验证来自您应用程序的 caspio 资源端点的后续请求

    function CallWebAPI() {
        var request_ = new XMLHttpRequest();        
        var encodedParams = encodeURIComponent(params);
        request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
        request_.setRequestHeader("Authorization", "Bearer "+ token_);
        request_.send();
        request_.onreadystatechange = function () {
            if (request_.readyState == 4 && request_.status == 200) {
                var response = request_.responseText;
                var obj = JSON.parse(response); 
                // handle data as needed... 
    
            }
        }
    } 
    

    此解决方案只考虑如何在纯 javascript 中使用 Caspio API 成功发出经过身份验证的请求。我敢肯定还有很多缺陷......

    【讨论】:

    • 这实际上不是问题的解决方案,它专门针对基本身份验证。
    • 我想我在原始答案中指定了您的观点。虽然,这是使用不同身份验证方法完成相同任务的替代方法。请阅读完整答案。
    【解决方案2】:

    今天我们使用Bearer tokenBasic Authentication 更频繁,但如果你想先让Basic Authentication 获得Bearer 令牌,那么有几种方法:

    const request = new XMLHttpRequest();
    request.open('GET', url, false, username,password)
    request.onreadystatechange = function() {
            // D some business logics here if you receive return
       if(request.readyState === 4 && request.status === 200) {
           console.log(request.responseText);
       }
    }
    request.send()
    

    完整的语法是here

    使用 Ajax 的第二种方法:

    $.ajax
    ({
      type: "GET",
      url: "abc.xyz",
      dataType: 'json',
      async: false,
      username: "username",
      password: "password",
      data: '{ "key":"sample" }',
      success: function (){
        alert('Thanks for your up vote!');
      }
    });
    

    希望这为您提供了使用 JS 开始 API 调用的提示。在 Angular、React 等框架中,有更强大的方法可以使用 Basic AuthenticationOauth Authentication 进行 API 调用。只是探索它。

    【讨论】:

      【解决方案3】:

      EncodedParams 变量被重新定义为 params 变量将不起作用。您需要对变量进行相同的预定义调用,否则看起来可能需要更多的工作。干杯! json 不习惯它在 php 中的全部功能,有更好的方法来调用 json,我现在不记得了。

      【讨论】:

        【解决方案4】:

        将用户名、密码、token_ 和密钥变量的 var 更改为 const。

        【讨论】:

        • 这不相关,不保证作为答案发布。
        • @Tom ,我认为但是,这个答案并不保证标志。我投了反对票
        猜你喜欢
        • 2014-09-15
        • 2015-08-12
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        • 2013-05-30
        • 2012-08-30
        • 1970-01-01
        • 2011-05-19
        相关资源
        最近更新 更多