Skip to main content

Python Django

Defined Constants:

OIDC_AUTH_END_POINT = "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/auth"
OIDC_CLIENT = "openidtestclient"
OIDC_CLIENT_SECRECT = "1c3ca8d5-41b0-4011-8834-13f61cf5711e"
OIDC_TOKEN_URI = "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/token"
OIDC_TENANT = "tenantname" #isteğe bağlı olarak front tarafına gönderilebilir

/auth/oidc (GET)

class OidcInfoAPIView(APIView):
def get(self, request, *args, **kwargs):
redirect_uri = request.query_params.get("redirect_uri")
nonce = gen_nonce(8)
url = f"{OIDC_AUTH_END_POINT}\
?client_id={OIDC_CLIENT}\
&redirect_uri={redirect_uri}\
&scope=openid\
&response_type=code\
&response_mode=query\
&nonce={nonce}"

data = {
"client_id": OIDC_CLIENT,
"auth_url": OIDC_AUTH_END_POINT,
"composed_url": url,
"realm": OIDC_TENANT
}
return Response(data, status=HTTP_200_OK)

#get_once yardımcı fonksiyonu
def gen_nonce(length):
""" Generates a random string of bytes, base64 encoded """
if length < 1:
return ''
string = base64.b64encode(os.urandom(length), altchars=b'-_')

return string[:8].decode()

/auth/code (POST)

import jwt
class CodeApiView(APIView):
def post(self, request, *args, **kwargs):
code = request.data.get("code")
redirect_uri = request.data.get("redirect_uri")
data = {
"code": code,
"client_id": OIDC_CLIENT,
"grant_type": "authorization_code",
"client_secret": OIDC_CLIENT_SECRECT,
"redirect_uri": redirect_uri
}
res = requests.post(OIDC_TOKEN_URI, data=data)
id_token = res.json().get("id_token")

if not id_token:
return Response(status=HTTP_400_BAD_REQUEST)
id_data = jwt.decode(id_token, verify=False)
email = id_data.get("email")
#user bizim uygulamamızın database yapısında var mı (e-mail ile kontrol)
user = UserTemplate.objects.filter(email=email).first()
# user yoksa id_tokendan gelen email ile user create et
if not user:
user = UserTemplate.objects.create_user(username=email,
email=email,
password=None, )
user.save()

serializer = UserDetailSerializer(user)
#jwt_payload_handler ve jwt_encode_handler djangoya ait yaedımcı fonksiyonlar , bize user bilgilerinden jwt token yaratmamıza yardımcı oluyor
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
data = {}
data["token"] = token
data["user"] = serializer.data
return Response(data, status=HTTP_200_OK)