iamexample/src/iamexample/iamexample.py

90 lines
2.8 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]
print('Call: ' + self.call)
def main(self):
if self.call== "AccessToken":
self.getAccessToken()
elif self.call=="UmaToken":
self.getUmaToken()
else:
print("Error unsupported operation")
def getAccessToken(self):
print("getAccessToken()")
self.clientId = sys.argv[2]
self.secret = sys.argv[3]
print('ClientId: ' + self.clientId)
print('Secret: ' + self.secret)
loginheaders = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded'}
logindata = { 'grant_type' : 'client_credentials', 'client_id' : self.clientId, 'client_secret' : self.secret}
# login with offline_token
resp1 = requests.post(self.iamURL, data=logindata, headers=loginheaders)
jwt1 = resp1.json()
print("Resp1: ",jwt1)
return jwt1["access_token"]
def getUmaToken(self):
print("getUmaToken()")
self.clientId = sys.argv[2]
self.secret = sys.argv[3]
self.context = sys.argv[4]
print('ClientId: ' + self.clientId)
print('Secret: ' + self.secret)
print('Context: '+ self.context)
self.context=urllib.parse.quote(self.context, safe='')
print('Context safe: '+ self.context)
loginheaders = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded'}
logindata = { 'grant_type' : 'client_credentials', 'client_id' : self.clientId, 'client_secret' : self.secret}
# login with offline_token
resp1 = requests.post(self.iamURL, data=logindata, headers=loginheaders)
jwt1 = resp1.json()
print("Resp1: ",jwt1)
umadata = { 'grant_type' : 'urn:ietf:params:oauth:grant-type:uma-ticket', 'audience' : self.context}
umaheaders = { "Accept" : "application/json", "Content-Type" : "application/x-www-form-urlencoded"}
#get UMA token for context
umaheaders["Authorization"] = "Bearer " + jwt1["access_token"]
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()