import axios from 'axios';
import React, { useEffect, useState} from 'react';
import pkceChallenge from 'pkce-challenge';
import { useCookies } from 'react-cookie';
function Login({ onLogin }) {
const [cookies, setCookie] = useCookies('accessToken');
const [codeVerifier, setCodeVerifier] = useState({});
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
retrieveToken(code);
window.history.replaceState({}, document.title, window.location.pathname);
}
}, [codeVerifier]);
const handleLogin = () => {
const challenge = pkceChallenge();
setCodeVerifier(challenge.code_verifier);
window.location.href = 'http://localhost:8080/oauth2/authorize?' +
'response_type=code&' +
'client_id=client&' +
'scope=openid&' +
'redirect_uri=http://127.0.0.1:3000/login&' +
'code_challenge=' +
challenge.code_challenge +
'&' +
'code_challenge_method=S256';
};
const retrieveToken = (code) => {
try {
const response = axios.post(
'http://localhost:8080/oauth2/token?' +
'client_id=client&' +
'redirect_uri=http://127.0.0.1:3000/login&' +
'grant_type=authorization_code&' +
'code=' + code + '&' +
'code_verifier=' + codeVerifier
);
setCodeVerifier('');
const accessToken = response.data.access_token;
const options = {
path: '/',
expires: new Date(new Date().getTime() + response.data.expires_in * 1000),
};
setCookie('accessToken', accessToken, options);
onLogin()
} catch (err) {
alert('Invalid Credentials');
}
};
return (
<div>
<h2>Login</h2>
<button onClick={handleLogin}>Login</button>
</div>
);
}
export default Login;
Current workflow: When user press login, authorization code will be delivered and right after i want to send a request to the /login with this authorize code and the code verifier that i have just set when the user pressed login, but the codeVerifier is always null. What is the problem?