Вот что у меня есть:
Код интерфейса :
Код: Выделить всё
const authenticate = async () => {
const token = Cookies.get('authToken');
console.log('Retrieved Token:', token);
if (token) {
try {
const decodedToken = jwtDecode(token);
console.log('Decoded Token:', decodedToken);
// Check token validity
if (decodedToken && decodedToken.exp) {
const currentTime = Math.floor(Date.now() / 1000);
if (decodedToken.exp < currentTime) {
console.error('The token is expired');
logout();
return false;
}
}
const response = await fetch('https://mysite/api/token', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
credentials: 'include',
});
if (response.ok) {
setIsAuthenticated(true);
return true;
} else {
console.error('Error validating token on server');
logout();
return false;
}
} catch (error) {
console.error('Error during authentication:', error);
logout();
return false;
}
} else {
console.error('Token is not present');
return false;
}
};
Код: Выделить всё
namespace App\Controller;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\AuthorizationHeaderTokenExtractor;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TokenController extends AbstractController
{
private $jwtManager;
public function __construct(JWTTokenManagerInterface $jwtManager)
{
$this->jwtManager = $jwtManager;
}
/**
* @Route("/api/token", name="api_token", methods={"POST"})
*/
public function handle(Request $request)
{
$tokenExtractor = new AuthorizationHeaderTokenExtractor('Bearer', 'Authorization');
$token = $tokenExtractor->extract($request);
if (!$token) {
throw new AccessDeniedException('Token not found');
}
try {
$jwtTokenData = $this->jwtManager->parse($token);
} catch (\Exception $e) {
error_log('Token parsing error: ' . $e->getMessage());
throw new AccessDeniedException('Invalid token');
}
$userEmail = $jwtTokenData['email'] ?? null;
if (!$userEmail) {
throw new AccessDeniedException('User not found in token');
}
return $this->json(['message' => 'Token validated']);
}
- Когда я вызываю конечную точку /api/token с действительным токеном, я получаю ошибку 401. Несанкционированный ответ.
- Токен выглядит правильно сформированным и действительным при декодировании.
- Процесс генерации токена возвращает действительный токен.
- Токен правильно включается в заголовок авторизации. .
- Процессы подписания и проверки используют один и тот же секретный ключ.
- Что может быть причиной ответа 401 «Неавторизованный», несмотря на то, что токен выглядит действительным?
- Необходимы ли какие-либо дополнительные проверки, которые мне следует выполнить для устранения этой проблемы? ?
Подробнее здесь: https://stackoverflow.com/questions/790 ... ymfony-api