Authlib fetch_token issue - authlib

when i attempt to run following :
from authlib.integrations.requests_client import OAuth2Session
APPCLIENTID=os.getenv('AppClientId')
APPCLIENTSECRET=os.getenv('AppClientSecret')
USERNAME2=os.getenv("Username2")
PASSWORD2=os.getenv("Password222")
scope = 'openid email profile'
token_endpoint = 'https://api-product-test99.auth.eu-west-1.amazoncognito.com/oauth/token'
client = OAuth2Session(APPCLIENTID, APPCLIENTSECRET, scope=scope) #, redirect_uri="https://localhost/callback"
ar = 'https://localhost/callback?code=xxxxxx&state=xxxxx'
token = client.fetch_token(token_endpoint, authorization_response=ar)
print(token)
i get the message :
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
im just following the example on the Authlib page.
Am I missing something ?

Related

How can I get a JWT Access Token using Docusign 4.0.4.0

I have a legacy application written in VB6 (I Know!!) to which I am adding a DocuSign feature. I a using InterOp to run .NET code written is VS2019 VB.Net. The reason I am using 4.0.4.0 as this is the version I can successfully call using InterOp. I have all the code working except for requesting a JWT token. Does anyone have JWT code working under this version of the API ?
This is what I have working under later versions of DocuSign and am trying to replace
`Dim privatekey As Byte() = File.ReadAllBytes("docusign_private_key.key")
Dim result As Object = x.RequestJWTApplicationToken(gsSIGNERCLIENTID, docuSignAuthServer, privatekey, 1, scopes)
txtAccessToken.Text = result
'
' Second attempt at alternative
'
` Dim authToken As OAuth.OAuthToken = x.RequestJWTUserToken(gsSIGNERCLIENTID, gsUserIDGUID, docuSignAuthServer, privatekey, 1)
txtAccessToken.Text = authToken.access_token`
'
' Third attempt
'
Dim request = TryCast(System.Net.WebRequest.Create("https://account-d.docusign.com/oauth/token"), System.Net.HttpWebRequest)
request.Method = "POST"
request.Headers.Add("username", "user123")
request.Headers.Add("password", "123")
request.Headers.Add("auth_access_type", "read")
request.ContentLength = 0
Dim responseContent As String = ""
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
End Using
End Using
'
' Fifth attempt
'
Dim apiClient5 As New ApiClient(gsBASEPATH)
Dim authToken5 As OAuth.OAuthToken = apiClient5.RequestJWTUserToken(gsINTEGRATIONKEY, gsUserIDGUID, "https://account-d.docusign.com/oauth/token", privatekey, 1, scopes)
All results in 'Error while requesting server, received a non-successful HTPC code Error with response Body'
Your second attempt is correct:
Dim authToken As OAuth.OAuthToken = x.RequestJWTUserToken(gsSIGNERCLIENTID, gsUserIDGUID, docuSignAuthServer, privatekey, 1)
txtAccessToken.Text = authToken.access_token
AuthServer has to be "account-d.docusign.com"
The privateKey has to be the exact thing you got from DocuSign, including the new lines and all. To get it use this code:
File.ReadAllBytes(path) where path is the path on the disk to a plain text file with your private key.
gsSIGNERCLIENTID should be the GUID for the user that you use that has consent. You must make sure user gave consent by building a consent URL as explained in here:
https://developers.docusign.com/platform/auth/consent/obtaining-individual-consent/
If you did all of this correctly - it should work.

CL_HTPP_CLIENT CODE 400 BAD REQUEST - ABAP

i am trying to Post a Json to a Web Service.
The connection is good , but Unfortunately the payload arrives empty to the other side.
The Variable Jsondata is not empty and is a string.
I dont know what is missing. I have another Service to another api with a small json and works well.
Call Method cl_http_client=>create_by_url
Exporting
url = url
Importing
client = client
Exceptions
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
Others = 4.
If Sy-Subrc Ne 0.
Raise Error_conexion_token.
Else.
.
Data(Bearer) = 'Bearer' && | | && token.
client->request->set_header_field(
Exporting
name = 'Authorization'
value = Bearer ).
client->request->set_header_field(
Exporting
Name = 'Content-Type'
Value = 'application/json; charset=utf-8' ).
Call method client->request->set_cdata(
Exporting data = jsondata ).
client->request->set_method( if_http_request=>co_request_method_post).
Call Method client->send.
If sy-subrc Ne 0.
Raise Error_conexion_token.
Else.
Call Method client->receive
Exceptions
http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3
Others = 4.
If sy-subrc Ne 0.
Data(rc) = sy-subrc.
client->get_last_error(
Importing
code = zhcm_fdexperience=>codigo
message = zhcm_fdexperience=>mensaje ).
Case rc.
When 1.
Raise http_communication_failure.
When 2.
Raise http_invalid_state.
When 3.
Raise http_processing_failed.
Endcase.
Else.
client->get_last_error(
Importing
code = zhcm_fdexperience=>codigo
message = zhcm_fdexperience=>mensaje ).
Call method client->response->get_status( Importing code = zhcm_fdexperience=>codigo
reason = zhcm_fdexperience=>mensaje ).
If zhcm_fdexperience=>codigo Ne '200' Or zhcm_fdexperience=>codigo Ne '000' Or zhcm_fdexperience=>codigo Ne '0'.
Clear zhcm_fdexperience=>codigo.
Clear zhcm_fdexperience=>mensaje.
Data(Respuesta) = client->response->get_cdata( ).
Else.
Respuesta = client->response->get_cdata( ).
Endif.
Call method client->close.
An this is the json.
{
"data": [
{
"apiTipo": 1,
"fechaHoraAccion": "07/09/2021 21:20:03",
"nombreUsuarioSAP": "JUAN",
"numeroPersonal": "00001127",
"numeroPersonalREF": "sin información",
"tratamiento": "Señor",
"apellidoPaterno": "letelier",
"apellidoMaterno": "diaz",
"nombre": "rodrigo",
"sexo": "masculino",
"fechaNacimiento": "29/05/1985",
"estadoCivil": "Casado",
"nacionalidad": "Argentina",
"documentoIdentidad": "15902492-2",
"sociedad": "SBIO",
"divisionPersona": "CL01",
"centroCosto": "sin información",
"subdivisionPersona": "sin información",
"calleNumero": "ladies nIght 3221",
"ciudad": "san fernando",
"region": "Libertador Bernardo",
"pais": "Chile",
"telefono": "717846",
"claseContrato": "INDEFINIDO",
"plazoPreavEmpresa": "22.5 HORAS SEMANALES",
"reglaPlanJornadaColaborador": "BHADP201",
"statGestionTiempo": "9 - Evaluacion",
"indAdicTiempo": "NC",
"claseConvenio": "Sin Negociacion",
"areaConvenio": "No Sindicalizado",
"grupoProfesional": "General",
"subgrupoProfesional": "01",
"claseCorreoPersonal": "adiazs#funk.com",
"idSistema": "0016",
"fechaInicio": "22/08/2021",
"fechaFin": "31/12/9999"
}
]
}
Note : I tested in postman and works well.

clients = self.AVAILABLE_CLIENTS[name] KeyError: 'requests' flask authlib client

good day everybody,
having some issues with flask and authlib. Bellow snip of my flash code
from flask import Flask, render_template
from authlib.integrations.flask_client import OAuth
import os
app = Flask(__name__)
app._static_folder = os.path.abspath("static")
app.config.from_object('config')
oauth = OAuth(app)
webex = oauth.register(name='WEBEX', redirect_uri='http://webapp.dcloud.cisco.com:5000/AuthWebex', client_kwargs={
'scope': 'spark:all'
} )
config.py
import os
WEBEX_CLIENT_ID='C3a256be511cdf07e19f272960c44a214aec14b727b108e4f10bd124d31d2112c'
WEBEX_CLIENT_SECRET='secret'
WEBEX_ACCESS_TOKEN_URL='https://api.ciscospark.com/v1/access_token'
WEBEX_REDIRECT_URI='http://localhost:5000/AuthWebex'
WEBEX_SCOPE='spark:all'
when running above code I get the following error:
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/authlib/integrations/flask_client/oauth_registry.py", line 61, in register
self.use_oauth_clients()
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/authlib/integrations/_client/oauth_registry.py", line 49, in use_oauth_clients
clients = self.AVAILABLE_CLIENTS[name]
KeyError: 'requests'
looked at examples and did some research, no luck. Can't find any solution...
thanks in adv.
Tobi
UPDATE:
per comment bellow here the latest code:
from flask import Flask, render_template, url_for, request
from authlib.integrations.flask_client import OAuth
import os
import requests
app = Flask(__name__)
app._static_folder = os.path.abspath("static")
app.config.from_object('config')
app.secret_key = os.urandom(24)
oauth = OAuth(app)
oauth.register(
'webex',
api_base_url='https://api.ciscospark.com/v1',
authorize_url='https://api.ciscospark.com/v1/authorize',
access_token_url='https://api.ciscospark.com/v1/access_token',
redirect_uri='http://webapp.dcloud.cisco.com:5000/AuthWebex',
scope='spark:all')
#app.route('/')
def main():
"""Entry point; the view for the main page"""
return render_template('main.html')
#app.route('/authorize')
def authorize():
return render_template('authorize.html')
#app.route('/login')
def login():
#redirect_uri = url_for('AuthWebex', _external=True)
redirect_uri = 'http://webapp.dcloud.cisco.com:5000/AuthWebex'
print(redirect_uri)
return oauth.webex.authorize_redirect(redirect_uri)
#app.route('/AuthWebex')
def AuthWebex():
#print(request.__dict__)
token = oauth.webex.authorize_access_token( authorization_response=request.url,
redirect_uri='http://webapp.dcloud.cisco.com:5000/AuthWebex',
client_id='C3a256be511cdf07e19f272960c44a214aec14b727b108e4f10bd124d31d2112c',
client_secret='secret',
)
print("Token: ", token)
resp = oauth.webex.get('https://api.ciscospark.com/v1/people/me')
profile = resp.json()
print(profile)
# do something with the token and profile
return '<html><body><h1>Authenticated</h1></body></html>'
if __name__ == '__main__':
app.run()
oauth.webex.authorize_access_token function throws and error when called without the parameters. which is strange as most examples I found exactly do that.
client_id and client_secret are set via the config.py file. This works for the oauth.register function but not for the authorize_access_token.
Additional problem is that even with the parameters, it produces a valid token. When I call the get function I get the following error:
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/requests/models.py", line 317, in prepare
self.prepare_auth(auth, url)
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/requests/models.py", line 548, in prepare_auth
r = auth(self)
File "/Users/tneumann/PycharmProjects/untitled/venv/lib/python3.7/site-packages/authlib/integrations/requests_client/oauth2_session.py", line 41, in __call__
raise UnsupportedTokenTypeError(description=description)
authlib.integrations._client.errors.UnsupportedTokenTypeError: unsupported_token_type: Unsupported token_type: 'token_type'
here is the format of the token returned from authorize_access_token function
Token: {'access_token': 'YWIzNGU3<secret>tNDQ5_PF84_7cc07dbd-<secret>-5877334424fd', 'expires_in': 1209599, 'refresh_token': 'MjU2ZDM4N2Et<secret>ZmItMTg5_PF84_7cc07dbd-<secret>877334424fd', 'refresh_token_expires_in': 7722014, 'expires_at': 1574863645}
went through the docs, the code on github and debugging in pycharm with no luck, help would be much appreciated!
The problem here is that this AuthWebex is not a standard OAuth service. The response has no token_type. We can fix it with Authlib compliance fix:
Check the example here:
https://docs.authlib.org/en/latest/client/frameworks.html#compliance-fix-for-oauth-2-0
The slack example has the same issue.

Authenticate from Retrofit with JWT token to Rest server

my server is Flask based, my client is android studio, and i'm communication using retrofit.
The problem is that i'm not able to pass the jwt token correctly from the android to the server after logging in.
With postman it's working good:
{{url}}/auth - I'm logging in as the user, and getting the JWT token.
Later i'm adding "Authorization" header, with the Value "JWT {{jwt_token}}" and
{{url}}/users/john - I'm asking for user info, which is recieved without problems.
The endpoint from android studio:
public interface RunnerUserEndPoints {
// #Headers("Authorization")
#GET("/users/{user}")
Call<RunnerUser> getUser(#Header("Authorization") String authHeader, #Path("user") String user);
The call itself (The access_token is correct before sending!):
final RunnerUserEndPoints apiService = APIClient.getClient().create(RunnerUserEndPoints.class);
Log.i("ACCESS","Going to send get request with access token: " + access_token);
Call<RunnerUser> call = apiService.getUser("JWT" + access_token, username);
Log.i("DEBUG","Got call at loadData");
call.enqueue(new Callback<RunnerUser>() {
#Override
public void onResponse(Call<RunnerUser> call, Response<RunnerUser> response) { ....
The response error log from the server:
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 176, in decorator
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 151, in _jwt_required
token = _jwt.request_callback()
File "C:\Users\Yonatan Bitton\RestfulEnv\lib\site-packages\flask_jwt\__init__.py", line 104, in _default_request_handler
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
flask_jwt.JWTError: Invalid JWT header. Unsupported authorization type
10.0.0.6 - - [30/Sep/2017 01:46:11] "GET /users/john HTTP/1.1" 500 -
My api-client
public class APIClient {
public static final String BASE_URL = "http://10.0.0.2:8000";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
Log.i("DEBUG APIClient","CREATED CLIENT");
return retrofit;
}
}
Actually i'm really stuck. Tried to follow along all of the tutorials at retrofit's website without success.
I'm sure that there is a simple solution, I just need to add "Authorization" Header with Value "JWT " + access_token like it works in postman and that's it! Thanks.
EDIT:
The problem was the build of the access_token in my client.
I did:
JsonElement ans = response.body().get("access_token");
access_token = "JWT " + ans.toString();
Which I should have done:
JsonElement ans = response.body().get("access_token");
access_token = "JWT " + ans.getAsString();
So before it sent "JWT "ey..." " (Double "" )
And now it sends "JWT ey ... "
Let's start to look at what we know about the problem.
We know that the request is sent
We know that the server processes the request
We know that the JWT is invalid thanks to the error:
JWTError('Invalid JWT header', 'Unsupported authorization type')
If we look for that error in the flask_jwt source code, we can see that this is where our error is raised:
def _default_request_handler():
auth_header_value = request.headers.get('Authorization', None)
auth_header_prefix = current_app.config['JWT_AUTH_HEADER_PREFIX']
if not auth_header_value:
return
parts = auth_header_value.split()
if parts[0].lower() != auth_header_prefix.lower():
raise JWTError('Invalid JWT header', 'Unsupported authorization type')
elif len(parts) == 1:
raise JWTError('Invalid JWT header', 'Token missing')
elif len(parts) > 2:
raise JWTError('Invalid JWT header', 'Token contains spaces')
return parts[1]
Basically flask_jwt takes the Authorization header value and tries to split it into two. The function split can split a string by a delimiter, but if you call it without a delimiter it will use whitespace.
That tells us that flask_jwt expects a string that contains 2 parts separated by whitespace, such as space, and that the first part must match the prefix we are using (in this case JWT).
If we go back and look at your client code, we can see that when you are building the value to be put in the Authorization header you are not adding a space between JWT and the actual token:
apiService.getUser("JWT" + access_token, username);
This is what you should have been doing:
apiService.getUser("JWT " + access_token, username);
Notice the space after JWT?

Matlab urlread2 - HTTP response code: 415 for URL

I am attempting to access the betfair API using Matlab and the urlread2 function available here.
EDIT: I have posted this problem on Freelancer if anyone can help with it: tinyurl.../pa7sblb
The documentation for the betfair API I am following is this getting started guide. I have successfully logged in and kept the session open using these codes: (I am getting a success response)
%% Login and get Token
url = 'https://identitysso.betfair.com/api/login';
params = {'username' '******' 'password' '******'};
header1 = http_createHeader('X-Application','*****');
header2 = http_createHeader('Accept','application/json');
header = [header1, header2];
[paramString] = http_paramsToString(params)
[login,extras] = urlread2(url,'POST',paramString,header)
login = loadjson(login)
token = login.token
%% Keep Alive
disp('Keep Session Alive')
url_alive = 'https://identitysso.betfair.com/api/keepAlive';
header1 = http_createHeader('X-Application','******');
header2 = http_createHeader('Accept','application/json');
header3 = http_createHeader('X-Authentication',token');
header_alive = [header1, header2, header3];
[keep_alive,extras] = urlread2(url_alive,'POST',[],header_alive);
keep_alive = loadjson(keep_alive);
keep_alive_status = keep_alive.status
My trouble starts when I am attempting to do the next step and load all available markets. I am trying to replicate this example code which is designed for Python
import requests
import json
endpoint = "https://api.betfair.com/exchange/betting/rest/v1.0/"
header = { 'X-Application' : 'APP_KEY_HERE', 'X-Authentication' : 'SESSION_TOKEN_HERE' ,'content-type' : 'application/json' }
json_req='{"filter":{ }}'
url = endpoint + "listEventTypes/"
response = requests.post(url, data=json_req, headers=header)
The code I am using for Matlab is below.
%% Get Markets
url = 'https://api.betfair.com/exchange/betting/rest/v1.0/listEventTypes/';
header_application = http_createHeader('X-Application','******');
header_authentication = http_createHeader('X-Authentication',token');
header_content = http_createHeader('content_type','application/json');
header_list = [header_application, header_authentication, header_content];
json_body = savejson('','filter: {}');
[list,extras] = urlread2(url_list,'POST',json_body,header_list)
I am having trouble with a http response code 415. I believe that the server cannot understand my parameter since the headings I have used with success previously.
Any help or advice would be greatly appreciated!
This is the error:
Response stream is undefined
below is a Java Error dump (truncated):
Error using urlread2 (line 217)
Java exception occurred:
java.io.IOException: Server returned HTTP response code: 415 for URL....
I looked at your problem and it seems to be caused by two things:
1) The content type should be expressed as 'content-type' and not 'content_type'
2) The savejson-function doesn't create an adequate json-string. If you use the json-request from the Python-script it works.
This code work for me:
%% Get Markets
url = 'https://api.betfair.com/exchange/betting/rest/v1.0/listEventTypes/';
header_application = http_createHeader('X-Application','*********');
header_authentication = http_createHeader('X-Authentication',token');
header_content = http_createHeader('content-type','application/json');
header_list = [header_application, header_authentication, header_content];
json_body = '{"filter":{ }}';
[list,extras] = urlread2(url,'POST',json_body,header_list)