Код_верификатора не соответствует коду_задачи, указанному в запросе авторизации для PKCE.
Я пытаюсь получить токен доступа и токен обновления учетной записи Microsoft.
const loginAndGetAuthorizationCode = async () => {
const code_verifier = generateCodeVerifier();
const code_challenge = await generateCodeChallenge(code_verifier);
localStorage.setItem('code_verifier', code_verifier);
localStorage.setItem('code_challenge', code_challenge);
const loginRequest = {
tenant: "common",
scopes: ["User.Read", "Mail.Read"],
response_type: "code",
responseMode: "query",
state: code_verifier,
codeChallenge: code_challenge,
codeChallengeMethod: "S256",
};
try {
const loginResponse = await msalInstance.acquireTokenRedirect(loginRequest);
console.log("loginResponse => ", loginResponse);
} catch (error) {
console.error("Login failed: ", error);
}
};
Это конфигурация
import { PublicClientApplication } from "@azure/msal-browser";
const msalConfig = {
auth: {
clientId: "ID", // client ID
authority: "https://login.microsoftonline.com/tenantID", // tenant ID
redirectUri: "http://localhost:3000/dashboard",
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
}
};
const msalInstance = new PublicClientApplication(msalConfig);
await msalInstance.initialize();
// await msalInstance.handleRedirectPromise();
export { msalInstance };
Это функции утилиты
export function generateCodeVerifier() {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
const array = new Uint8Array(43); // Minimum length of 43
window.crypto.getRandomValues(array);
return Array.from(array, (b) => characters[b % characters.length]).join("");
}
// Generate the code challenge from the code verifier
export async function generateCodeChallenge(codeVerifier: string) {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await window.crypto.subtle.digest("SHA-256", data);
// Convert Uint8Array to an array using Array.from() before processing
const base64Digest = btoa(String.fromCharCode(...Array.from(new Uint8Array(digest))))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
return base64Digest;
}
Это бэкэнд
@staticmethod
def get_access_token(code, code_verifier):
url = f'https://login.microsoftonline.com/{MICROSOFT_TENANT_ID}/oauth2/v2.0/token'
headers = {}
print("code => ", code)
print("code_verifier => ", code_verifier)
data = {
'client_id': MICROSOFT_CLIENT_ID,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': MICROSOFT_REDIRECT_URI,
"code_verifier": code_verifier,
}
print("code => ", code)
print("MICROSOFT_CLIENT_ID => ", MICROSOFT_CLIENT_ID)
print("MICROSOFT_REDIRECT_URI => ", MICROSOFT_REDIRECT_URI)
print("MICROSOFT_CLIENT_SECRET => ", MICROSOFT_CLIENT_SECRET)
response = requests.post(url, headers=headers, data=data)
print("response => ", response.json())
if response.status_code == 200:
access_token = response.json()['access_token']
refresh_token = response.json()['refresh_token']
return access_token, refresh_token
else:
return None, None
Я получаю такой ответ об ошибке => {'error':'invalid_grant','error_description':'AADSTS501481: Code_Verifier не соответствует code_challenge, указанному в запросе авторизации. ID трассировки: 03bb855a-c418-4039-9008-7eec48e91e00 ID корреляции: 6e2d26b8-9a8b-4d06-9326-40ec7659c4a9 Timestamp: 2024-10-21 11:13:56Z', 'error_codes': [501481], 'timestamp': '2024-10-21 11:13:56Z', 'trace_id': '03bb855a-c418-4039-9008-7eec48e91e00', 'correlation_id': '6e2d26b8-9a8b-4d06-9326-40ec7659c4a9'}