javascript - 我没有根据需要获得 32 个字符的十六进制签名
问题描述
我必须签署我的 lastfm api:
- 签署您的电话
通过首先按参数名称的字母顺序对调用中发送的所有参数进行排序,然后使用方案将它们连接成一个字符串,从而构建您的 api 方法签名。所以调用 auth.getSession 你可能有:
api_keyxxxxxxxxxmethodauth.getSessiontokenxxxxxxx
确保您的参数是 utf8 编码的。现在将您的秘密附加到此字符串。最后,生成结果字符串的 md5 哈希。例如,对于密码等于“mysecret”的帐户,您的 api 签名将是:
api 签名 = md5("api_keyxxxxxxxxmethodauth.getSessiontokenxxxxxxxxxmysecret")
其中 md5() 是一个 md5 散列操作,它的参数是要散列的字符串。散列操作应返回 32 个字符的十六进制 md5 散列。
var myAPI_key="b6720a4ef50c0a1f63419e334fbf9c74";
var myshared_secret="5df5d9e40e9375f043edf1e1fb629236";
var url = window.location.href; // or window.location.href for current url
var captured = /token=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
console.log(captured);
function calculateApiSignature(){
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
var string = "api_key" + "b6720a4ef50c0a1f63419e334fbf9c74"+ "methodauth.getSessiontoken"+captured;
var textoUtf8 = encodeURI(string);
textoUtf8 = textoUtf8 + myshared_secret;
console.log("String a firmar : " + textoUtf8);
var ApiSignature = textoUtf8.hashCode();
console.log("Api Signature" + ApiSignature);
}
<!DOCTYPE html>
<html>
<head>
<title>Menu principal Last FM</title>
<meta charset="utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- <script type="text/javascript" src="./js/constants.js"></script>-->
<script type="text/javascript" src="./js/main.js"></script>
</head>
<body>
<h1>Im login to</h1>
<div id="userData">
<!--<img src="https://lastfm-img2.akamaized.net/i/u/34s/cc637716959b4acecaa1a307e300f61f.png" />-->
</div>
<div id="success">
<div id="artistName"></div>
<div id="artistImage"></div>
<div id="artistBio"></div>
</div>
<div id="error"></div>
<button type="button" onclick="loadUserInfoXMLDoc()">Get User information</button>
<br><br>
<button type="button" onclick="loadChartTopArtistsJSONDoc()">Get Top Artist Chart</button>
<button type="button" onclick="calculateApiSignature()">Calculate API</button>
<table id="demo"></table>
<p id="artist"></p>
</body>
</html>
不知道我错过了什么或做错了什么....我想我按照说明获取 api_signature ....
然后,一旦我有了 api_signature,我认为 id 必须拨打电话:
$.ajax({
type : 'GET',
url : 'http://ws.audioscrobbler.com/2.0/?',
data : 'api_key=b6720a4ef50c0a1f63419e334fbf9c74&' +
'token:xxxx&'+
'api_sig:apisig from above',
dataType : 'json',
success : function(data) {
//hooray
},
error : function(code, message){
//upset
}
});
解决方案
我找到并为我工作的解决方案:
/*
Metode: https://www.last.fm/api/show/auth.getSession
Objective: Fetch a session key for a user. The third step in the authentication process. See the authentication how-to for more information.
( as we are making a web application...https://www.last.fm/api/webauth)
Params:
token (Required) : A 32-character ASCII hexadecimal MD5 hash returned by step 1 of the authentication process (following the granting of
permissions to the application by the user)
api_key (Required) : A Last.fm API key.
api_sig (Required) : A Last.fm method signature. See authentication for more information
Api_sig requereix uns quants canvis ( calculs complicats que he anant fent)...
Result JSON expected:
exit ->
{
"session": {
"subscriber": 0,
"name": "edufissure",
"key": "fem3L_nnsWNwD_yGL4mtVRPOlblLynx5"
}
}
error ->
{
"error": 4,
"message": "Unauthorized Token - This token has not been issued"
}
*/
function calculateApiSignatureStack()
{
/*note in captured i have a string with the actual token....
You can get it from your url:
var url = window.location.href; // or window.location.href for current url
var captured = /token=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
*/
// Set elsewhere but hacked into this example:
var last_fm_data = {
'last_token':captured,
'user': 'bob',
'secret': '5df5d9e40e9375f043edf1e1fb629236'
};
// Kick it off.
last_fm_call('auth.getSession', {'token': last_fm_data['last_token']});
// Low level API call, purely builds a POSTable object and calls it.
function last_fm_call(method, data){
// param data - dictionary.
last_fm_data[method] = false;
// Somewhere to put the result after callback.
// Append some static variables
data.api_key = "b6720a4ef50c0a1f63419e334fbf9c74";
//data['format'] = 'json';
data['method'] = method;
post_data = last_fm_sign(data);
/*
.*/
console.log("Post data: Last token " + post_data.token + "ApiKey: "+ post_data.api_key + "ApiSig: " + post_data.api_sig);
sessionStorage.setItem("myApiSig",post_data.api_sig );
var last_url="http://ws.audioscrobbler.com/2.0/?";
$.ajax({
type: "GET",
url: last_url,
data : 'method=auth.getSession' +
'&token='+
captured+
'&api_key=b6720a4ef50c0a1f63419e334fbf9c74' +
'&api_sig='+
post_data.api_sig+
'&format=json',
//data: post_data,
dataType: 'json',
success: function(res){
last_fm_data[method] = res;
//var myresposta = JSON.parse(res);
console.log("Resposta: Name " + res.session.name);// Should return session key.
console.log("Resposta: Key " + res.session.key);
//store session key for further authenticate operations...
sessionStorage.setItem("mySessionKey", res.session.key);
},
error : function(code, message){
console.log("Error en autenticacion");
}
});
}
function last_fm_sign(params){
ss = "";
st = [];
so = {};
so['api_key'] = params['api_key'];
so['token'] = params['token'];
Object.keys(params).forEach(function(key){
st.push(key); // Get list of object keys
});
st.sort(); // Alphabetise it
st.forEach(function(std){
ss = ss + std + params[std]; // build string
});
ss += last_fm_data['secret'];
// console.log(ss + last_fm_data['secret']);
// api_keyAPIKEY1323454formatjsonmethodauth.getSessiontokenTOKEN876234876SECRET348264386
//hashed_sec = $.md5(unescape(encodeURIComponent(ss)));
var hashed_sec = md5(unescape(encodeURIComponent(ss))); // "2063c1608d6e0baf80249c42e2be5804"
console.log("La apiSig es: " + hashed_sec);
so['api_sig'] = hashed_sec; // Correct when calculated elsewhere.
return so; // Returns signed POSTable object
}
}
推荐阅读
- jquery - 并排的图像一个一个地闪烁——就像一个序列
- react-admin - 获取 ReferenceManyField 计数?
- performance - get_surface().blit() 与 var_screen.blit()
- javascript - 如何在reducer的映射数组中映射嵌套数组
- android-layout - 如何在 declare-styleable 中设置自定义属性的默认值
- python - 除了blueZ(Pybluez)之外,还有其他方法可以获取RSSI值吗
- php - 如何将 Outlook 条件 CSS 添加到 wooocmmerce 订单电子邮件模板自定义?
- doxygen - 如何从 doxygen RTF 输出中删除文件列表和命名空间列表
- javascript - javascript中的onclick与php中的while循环
- yaml - 在 Hugo v0.55 的 YAML 文件中获取 Hugo 的版本号