Creating Keycloak user from docker container - python

I am having problems creating users using the Keycloak REST API from my docker container running a Django application. The following works using postman:
Fetch admin token
Create user:
The following does NOT work in python, and returns 401 Unauthorized:
Fetch admin toke (This successfully returns a token):
Create user (This returns 401):
I am using the exact same user credentials in both scenarios,and since I am able to get this to work in postman I don't think there's any problem with access/roles etc.
Any help is greatly appreciated. Thanks!

You are not givingspace after "Bearer" so instead of "Bearer"+ token , use "Bearer " + token
you can also geenrate python code from postman :
click code:
Search for python
copy paste the generated code

Related

401 error when using API from CPanel for first time

I have used API data from websites like Microsoft, Knowbe4, ninja, ITglue, twitch, etc. However I am having trouble understanding the authentication for Cpanel.
I have an API key that I obtained from the cpanel website.
Cpanel authorization: https://api.docs.cpanel.net/cpanel/tokens/
It says:
Using an API token
To call a UAPI function with an API token, run the following command from the command line:
curl -H'Authorization: cpanel username:APITOKEN' 'https://example.com:2083/execute/Module/function?parameter=value'
So I tried using python but I am getting a 401 error which relates to the password or api key.
Here is my code:
import requests
bluehostapi = "ANAPIKEY"
bluehosturl = "https://cpanel-box5504.bluehost.com:2083/cpsess4830273370/"
header = {"Authorization": "cpanel", "username":bluehostapi}
buuserrequest = requests.get(bluehosturl+"execute/email",headers=header)
print(buuserrequest)
But I always get back:
<Response [401]>
I also tried putting https://cpanel-box5504.bluehost.com:2083/cpsess4830273370/execute/mail into google chrome's address bar directly as the docs said that you can go to the api url directly. However when I did I received an error saying:
{"warnings":null,"status":0,"data":null,"messages":null,"errors":["Failed to load module “”: “Cpanel::API::” is not a valid name for a Perl module."],"metadata":{}}
My main goal is to test connecting to cpanel's api so I can retrieve all the usernames and emails of my clients programmably.

Integrate DocuSign's EnvelopeViews:createSender REST api in python flask

def sender_edit_view(self, authenticationMethod=None, envelopeId='',
returnUrl=''):
if not self.account_url:
self.login_information()
url = '/accounts/{accountId}/envelopes/{envelopeId}/views/edit' \
.format(accountId=self.account_id,
envelopeId=envelopeId)
if authenticationMethod is None:
authenticationMethod = 'none'
data = {
'authenticationMethod': authenticationMethod,
'returnUrl': returnUrl,
}
return self.post(url, data=data, expected_status_code=201)
pydocusign.exceptions.DocuSignException: DocuSign request failed: GET https://demo.docusign.net/restapi/v2/accounts/9286679/envelopes/http://127.0.0.1:5000/views/edit returned code 404 while expecting code 201; Message: ;
i want to redirect to sender view with the UI.
https://github.com/peopledoc/pydocusign/tree/master/pydocusign
trying to use from the above pydocusign.
The pydocusign library is not from DocuSign. You're welcome to use it but we (DocuSign folks) can't provide advice about it.
Instead, I suggest that you check out the DocuSign SDK for Python.
There is an example app that includes many example workflows. Workflow example 1 shows how to create an embedded signing ceremony.
Added
For embedded sending, see Workflow example 11.

flask: hashes "#" in the routing

I'm working with google API lately and use simple flask method to retrieve some id_token.
here is my code with explanations in comment:
#app.route('/afterlogin/id_token')
def afterlogin(id): # get the id
print(id) # print it
return render_template(r'creds_view.html', data=id) # and render the template with 'id' in it (for test purposes)
So what happens is that after the user logins, the api redirects the id_token to http://localhost:8000/afterlogin/#id_token=some_id_token.
but for some reason it is showing me 404 error.
i think it is because of the '#' in the url , i want the id_token. i know that '#' in html means for path linking or routing in 'href'.
so for that i tried.
#app.route('/afterlogin/<path:id>')
but the error still persists.
any guesses?
Everything after # is processed locally by the browser, it's not sent to the server, so you can't use it in routing. Leave out the #:
http://localhost:8000/afterlogin/some_id_token

administrator has not consented to use the application -- Azure AD

I am trying to obtain a token from Azure AD from Python client application. I want users to seamlessly authenticate with just a username and password (client_id / secret will be embedded in the app). I registered my app and given it all permissions and hit the "grant permissions" button in the new portal according to this post:
The user or administrator has not consented to use the application - Send an interactive authorization request for this user and resource
I am sending an http post to:
https://login.microsoftonline.com/{tenant_id}/oauth2/token
with the following data:
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
body = "resource={0}&grant_type=password&username={1}&password={2}&client_id={3}&client_secret={4}&scope=openid".format(app_id_uri,user,password,client_id,client_secret)
I cannot seem to get past this error no matter what I try:
b'{"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID \'078c1175-e384-4ac7-9116-efbebda7ccc2\'. Send an interactive authorization request for this user and resource.
Again, my goal:
User enters user / pass and nothing else. App sends user / pass / client_id / client_secret, obtains token.
According to your comment:
The message I'm receiving says to do an interactive request but that is exactly what I'm trying to avoid because this is a python app with no web browser and I'm trying to avoid complexity.
I think you want to build a daemon app or an app only application integrating with Azure AD. You can refer to https://graph.microsoft.io/en-us/docs/authorization/app_only for the general introduction.
Furthermore, you can leverage the ADAL for Python to implement this functionality with a ease. Also, you can refer to client_credentials_sample.py for a quick start.
You should try logging in as an admin to be able to give consent to use the application on your tenant at all.

401 Unauthorized making REST Call to Azure API App using Bearer token

I created 2 applications in my Azure directory, 1 for my API Server and one for my API client. I am using the Python ADAL Library and can successfully obtain a token using the following code:
tenant_id = "abc123-abc123-abc123"
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token = context.acquire_token_with_username_password(
'https://myapiserver.azurewebsites.net/',
'myuser',
'mypassword',
'my_apiclient_client_id'
)
I then try to send a request to my API app using the following method but keep getting 'unauthorized':
at = token['accessToken']
id_token = "Bearer {0}".format(at)
response = requests.get('https://myapiserver.azurewebsites.net/', headers={"Authorization": id_token})
I am able to successfully login using myuser/mypass from the loginurl. I have also given the client app access to the server app in Azure AD.
Although the question was posted a long time ago, I'll try to provide an answer. I stumbled across the question because we had the exact same problem here. We could successfully obtain a token with the adal library but then we were not able to access the resource I obtained the token for.
To make things worse, we sat up a simple console app in .Net, used the exact same parameters, and it was working. We could also copy the token obtained through the .Net app and use it in our Python request and it worked (this one is kind of obvious, but made us confident that the problem was not related to how I assemble the request).
The source of the problem was in the end in the oauth2_client of the adal python package. When I compared the actual HTTP requests sent by the .Net and the python app, a subtle difference was that the python app sent a POST request explicitly asking for api-version=1.0.
POST https://login.microsoftonline.com/common//oauth2/token?api-version=1.0
Once I changed the following line in oauth2_client.py in the adal library, I could access my resource.
Changed
return urlparse('{}?{}'.format(self._token_endpoint, urlencode(parameters)))
in the method _create_token_url, to
return urlparse(self._token_endpoint)
We are working on a pull request to patch the library in github.
For the current release of Azure Python SDK, it support authentication with a service principal. It does not support authentication using an ADAL library yet. Maybe it will in future releases.
See https://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html#authentication for details.
See also Azure Active Directory Authentication Libraries for the platforms ADAL is available on.
#Derek,
Could you set your Issue URL on Azure Portal? If I set the wrong Issue URL, I could get the same error with you. It seems that your code is right.
Base on my experience, you need add your application into Azure AD and get a client ID.(I am sure you have done this.) And then you can get the tenant ID and input into Issue URL textbox on Azure portal.
NOTE:
On old portal(manage.windowsazure.com),in the bottom command bar, click View Endpoints, and then copy the Federation Metadata Document URL and download that document or navigate to it in a browser.
Within the root EntityDescriptor element, there should be an entityID attribute of the form https://sts.windows.net/ followed by a GUID specific to your tenant (called a "tenant ID"). Copy this value - it will serve as your Issuer URL. You will configure your application to use this later.
My demo is as following:
import adal
import requests
TenantURL='https://login.microsoftonline.com/*******'
context = adal.AuthenticationContext(TenantURL)
RESOURCE = 'http://wi****.azurewebsites.net'
ClientID='****'
ClientSect='7****'
token_response = context.acquire_token_with_client_credentials(
RESOURCE,
ClientID,
ClientSect
)
access_token = token_response.get('accessToken')
print(access_token)
id_token = "Bearer {0}".format(access_token)
response = requests.get(RESOURCE, headers={"Authorization": id_token})
print(response)
Please try to modified it. Any updates, please let me know.

Categories

Resources