我正在创建一个Ionic 3应用程序,在某些方面我想做一些 在Twitter REST API上获取请求。
为了避免CORS问题,我安装了Ionic Native HTTP,我认为使用本机代码来发出请求。
在crypto-js
的帮助下,我做了这个:
@Injectable()
export class SocialAuthProvider {
readonly tw_consumer_key = "KMrbopjEliojNyhWAhc5DqrEB";
readonly tw_consumer_secret_key = "z66rlC6kTXNq2fjrP3UJc1pVDaTlKggkZHSDtl81dnqDRPwfoB";
public token: string;
public tokenSecret: string;
public generatedNONCE = '';
public time;
public userID: string;
constructor(
private fb: Facebook,
private tw: TwitterConnect,
private ns: NativeStorage,
private HTTPnative: HTTP
) {
this.generatedNONCE = this.createNonce();
this.time = Math.floor((new Date()).getTime() / 1000);
}
twitterApiRequest():承诺{
let url = 'https://api.twitter.com/1.1/users/show.json';
let headers = this.prepareTwitterHeaders();
return new Promise((resolve, reject) => {
this.HTTPnative.get(url, {'user_id': this.userID}, headers).then((response: HTTPResponse) => {
resolve(response);
}).catch((err: Error) => {
reject(err);
})
});
}
public prepareTwitterHeaders(){
const headerJson = {
'Accept': '*/*',
'Content-Type' : 'application/x-www-form-urlencoded',
'Authorization' : this.prepareAuthorization(),
};
return headerJson;
}
public createNonce():string {
let text = "";
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
public prepareAuthorization(){
let authorization = 'OAuth ';
authorization += this.fixedEncodeUri('oauth_consumer_key') + '="' + this.fixedEncodeUri(this.tw_consumer_key) + '", ' ;
authorization += this.fixedEncodeUri('oauth_nonce') + '="' + this.fixedEncodeUri(this.generatedNONCE) + '", ' ;
authorization += this.fixedEncodeUri('oauth_signature') + '="' + this.fixedEncodeUri(this.prepareSignature()) + '", ' ;
authorization += this.fixedEncodeUri('oauth_signature_method') + '="' + this.fixedEncodeUri('HMAC-SHA1') + '", ' ;
authorization += this.fixedEncodeUri('oauth_timestamp') + '="' + this.fixedEncodeUri(this.time) + '", ' ;
authorization += this.fixedEncodeUri('oauth_token') + '="' + this.fixedEncodeUri(this.token) + '", ' ;
authorization += this.fixedEncodeUri('oauth_version') + '="' + this.fixedEncodeUri('1.0') + '"' ;
return authorization;
}
public fixedEncodeUri(str:string){
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
public prepareSignature():string {
const sigParams = {
'oauth_consumer_key' : this.tw_consumer_key,
'oauth_nonce' : this.generatedNONCE,
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp' : this.time,
'oauth_token' : this.token,
'oauth_version' : '1.0',
'user_id' : this.userID
};
/** Create the string from parameters */
let paramStr = '';
let total = Object.keys(sigParams).length - 1;
Object.keys(sigParams).forEach((key, i) => {
let name = this.fixedEncodeUri(key);
let value = this.fixedEncodeUri(sigParams[key]);
paramStr += name;
paramStr += '=';
paramStr += value;
if ( i < total ) { paramStr += '&' }
});
console.log(paramStr);
/** Create the base signature base string */
let baseSignatureStr = '';
const method = 'GET';
const encodedTwitterUrl = this.fixedEncodeUri('https://api.twitter.com/1.1/users/show.json');
baseSignatureStr += method + '&' + encodedTwitterUrl + '&' + this.fixedEncodeUri(paramStr);
/** Create the Signing Key (Consumer Secret & Token Secret) */
let signingKey = this.fixedEncodeUri(this.tw_consumer_secret_key) + '&' + this.fixedEncodeUri(this.tokenSecret);
let hashedParams = CryptoJS.HmacSHA1(baseSignatureStr, signingKey).toString();
let utf8parsed = CryptoJS.enc.Utf8.parse(hashedParams);
let final = CryptoJS.enc.Base64.stringify(utf8parsed);
return final;
} }
但我一直在接受status: 401, code: 32, Could not authenticate you.
我感觉非常接近,但我开始变得疯狂。
非常感谢任何帮助。
PS。所有凭据token, tokenSecret, consumer key, consumer secret key
都是正确的。