使用 JavaScript 的基本身份验证

Basic Authentication Using JavaScript(使用 JavaScript 的基本身份验证)

本文介绍了使用 JavaScript 的基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我看过的一些参考资料:

1) 用于 HTTP 基本身份验证的纯 JavaScript 代码?

2) 如何在从 javascript 调用 REST API 中进行 http 身份验证

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

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

方法: POST

网址:您的令牌端点

正文:grant_type=client_credentials

标头参数:

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

以下是我的 Javascript 和 HTML 代码.

JavaScript:

var userName = "clientID";var passWord = "secretKey";功能验证用户(用户,密码){var token = 用户 + ":" + 密码;//我应该编码这个值吗??????有关系吗???//Base64 编码 ->BTOAvar hash = btoa(token);返回基本"+哈希;}函数 CallWebAPI() {//新的 XMLHTTPRequestvar request = new XMLHttpRequest();request.open("POST", "https://xxx123.casio.com/oauth/token", false);request.setRequestHeader("授权", authenticateUser(userName, passWord));请求.发送();//查看请求状态警报(请求.状态);response.innerHTML = request.responseText;}

HTML:

<div id="响应"></div>

解决方案

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

var token_//变量将存储令牌var userName = "clientID";//应用客户端IDvar passWord = "secretKey";//应用程序客户端秘密var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token";//您的应用程序令牌端点var request = new XMLHttpRequest();函数 getToken(url, clientID, clientSecret) {变量键;request.open("POST", url, true);request.setRequestHeader("内容类型", "应用程序/json");request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret);//指定凭据以在请求时接收令牌request.onreadystatechange = function () {如果(request.readyState == request.DONE){var response = request.responseText;var obj = JSON.parse(response);键 = obj.access_token;//存储accesstoken的值令牌_ =键;//将令牌存储在全局变量token_"中,或者您可以简单地从函数中返回访问令牌的值}}}//获取令牌getToken(casioTokenUrl, 用户名, 密码);

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

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

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

function CallWebAPI() {var request_ = new XMLHttpRequest();var encodedParams = encodeURIComponent(params);request_.open("GET", "https://xxx123.casio.com/rest/v1/tables/", true);request_.setRequestHeader("授权", "承载"+ token_);request_.send();request_.onreadystatechange = function () {if (request_.readyState == 4 && request_.status == 200) {var response = request_.responseText;var obj = JSON.parse(response);//根据需要处理数据...}}}

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

I am building an application that consumes the Caspio API. I am having some trouble authenticating against their API. I have spent 2-3 days trying to figure this out but it may be due to some understanding on my end. I have read countless articles on stackoverflow post and otherwise but have not solved the issue. Below is a code example of my solution based on what i have looked at and i am getting a 400 Status code message; What am i doing wrong here? (Please provide well commented code example and i would prefer to NOT have links posted here referencing other material as i have looked at these extensively. Thanks!):

Some references i have looked at:

1) Pure JavaScript code for HTTP Basic Authentication?

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

I would like to use this authentication method as described by caspio below:

As an alternative to including credentials in the request body, a client can use the HTTP Basic authentication scheme. In this case, authentication request will be setup in the following way:

Method: POST

URL: Your token endpoint

Body: grant_type=client_credentials

Header parameter:

Authorization: Basic Basic authentication realm

Below are my Javascript and HTML code.

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();" />

解决方案

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

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);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

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... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

这篇关于使用 JavaScript 的基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 JavaScript 的基本身份验证

基础教程推荐