AWS API Gateway Post Requests - amazon-web-services

I created an api with AWS Api Gateway and when I try to execute a POST request I get a 403 vs when I do GET request it returns 200 and returns the data I expect.
data = json.dumps({'to': 'USD', 'from': 'CNY', 'start': '2022-03-01', 'end': '2022-12-01'})
requests.get(url,headers = headers,data=data).json()
headers = {'Content-type': 'application/json'}
data = json.dumps({'to': 'USD', 'from': 'CNY', 'start': '2022-03-01', 'end': '2022-12-01'})
requests.post(url,headers = headers,data=data).json()
>>> {'message': 'Missing Authentication Token'}
How do I authenticate to get a 200 for a post requests ?

Related

Google cloud reCAPTCHA Enterprise showing invalid argument error

devs.
I am migrating my Recaptcha V2 to the Recaptcha enterprise using the below link.
https://cloud.google.com/recaptcha-enterprise/docs/using-features
the frontend integration part work and the Recaptcha checkbox part are showing.
On the backend side after the user submit the form passing the Recaptcha test. to verify the Recaptcha test, I call google REST API to create an assessment.
I am using this link.
https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#rest-api
code of the function to verify user response.
def verify_captcha_response(self, recaptcha_response):
"""
Verify the Google Recaptcha V2 response of the request
- if recatacha response value is more than the value set
on google recaptcha admin.
- if request fail error will be raise and no response will be accept
"""
if not recaptcha_response:
return False
if isinstance(recaptcha_response, list):
recaptcha_response = recaptcha_response[0]
url = "https://recaptchaenterprise.googleapis.com/v1/projects/%s/assessments?key=%s" % ("Project id", settings.RECAPTCHA_SITE_KEY)
recaptcha_secret_key = settings.RECAPTCHA_SECRET_KEY,
headers={'Content-Type': 'application/json'}
data = {
"event":{
"token": recaptcha_response,
"siteKey": recaptcha_secret_key,
"expectedAction": "login"
}
}
response = requests.post(url, headers=headers,
data=data)
result = response.json()
if not result['success']:
if 'timeout-or-duplicate' in result['error-codes']:
raise forms.ValidationError(msg.RECAPTCHA_FAILED)
return False
return True
The response I am getting.
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT"
}
}
but as per the documentation, I am passing all the arguments.
Thank you.

Invoking PowerBi rest api and generate token

I want to invoke PowerBI rest api calls to upload pbix files from local/specific repository.
How should I generate bearer token for authorization from Postman?
Will this rest api call work to generateToken?
What needs to passed as authorization token for this rest call?
Does myorg is the PowerBI account name? from where can I fetch the myorg value?
POST https://api.powerbi.com/v1.0/myorg/GenerateToken
Below are few more calls that I want to invoke through postman:
GET https://api.powerbi.com/v1.0/myorg/imports
GET https://api.powerbi.com/v1.0/myorg/reports/{reportId}
and few post calls also.
What will be a quick solution for generating token?
You can use this function to request access
it is necessary to create the Client ID in azure
https://learn.microsoft.com/en-us/power-bi/developer/embedded/register-app?tabs=customers%2CAzure
application_id= 'None'
application_secret= 'None'
user_id= 'None'
user_password= 'None'
accessToken = None
requestHeaders = None
tokenExpiry = None
accessToken_AD = None
requestHeaders_AD = None
tokenExpiry_AD = None
def pbi_auth(application_id,application_secret,user_id,user_password):
global accessToken
global requestHeaders
global tokenExpiry
data = {
'grant_type': 'password',
'scope': 'openid',
'resource': "https://analysis.windows.net/powerbi/api",
'client_id': application_id,
'client_secret': application_secret,
'username': user_id,
'password': user_password
}
token = requests.post("https://login.microsoftonline.com/common/oauth2/token", data=data)
assert token.status_code == 200, "Fail to retrieve token: {}".format(token.text)
#print("Got access token: ")
#print(token.json())
accessToken = token.json()['access_token']
requestHeaders= {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': "Bearer {}".format(accessToken)
}
pbi_auth(application_id,application_secret,user_id,user_password)
reportId= ""
URI = "https://api.powerbi.com/v1.0/myorg/reports/{}".format(reportId)
queryResults = requests.get(URI, headers=requestHeaders)

403 Forbidden when trying to register receiver endpoint using the RISC API

While trying to register my receiver endpoint in order to start receiving RISC indications from google, I constantly get the same reply:
403 Client Error: Forbidden for url:
https://risc.googleapis.com/v1beta/stream:update
I have created the service with the Editor Role and using the json key I created as requested on the integration guide.
This is my provisioning code I use to do that:
import json
import time
import jwt # pip install pyjwt
import requests
def make_bearer_token(credentials_file):
with open(credentials_file) as service_json:
service_account = json.load(service_json)
issuer = service_account['client_email']
subject = service_account['client_email']
private_key_id = service_account['private_key_id']
private_key = service_account['private_key']
issued_at = int(time.time())
expires_at = issued_at + 3600
payload = {'iss': issuer,
'sub': subject,
'aud': 'https://risc.googleapis.com/google.identity.risc.v1beta.RiscManagementService',
'iat': issued_at,
'exp': expires_at}
encoded = jwt.encode(payload, private_key, algorithm='RS256',
headers={'kid': private_key_id})
return encoded
def configure_event_stream(auth_token, receiver_endpoint, events_requested):
stream_update_endpoint = 'https://risc.googleapis.com/v1beta/stream:update'
headers = {'Authorization': 'Bearer {}'.format(auth_token)}
stream_cfg = {'delivery': {'delivery_method': 'https://schemas.openid.net/secevent/risc/delivery-method/push',
'url': receiver_endpoint},
'events_requested': events_requested}
response = requests.post(stream_update_endpoint, json=stream_cfg, headers=headers)
response.raise_for_status() # Raise exception for unsuccessful requests
def main():
auth_token = make_bearer_token('service_creds.json')
configure_event_stream(auth_token, 'https://MY-ENDPOINT.io',
['https://schemas.openid.net/secevent/risc/event-type/sessions-revoked',
'https://schemas.openid.net/secevent/oauth/event-type/tokens-revoked',
'https://schemas.openid.net/secevent/risc/event-type/account-disabled',
'https://schemas.openid.net/secevent/risc/event-type/account-enabled',
'https://schemas.openid.net/secevent/risc/event-type/account-purged',
'https://schemas.openid.net/secevent/risc/event-type/account-credential-change-required'])
if __name__ == "__main__":
main()
Also tested my auth token and it seems as the integration guide suggests.
Could not find 403 forbidden on the error code reference table there.
You can check for error description in the response body and match that against the possible reasons listed here!

getting code 400 message Bad request syntax , after post from flutter

getting code 400 message Bad request syntax , after post from flutter,
with postman request send and no problem but with flutter after Post Map data to Django server i get this error
[19/May/2020 14:58:13] "POST /account/login/ HTTP/1.1" 406 42
[19/May/2020 14:58:13] code 400, message Bad request syntax ('32')
[19/May/2020 14:58:13] "32" 400 -
Django
#api_view(['POST'])
def login_user(request):
print(request.data)
if request.method == 'POST':
response = request.data
username = response.get('username')
password = response.get('password')
if password is not None and username is not None:
user = authenticate(username=username, password=password)
if user is not None:
create_or_update_token = Token.objects.update_or_create(user=user)
user_token = Token.objects.get(user=user)
return Response({'type': True, 'token': user_token.key, 'username': user.username},
status=status.HTTP_200_OK)
else:
return Response({'type': False, 'message': 'User Or Password Incorrect'},
status=status.HTTP_404_NOT_FOUND)
else:
return Response({'type': False, 'message': 'wrong parameter'}, status=status.HTTP_406_NOT_ACCEPTABLE)
else:
return Response({'type': False, 'message': 'method is wrong'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
flutter
Future<dynamic> postGoa(String endpoint, Map data)async{
Map map = {
"username":"user",
"password":"password"
};
var url = _getUrl("POST", endpoint);
var client = new HttpClient();
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.headers.set('Authorization', 'Bearer '+ athenticated
);
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String mydata= await response.transform(utf8.decoder).join();
client.close();
return mydata;
}
}
after add
request.add(utf8.encode(json.encode(map)));
i get error in Django console
Try printing out your request headers from the Django application.
print(request.headers)
I bet one of the headers is Content-Type: ''. If that is the case, Django isn't reading your POST data because it thinks there is no data. I recommend calculating the length of the content you are sending in Flutter, then sending the correct Content-Length header with your request.
That might look something like this (in your Flutter app):
encodedData = jsonEncode(data); // jsonEncode is part of the dart:convert package
request.headers.add(HttpHeaders.contentLengthHeader, encodedData.length);

Django OAuth2 unsupported_grant_type

I'm trying to send a request with django to get an access_token from my api using OAuth2. I'm executing this code :
data = {'username': 'admin', 'password': '123123', 'grant_type':
'password','client_id': 'xxx','client_secret': 'xxx'}
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=data, headers=headers)
When I send this request I get this error :
{'error': 'unsupported_grant_type'}
Thanks for your help !
If anyone is interested the correct request was :
payload = "grant_type=password&client_secret=xxx&client_id=xxx&username=username&password=password"
headers = {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache",
}
response = requests.request("POST", url, data=payload, headers=headers)
If you don't want to encode data in url, you can put this in your settings.
OAUTH2_PROVIDER = {
'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
}
I had the same problem and later I found that the grant type should be a string.
payload = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}