我在Ionic2应用程序中配置OAuth时遇到问题。我不在OAuth的前端部分使用任何框架/库。
问题是每次尝试检索access_token时都会得到401: Unauthorized: Invalid signature
。(向下滚动查看代码,用注释缩进问题)
现在我的服务器被设置为三条腿的OAuth应用程序(如此处所述)。这意味着将有 3 个端点:
1./request_token
(这个有效)
请求(GET 参数):
oauth_version : ...
oauth_nonce: ....
oauth_timestamp: ...
oauth_consumer_key: ...
oauth_signature_method: ...
oauth_signature: ...
响应:
oauth_token: .... (temporary)
oauth_token_secret: ....
2./authorize
(这个也可以工作 ->打开浏览器进行身份验证)
请求(GET 参数):
oauth_token: ....
oauth_callback: ....
响应
oauth_token: ....
oauth_verifier: ...
3./access_token
(这个不起作用)
请求(GET 参数)
oauth_token: ....
oauth_verifier: ....
oauth_version : ...
oauth_nonce: ....
oauth_timestamp: ...
oauth_consumer_key: ...
oauth_signature_method: ...
oauth_signature: ...
响应:
oauth_token: .... (permanent)
oauth_secret: ....
最后一个不起作用,尽管我以相同的方式设置signatureBaseString
并根据指南设置密钥
完整的代码,包括其他 2 个调用(混乱是的,我知道)
让它工作,让它变得更好,让它更快
目前在"让它工作">
login() {
try{
this.getRequestToken();
}catch(err) {
alert("ERROR: " + JSON.stringify(err));
}
}
getRequestToken() {
alert("in request token");
let token_base_url = "https://servername/oauth/request_token";
var oauth_nonce = this.generateNonce();
var oauth_timestamp = this.getCurrentTimeStamp();
let signatureBaseString = this.createSignatureBaseString(token_base_url, oauth_nonce, oauth_timestamp);
let encryptedSignature = this.generateEncryptedSignature(signatureBaseString);
let token_url = this.createOauthUrl(token_base_url, oauth_nonce, oauth_timestamp, encryptedSignature);
this.http.get(token_url).subscribe(data => {
this.doAuthorize(data);
}, err => {
alert("ups: " + JSON.stringify(err));
});
}
doAuthorize(data: any) {
alert("in do authorize");
let responseParameters = data.text().split("&");
let requestToken = responseParameters[0].split("=")[1];
let requestTokenSecret = responseParameters[1].split("=")[1];
let authorize_url = `https://servername/oauth/authorize?oauth_token=${requestToken}&oauth_callback=${encodeURIComponent('http://localhost/callback')}`;
let ref = cordova.InAppBrowser.open(authorize_url, '_blank', 'location=yes');
ref.addEventListener("loadstart", (event) => {
// little workaround to make this work without actually having a callback url
if((event.url).indexOf('http://localhost/callback') == 0) {
ref.removeEventListener("exit", (event)=>{});
ref.close();
this.getAccessToken(event.url, requestTokenSecret, requestToken);
}
});
ref.addEventListener("exit", (event) => {
alert("closeseddd");
});
}
getAccessToken(url:string, requestTokenSecret: string, requestToken: string) {
alert("in get accesstoken");
let access_token_base_url = "https://servername/oauth/access_token";
var responseParameters = ((url).split("?")[1].split("&"));
let authorizationToken = responseParameters[0].split("=")[1];
let oauth_verifier = responseParameters[1].split("=")[1];
let oauth_timestamp = this.getCurrentTimeStamp();
let oauth_nonce = this.generateNonce();
let signatureBaseString = this.createSignatureBaseString(access_token_base_url, oauth_nonce, oauth_timestamp, authorizationToken, oauth_verifier);
let encryptedSignature = this.generateEncryptedSignature(signatureBaseString, requestTokenSecret);
let access_token_url = this.createOauthUrl(access_token_base_url, oauth_nonce, oauth_timestamp, encryptedSignature, authorizationToken, oauth_verifier);
this.http.get(access_token_url).subscribe(response => {
alert(response.text());
}, err => {
alert("nooooo " + JSON.stringify(err));
});
}
getCurrentTimeStamp(): number {
return Math.round((new Date()).getTime()/1000.0);
}
generateNonce(): string {
return Math.random().toString(36).replace(/[^a-z]/, '').substr(2);
}
createSignatureBaseString(url: string, nonce: string, timestamp: number, oauth_token?: string, oauth_verifier?: string): string {
let baseString = "GET&" + encodeURIComponent(url) + "&";
baseString += encodeURIComponent(`oauth_consumer_key=${this.oauth_consumer_key}&`);
baseString += encodeURIComponent(`oauth_nonce=${nonce}&`);
baseString += encodeURIComponent(`oauth_signature_method=${this.oauth_signature_method}&`);
baseString += encodeURIComponent(`oauth_timestamp=${timestamp}&`);
baseString += encodeURIComponent(`oauth_version=1.0`);
if(oauth_token) {
baseString += encodeURIComponent(`&oauth_token=${oauth_token}`);
}
if(oauth_verifier) {
baseString += encodeURIComponent(`&oauth_verifier=${oauth_verifier}`);
}
alert("generated baseString: " + baseString);
return baseString;
}
createOauthUrl(baseUrl: string, nonce: string, timestamp: number, signature: string, oauth_token?: string, oauth_verifier?: string): string {
var url = `${baseUrl}?`;
url += `oauth_consumer_key=${this.oauth_consumer_key}&`;
url += `oauth_nonce=${nonce}&`;
url += `oauth_signature_method=HMAC-SHA1&`;
url += `oauth_timestamp=${timestamp}&`;
url += `oauth_version=1.0&`;
url += `oauth_signature=${signature}`;
if(oauth_token) {
url += `&oauth_token=${encodeURIComponent(oauth_token)}`;
}
if(oauth_verifier) {
url += `&oauth_verifier=${encodeURIComponent(oauth_verifier)}`;
}
alert("generated url : " + url);
return url;
}
generateEncryptedSignature(signatureBaseString: string, tokenSecret?: string): string {
let secret_signing_key = this.oauth_consumer_secret + "&";
if(tokenSecret) {
secret_signing_key += tokenSecret;
}
let oauth_signature = CryptoJS.HmacSHA1(signatureBaseString, secret_signing_key);
let encryptedSignature = encodeURIComponent(CryptoJS.enc.Base64.stringify(oauth_signature));
alert("Generated signature: "+ encryptedSignature + " with key: " + secret_signing_key);
return encryptedSignature;
}
好吧,所以我不知道确切的解决方案是什么,但现在它可以工作了。它确实有一些东西可以按字母顺序排列基字符串。
这些是我目前用于OAuth的函数:
创建基字符串:
exampleUse() {
let baseString = this.createSignatureBaseString('GET', 'someurl', 'asdfva323', '15134234234', localStore.getItem('token'));
}
createSignatureBaseString(method: string, url: string, nonce: string, timestamp: number, oauth_token?: string): string {
let baseString = method+"&" + encodeURIComponent(url) + "&";
baseString += encodeURIComponent(`oauth_consumer_key=${this.oauth_consumer_key}&`);
baseString += encodeURIComponent(`oauth_nonce=${nonce}&`);
baseString += encodeURIComponent(`oauth_signature_method=${this.oauth_signature_method}&`);
baseString += encodeURIComponent(`oauth_timestamp=${timestamp}&`);
if(oauth_token) {
baseString += encodeURIComponent(`oauth_token=${oauth_token}&`);
}
baseString += encodeURIComponent(`oauth_version=1.0`);
return baseString;
}
创建加密签名:
exampleUse() {
let baseString = ...
let mySecret = thatthissolutiontookmetwomonths;
let signature = this.generateEncryptedSignature(baseString, mySecret);
}
generateEncryptedSignature(signatureBaseString: string, tokenSecret?: string): string {
let secret_signing_key = this.oauth_consumer_secret + "&";
if(tokenSecret) {
secret_signing_key += tokenSecret;
}
let oauth_signature = CryptoJS.HmacSHA1(signatureBaseString, secret_signing_key);
let encryptedSignature = encodeURIComponent(CryptoJS.enc.Base64.stringify(oauth_signature));
return encryptedSignature;
}
使用 OAuth 参数创建 URL(以获取访问令牌等):
createOauthUrl(baseUrl: string, nonce: string, timestamp: number, signature: string, oauth_token?: string): string {
var url = `${baseUrl}?`;
url += `oauth_consumer_key=${this.oauth_consumer_key}&`;
url += `oauth_nonce=${nonce}&`;
url += `oauth_signature_method=HMAC-SHA1&`;
url += `oauth_timestamp=${timestamp}&`;
if(oauth_token) {
url += `oauth_token=${oauth_token}&`;
}
url += `oauth_version=1.0&`;
url += `oauth_signature=${signature}`;
return url;
}
创建授权标头值(每个经过身份验证的请求都是必需的):
exampleUse(){
let headerValue = this.getHeaderValue('POST', 'someserver');
let headers = new Headers();
headers.append('Authorization', headerValue);
let options = new RequestOptions(headers);
this.http.post(url, some_data, options).then(res => {...});
}
getHeaderValue(method: string, url: string): string {
let headerValue = 'OAuth ';
//these functions not included but they're pretty straightforward
let timestamp = this.getCurrentTimeStamp();
let nonce = this.generateNonce();
let token = localStorage.getItem("u:access_token");
let secret = localStorage.getItem("u:access_token:s");
let baseString;
baseString = this.createSignatureBaseString(method, url, nonce, timestamp, token);
let signature = this.generateEncryptedSignature(baseString, secret);
headerValue += `oauth_consumer_key="${this.oauth_consumer_key}"`;
headerValue += `,oauth_token="${token}"`;
headerValue += `,oauth_signature_method="HMAC-SHA1"`;
headerValue += `,oauth_timestamp="${timestamp}"`;
headerValue += `,oauth_nonce="${nonce}"`;
headerValue += `,oauth_version="1.0"`;
headerValue += `,oauth_signature="${signature}"`;
return headerValue;
}
如果有人在使用我上面共享的代码时遇到任何问题,请告诉我!我有点觉得我为此写了一个迷你库。甚至可能合二为一。