iamexample/src/iamexample/iamexample.py

80 lines
2.4 KiB
Python
Raw Normal View History

2023-02-01 16:56:42 +01:00
#!/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]
2023-02-01 17:42:40 +01:00
self.clientId = sys.argv[2]
2023-02-01 17:47:25 +01:00
self.clientSecret = sys.argv[3]
2023-02-01 16:56:42 +01:00
print('Call: ' + self.call)
2023-02-01 17:42:40 +01:00
print('ClientId: ' + self.clientId)
2023-02-01 17:47:25 +01:00
print('ClientSecret: ' + self.clientSecret)
2023-02-01 17:42:40 +01:00
2023-02-01 16:56:42 +01:00
def main(self):
if self.call== "AccessToken":
2023-02-02 11:21:11 +01:00
print("Access Token: "+self.getAccessToken())
2023-02-01 16:56:42 +01:00
elif self.call=="UmaToken":
2023-02-02 11:21:11 +01:00
print("Uma Token: "+self.getUmaToken())
2023-02-01 16:56:42 +01:00
else:
print("Error unsupported operation")
def getAccessToken(self):
print("getAccessToken()")
2023-02-01 17:56:12 +01:00
2023-02-01 16:56:42 +01:00
loginheaders = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded'}
2023-02-01 17:47:25 +01:00
logindata = { 'grant_type' : 'client_credentials', 'client_id' : self.clientId, 'client_secret' : self.clientSecret }
2023-02-01 16:56:42 +01:00
2023-02-01 17:42:40 +01:00
# Get Access Token by client_id
2023-02-01 16:56:42 +01:00
resp1 = requests.post(self.iamURL, data=logindata, headers=loginheaders)
jwt1 = resp1.json()
print("Resp1: ",jwt1)
2023-02-01 17:42:40 +01:00
accessToken=jwt1["access_token"]
return accessToken
2023-02-01 16:56:42 +01:00
def getUmaToken(self):
2023-02-01 17:42:40 +01:00
print("getUmaToken()")
context = sys.argv[4]
print('Context: '+ context)
2023-02-01 16:56:42 +01:00
2023-02-01 17:42:40 +01:00
context=urllib.parse.quote(context, safe='')
print('Context safe: '+ context)
2023-02-01 16:56:42 +01:00
2023-02-01 17:42:40 +01:00
accessToken=self.getAccessToken()
2023-02-01 16:56:42 +01:00
2023-02-01 18:11:00 +01:00
umaheaders = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded'}
2023-02-01 17:42:40 +01:00
umadata = { 'grant_type' : 'urn:ietf:params:oauth:grant-type:uma-ticket', 'audience' : context}
2023-02-01 17:30:44 +01:00
2023-02-01 17:42:40 +01:00
# Get UMA token for context
umaheaders["Authorization"] = "Bearer " + accessToken
2023-02-01 16:56:42 +01:00
resp2 = requests.post(self.iamURL, data=umadata, headers=umaheaders)
jwt2 = resp2.json()
print("Resp2: ",jwt2)
umaToken=jwt2["access_token"]
return umaToken
2023-02-01 17:47:25 +01:00
2023-02-01 16:56:42 +01:00
def __str__(self):
return 'IAMExample'
def main():
print('IAMExample')
iamExample = IAMExample()
iamExample.main()
main()