K
Kinde8mo ago
iamaman

How to validate an access token in Python?

Hi there, I'm using Fast API as my backend. I read the blog post but the post assumes that I'm handling the auth from my backend. However, my frontend (NextJS) manages the auth flow. I'm looking for a way such that the FE sends me the access-token only and then I validate it on the backend before allowing any requests. Can someone please point me to the right resources to understand how to achieve this? Thank you
11 Replies
palooka8300
palooka83008mo ago
I don't use Python and not much next.js, but after the user logs in, you get the access token in your front-end app (getAccessToken is in useKindeAuth), then add that to the authorization header in calls to your API. On the Python side, you validate the JWT token.
palooka8300
palooka83008mo ago
Kinde Docs
Verifying JSON Web Tokens - Developer tools - Help center
Our developer tools provide everything you need to get started with Kinde.
onderay
onderay8mo ago
@palooka8300 thanks for helping to answer. @iamaman does that help you with your use case?
iamaman
iamamanOP8mo ago
Thanks all - it does but not really. I feel that there's no good documentation on how to validate the token using the SDK.
palooka8300
palooka83008mo ago
You don’t validate the token using the sdk is at is a standard technology. So use any python library for authenticating jwt tokens. More info on the kinde token and config here. https://kinde.com/docs/developer-tools/using-kinde-without-an-sdk/#verifying-the-kinde-access-token
Kinde Docs
Using Kinde without an SDK - Developer tools - Help center
Our developer tools provide everything you need to get started with Kinde.
palooka8300
palooka83008mo ago
I agree a working example from kinde would go a long way to explain things!
iamaman
iamamanOP8mo ago
Yeah I mean, agree! However it could easily be a function on the SDK? I guess it's all about the dev experience at the end of the day 🙂
palooka8300
palooka83008mo ago
I agree, although I guess they’re a startup and don’t have the resources of an auth0 etc. I think I saw something mentioned about community toolkits, and more fleshed out samples, so I suspect it will happen in time. Until then, the team is very active on here and I’m sure they’ll help if you get stuck
Mgregchi
Mgregchi8mo ago
Hello, I have been stuck with this for about a week now. I slept on the documentation also Kinde API but nothing seem to work. Still trying to identify user via the acccess token before performing any task on the backend (Python). Currently, i have this:
import requests

TOKEN = "eyJhbGci***"
ORG_NAME = "example"

def introspect_token(token, token_type, *args, **kwargs):
introspection_url = f'https://{ORG_NAME}.kinde.com/oauth2/introspect'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': f'Bearer {TOKEN}'
}
data = {
'token': token,
'token_type': token_type
}
response = requests.post(introspection_url, data=data, headers=headers)
return response.json()

def token_introspect_view(token, token_type="Bearer"):
introspection_response = introspect_token(token, token_type)
print(introspection_response)


token_introspect_view(token="kp_kdjejr***")
import requests

TOKEN = "eyJhbGci***"
ORG_NAME = "example"

def introspect_token(token, token_type, *args, **kwargs):
introspection_url = f'https://{ORG_NAME}.kinde.com/oauth2/introspect'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': f'Bearer {TOKEN}'
}
data = {
'token': token,
'token_type': token_type
}
response = requests.post(introspection_url, data=data, headers=headers)
return response.json()

def token_introspect_view(token, token_type="Bearer"):
introspection_response = introspect_token(token, token_type)
print(introspection_response)


token_introspect_view(token="kp_kdjejr***")
The doc isn't clear about this tho but anyway, i recieve
{'error': 'token_inactive', 'error_description': 'Token is inactive because it is malformed, expired or otherwise invalid. An introspection strategy indicated that the token is inactive.'}
{'error': 'token_inactive', 'error_description': 'Token is inactive because it is malformed, expired or otherwise invalid. An introspection strategy indicated that the token is inactive.'}
Even if i refresh and get new access token. I don't know what's up with it...maybe doing it wrong. I have Also tried following another approach i saw on the doc under "Verifying JSON Web Tokens" but not working for me. Any update?
Tudor
Tudor7mo ago
same problem here but with nestjs i don t get it how i can t verify the token in external backend i m trying to validate it but i get this error: secretOrPublicKey must be an asymmetric key when using RS256 // src/auth/jwt-auth.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class JwtAuthGuard implements CanActivate {
private readonly secret =
'my_client_secret';
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers.authorization;

if (!authHeader) {
throw new UnauthorizedException('Authorization header is missing.');
}

const token = authHeader.split(' ')[1];

try {
console.log('token', token);
const decoded = jwt.verify(token, this.secret, {
algorithms: ['RS256'],
});
console.log('Decoded JWT:', decoded);
request.user = decoded;
return true;
} catch (error) {
console.error('Error:', error);
throw new UnauthorizedException('Invalid token.');
}
}
}
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class JwtAuthGuard implements CanActivate {
private readonly secret =
'my_client_secret';
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers.authorization;

if (!authHeader) {
throw new UnauthorizedException('Authorization header is missing.');
}

const token = authHeader.split(' ')[1];

try {
console.log('token', token);
const decoded = jwt.verify(token, this.secret, {
algorithms: ['RS256'],
});
console.log('Decoded JWT:', decoded);
request.user = decoded;
return true;
} catch (error) {
console.error('Error:', error);
throw new UnauthorizedException('Invalid token.');
}
}
}
Mgregchi
Mgregchi7mo ago
What I don't really understand is why is there a getToken() but not verifyToken() I think I will just mail support and if no solution tomorrow, then I will opt out using kinde especially for now. My project would've been deployed by now if I sticked with firebase. I finally made it to work... As stated on the doc, you have to grab the well-known keys from https://yourbiz.kinde.com/.well-known/jwks then use it to validate the access token. For Python I used the recommended jwkest Example code
function verifyJwt(token) {
const jose = require('jose');
const jwksUrl = 'https://<your_subdomain>.(link unavailable)';
try {
const keys = await jose.fetchJwks(jwksUrl);
const verified = await jose.verifyJwt(token, keys);
return verified;
} catch (err) {
return false;
}
}
function verifyJwt(token) {
const jose = require('jose');
const jwksUrl = 'https://<your_subdomain>.(link unavailable)';
try {
const keys = await jose.fetchJwks(jwksUrl);
const verified = await jose.verifyJwt(token, keys);
return verified;
} catch (err) {
return false;
}
}
This function fetches the JWKS from the provided URL, and then uses the fetched keys to verify the JWT. If the verification is successful, it returns the verified payload; otherwise, it returns false. Make sure to replace <your_subdomain> with your actual Kinde subdomain. Note: The fetchJwks function is used to fetch the JWKS from the endpoint, and the verifyJwt function is used to verify the JWT using the fetched keys. Used Jose because it's listed among the recommended
Want results from more Discord servers?
Add your server