K
Kinde6mo ago
ATOM

React Kinde with FastAPI python

I have react application and I'm using there react sdk for kinde with provider. Now i have access token from react app My goal is to grab this access token from react app pass it into Headers and make an API call to my FastAPI python backend. How i can validate this access token on my backend ?
7 Replies
Roshan
Roshan6mo ago
Hi there, Thanks for your question. Here's how you can handle access token validation between your React frontend and FastAPI backend using Kinde: --- Frontend – React: Use the Kinde React SDK to retrieve the access token and include it in the Authorization header when making API requests to your backend:
const { getAccessToken } = useKindeAuth();
const fetchData = async () => {
try {
const accessToken = await getAccessToken();
const res = await fetch('<your-api-endpoint>', {
headers: {
Authorization: Bearer ${accessToken},
},
});
const { data } = await res.json();
console.log({ data });
} catch (err) {
console.error(err);
}
};
const { getAccessToken } = useKindeAuth();
const fetchData = async () => {
try {
const accessToken = await getAccessToken();
const res = await fetch('<your-api-endpoint>', {
headers: {
Authorization: Bearer ${accessToken},
},
});
const { data } = await res.json();
console.log({ data });
} catch (err) {
console.error(err);
}
};
--- Backend – FastAPI (Python): To validate the token on your FastAPI server, follow these steps: 1. Install the Kinde SDK:
pip install kinde-python-sdk
pip install kinde-python-sdk
2. Configure the Kinde client:
from kinde_sdk import Configuration
from kinde_sdk.kinde_api_client import GrantType, KindeApiClientconfiguration = Configuration(host=KINDE_HOST)
kinde_api_client_params = {
"configuration": configuration,
"domain": KINDE_HOST,
"client_id": KINDE_CLIENT_ID,
"client_secret": KINDE_CLIENT_SECRET,
"grant_type": GRANT_TYPE,
"callback_url": KINDE_REDIRECT_URL,
}
kinde_client = KindeApiClient(**kinde_api_client_params)
from kinde_sdk import Configuration
from kinde_sdk.kinde_api_client import GrantType, KindeApiClientconfiguration = Configuration(host=KINDE_HOST)
kinde_api_client_params = {
"configuration": configuration,
"domain": KINDE_HOST,
"client_id": KINDE_CLIENT_ID,
"client_secret": KINDE_CLIENT_SECRET,
"grant_type": GRANT_TYPE,
"callback_url": KINDE_REDIRECT_URL,
}
kinde_client = KindeApiClient(**kinde_api_client_params)
3. Validate the access token:
if kinde_client.is_authenticated_token(access_token):
# Token is valid – proceed with your logic
if kinde_client.is_authenticated_token(access_token):
# Token is valid – proceed with your logic
--- Additional Notes: - Make sure your API is registered in the Kinde dashboard. - Define an audience for your API – this ensures the token includes the correct aud claim. - When using the React SDK, the audience is typically set automatically. - Keep in mind: the kinde_client instance stores the access token internally, so you’ll need to create one per user session. Let me know if you'd like help setting up the audience or if you run into any issues during integration.
ATOM
ATOMOP6mo ago
in which format it's accept access token in kinde_client.is_authenticated_token?
Roshan
Roshan6mo ago
Hi, The is_authenticated_token method expects the access token in raw JWT string format. If you're using the React SDK, you'll receive the correct format automatically when calling getAccessToken(). You can refer to the documentation here:
🔗 https://docs.kinde.com/developer-tools/sdks/frontend/react-sdk/#test-sign-up Here’s an example of what the token might look like:
eyJhbGciOiJIUzI1...
eyJhbGciOiJIUzI1...
This is the raw JWT string you should send from the React frontend to your Python backend. On the backend, you can extract the token from the Authorization header and pass it directly to is_authenticated_token():
# Example in Python
access_token = request.headers.get('Authorization').replace('Bearer ', '')
if kinde_client.is_authenticated_token(access_token):
# Continue processing
# Example in Python
access_token = request.headers.get('Authorization').replace('Bearer ', '')
if kinde_client.is_authenticated_token(access_token):
# Continue processing
The token includes standard JWT claims like aud, exp, and iss, which Kinde validates internally when you call this method. Let me know if you need help implementing this or debugging a specific case!
Straegge
Straegge4mo ago
Hijacking this support thread because the given solution doesn't work. is_authenticated_token() expects a dict and calls is_expired() on the given token - so passing in request.headers.get('Authorization').replace('Bearer ', '') as suggested, which is obviously a string because as stated it is just the "raw JWT string", throws an error. Calling "get_claim_token" actually does validate the token internally and return the requested claim, however since it is internal, the validation cannot be modified, like validating additional claims etc. It's do weird to me that the library doesn't state at ALL what "token_value" is actually supposed to be. It is clearly not just a "dict", since "is_expired()" would throw an error on that as well. Is there actual real support here that can answer this question? If the solution is just "the Python SDK doesn't support built-in JWT validation yet, use a third-party library to validate and call the Kinde API to get further information like user roles etc.", then STATE THAT PLEASE instead of giving half-baked solutions.
Straegge
Straegge4mo ago
No description
Straegge
Straegge4mo ago
The is_authenticated_token method expects the access token in raw JWT string format.
How is it possible that the "support" here blatantly misstates your own API?
Abdelrahman Zaki - Kinde
Hi @Straegge, Thank you for jumping in and raising these concerns — you’re absolutely right to call out the confusion, and I appreciate your detailed explanation. You're correct: the is_authenticated_token() method does not accept a raw JWT string as input, and my earlier response was incorrect on that point. I appreciate your patience and want to offer a more accurate approach. The correct way to validate a JWT access token issued by Kinde using the Python SDK is to manually validate the token using the SDK’s JWKS support and a JWT decoding library, like this:
from kinde_sdk import Configuration
from kinde_sdk.kinde_api_client import GrantType, KindeApiClient
import jwt

# Set up the Kinde client
configuration = Configuration(host="https://<your_kinde_subdomain>.kinde.com")
kinde_api_client_params = {
"configuration": configuration,
"domain": "https://<your_kinde_subdomain>.kinde.com",
"client_id": "<your_kinde_client_id>",
"client_secret": "<your_kinde_client_secret>",
"grant_type": GrantType.CLIENT_CREDENTIALS,
"callback_url": "http://localhost:8000/callback"
}
kinde_client = KindeApiClient(**kinde_api_client_params)

# Token validation function
def validate_token(token):
try:
signing_key = kinde_client.jwks_client.get_signing_key_from_jwt(token)
decoded_token = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
options={
"verify_signature": True,
"verify_exp": True,
"verify_aud": False # You can enable this and pass expected audience if required
}
)
return decoded_token
except Exception as e:
print("Token validation failed:", str(e))
return None
from kinde_sdk import Configuration
from kinde_sdk.kinde_api_client import GrantType, KindeApiClient
import jwt

# Set up the Kinde client
configuration = Configuration(host="https://<your_kinde_subdomain>.kinde.com")
kinde_api_client_params = {
"configuration": configuration,
"domain": "https://<your_kinde_subdomain>.kinde.com",
"client_id": "<your_kinde_client_id>",
"client_secret": "<your_kinde_client_secret>",
"grant_type": GrantType.CLIENT_CREDENTIALS,
"callback_url": "http://localhost:8000/callback"
}
kinde_client = KindeApiClient(**kinde_api_client_params)

# Token validation function
def validate_token(token):
try:
signing_key = kinde_client.jwks_client.get_signing_key_from_jwt(token)
decoded_token = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
options={
"verify_signature": True,
"verify_exp": True,
"verify_aud": False # You can enable this and pass expected audience if required
}
)
return decoded_token
except Exception as e:
print("Token validation failed:", str(e))
return None
For additional security and flexibility, you can also validate the token using a standalone JWT library without depending on the SDK. In that case, you can fetch the JWKS directly from: https://<your_kinde_subdomain>.kinde.com/.well-known/jwks Make sure your API is registered in the Kinde dashboard, and that your React frontend includes the audience parameter when initializing the Kinde provider: <KindeProvider audience="<your_api>"> Let me know if you'd like help implementing this or if you run into any issues.

Did you find this page helpful?