Bei meiner Postanforderung erhalte ich einen Status 401 -Fehler aus dem Endpunkt/oAuth/request_token . Ich bin beim ersten Schritt in einem 3 -Stufe -Prozess zum Authentifizieren mit https://api.x.com, um eine "Taste" mit x "zu aktivieren.
import crypto from 'crypto';
import axios from 'axios';
import { NextResponse } from 'next/server';
const X_CLIENT_ID = process.env.X_CLIENT_ID as string;
const X_CLIENT_SECRET = process.env.X_CLIENT_SECRET as string;
const X_CALLBACK_URL = process.env.X_CALLBACK_URL as string;
if (!X_CLIENT_ID || !X_CLIENT_SECRET || !X_CALLBACK_URL) {
throw 'Missing env vars';
}
const BASE_URL = 'https://api.x.com/oauth/request_token';
export async function GET() {
try {
const params = createSignedRequestParams();
const authorizationHeader = `Oauth oauth_callback="${params.oauth_callback}",oauth_consumer_key="${params.oauth_consumer_key}",oauth_nonce="${params.oauth_nonce}",oauth_signature="${params.oauth_signature}",oauth_signature_method="${params.oauth_signature_method}",oauth_timestamp="${params.oauth_timestamp}",oauth_version="${params.oauth_version}"`
const response = await axios.post(BASE_URL, null, {
headers: {
'User-Agent': 'Cutcosts',
'Host': 'api.x.com',
'Accept': '*/*',
'Authorization': authorizationHeader
}
});
console.log(response);
return NextResponse.json({ success: true })
} catch (error: any) {
console.log(JSON.stringify(error, null, 2));
return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
}
}
function enc(str: string) {
return encodeURIComponent(str);
}
function createSignedRequestParams() {
// RFC 5849 Section 3.4.1
// Encoding method is only necessary for custom methods
const method = 'POST';
// Params
const params: Record = {
'oauth_callback': X_CALLBACK_URL,
'oauth_consumer_key': X_CLIENT_ID, // "API Key" in X Developer Portal, per https://docs.x.com/resources/fundamenta ... he-process
'oauth_nonce': Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': String(Math.floor(Date.now() / 1000)),
'oauth_version': '1.0'
};
// Encode params
const encodedParams: Record = {};
Object.keys(params).forEach((key) => {
encodedParams[key] = enc(params[key]);
});
// Normalize encoded params
const normalizedParams = Object.keys(encodedParams).sort().map(key => `${key}=${encodedParams[key]}`).join('&');
// The example in RFC 5849 Section 3.4.1.1 shows one ampersand after POST, and one after base URL
// the rest of the ampersands and equal signs in params are encoded
// Encode normalize params
const encodedNormalizedParams = normalizedParams; // enc(normalizedParams);
// Encode base url
const encodedBaseUrl = enc(BASE_URL);
// Construct base string
// https://docs.x.com/resources/fundamenta ... ase-string
const baseString = method + '&' + encodedBaseUrl + '&' + enc(encodedNormalizedParams);
console.log('Example:', 'POST&https%3A%2F%2Fapi.x.com%2F1.1%2Fstatuses%2Fupdate.json&include\_entities%3Dtrue%26oauth\_consumer\_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth\_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth\_signature\_method%3DHMAC-SHA1%26oauth\_timestamp%3D1318622958%26oauth\_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521');
console.log('Actual:', baseString);
// Construct encoded signature
// X_CLIENT_SECRET is "API Secret" in X Developer Portal, per https://docs.x.com/resources/fundamenta ... he-process
const signingKey = enc(X_CLIENT_SECRET) + '&';
const signature = crypto.createHmac('sha1', signingKey)
.update(baseString)
.digest('base64');
const encodedSignature = enc(signature);
// Update params to include encoded signature
encodedParams.oauth_signature = encodedSignature;
return encodedParams;
}
< /code>
Fehlerbehebung Versuche: < /p>
Versucht, die gesamte Zeichenfolge nach "oAuth" im Autorisierungsheader zu codieren. (Status 400) < /p>
Versucht, die Signatur nicht zu codieren, nachdem sie in Base64 (Status 400) < /p>
versucht wurde, den Parameter oAuth_callback zu setzen, anstatt den oauuth_callback -Parameter anstatt in den Postkörper zu bringen, anstatt den Parameter oAuth_callback zu setzen, anstatt den Parameter oAuth_callback zu setzen und nicht in Postkörper anstatt in den Autorisierungsheader (Status 401) < /p>
Versucht, die normalisierten Parameter während der Signaturerstellung nicht zu codieren Callback URI in der Postanforderung < /p>
verifiziert, dass oAuth_consumer_key -Wert den Client -ID -Wert des X -Entwicklerportals übergeht. Geheimnis aus dem X -Entwickler -Portal < /p>
Versucht mit "API -Schlüssel" und "API Secret" für oAuth_consumer_key und Signing Secret anstelle von Client -ID und Client -Geheimnis (gelernt aus DOCs [DOT] x [DOT] com/ressourcen/fundamentals/authentication/oauth-1-0a/actous-access-tokens#Übersicht des Verfahrens erhalten, dass dies tatsächlich für den OAuth 1.0A-Fluss korrekt ist, aber ich erhalte immer noch einen Status 401)
Was kann ich sonst noch Fehler beheben? (CreateHmac, Update, Digest)
Wie unterschreibe ich eine HTTP -Anfrage für https: //api.x.com's OAuth 1.0a Flow? ⇐ JavaScript
-
- Similar Topics
- Replies
- Views
- Last post
-
-
PHP - Anfrage für https://apis.roblox.com/challenge/v1/continue, Login Roblox
by Anonymous » » in Php - 0 Replies
- 0 Views
-
Last post by Anonymous
-