iamexample/src/iamexample/iamexample.py

80 lines
2.4 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @author: Giancarlo Panichi
#
# Created on 2023/02/01
#
import sys
import requests
import urllib.parse
class IAMExample:
def __init__(self):
self.iamURL = 'https://accounts.dev.d4science.org/auth/realms/d4science/protocol/openid-connect/token'
self.call = sys.argv[1]
self.clientId = sys.argv[2]
self.clientSecret = sys.argv[3]
print('Call: ' + self.call)
print('ClientId: ' + self.clientId)
print('ClientSecret: ' + self.clientSecret)
def main(self):
if self.call== "AccessToken":
print("Access Token: "+self.getAccessToken())
elif self.call=="UmaToken":
print("Uma Token: "+self.getUmaToken())
else:
print("Error unsupported operation")
def getAccessToken(self):
print("getAccessToken()")
loginheaders = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded'}
logindata = { 'grant_type' : 'client_credentials', 'client_id' : self.clientId, 'client_secret' : self.clientSecret }
# Get Access Token by client_id
resp1 = requests.post(self.iamURL, data=logindata, headers=loginheaders)
jwt1 = resp1.json()
print("Resp1: ",jwt1)
accessToken=jwt1["access_token"]
return accessToken
def getUmaToken(self):
print("getUmaToken()")
context = sys.argv[4]
print('Context: '+ context)
context=urllib.parse.quote(context, safe='')
print('Context safe: '+ context)
accessToken=self.getAccessToken()
umaheaders = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded'}
umadata = { 'grant_type' : 'urn:ietf:params:oauth:grant-type:uma-ticket', 'audience' : context}
# Get UMA token for context
umaheaders["Authorization"] = "Bearer " + accessToken
resp2 = requests.post(self.iamURL, data=umadata, headers=umaheaders)
jwt2 = resp2.json()
print("Resp2: ",jwt2)
umaToken=jwt2["access_token"]
return umaToken
def __str__(self):
return 'IAMExample'
def main():
print('IAMExample')
iamExample = IAMExample()
iamExample.main()
main()