Unable to login by using LinkidIn social login - django

I am trying to login using social logins like google,github,facebook but when i am trying that in case of LinkedIn i am getting the following error
HTTPError at /social/linkedin_login/
HTTP Error 404: Not Found
I am user v2 for linkedin
views.py
required_info = "id,first-name,last-name,email-address,location,positions,educations,industry,summary,public-profile-url,picture-urls::(original)"
rty = "https://api.linkedin.com/v2/me:(" + required_info + ")" + \
"?format=json&oauth2_access_token="
rty += accesstoken
details = ur.urlopen(rty).read().decode('utf8')
I am getting error in details = ur.urlopen(rty).read().decode('utf8')
else:
rty = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=" + \
settings.LN_API_KEY
rty += "&scope=r_liteprofile r_emailaddress w_member_social&state=8897239179ramya"
rty += "&redirect_uri=" + request.scheme + '://' + \
request.META['HTTP_HOST'] + reverse('social:linkedin_login')
return HttpResponseRedirect(rty)
Can someone help me out of this error.

The format you are using resembles LinkedIn's v1 API. You will need to update your request URL to be https://api.linkedin.com/v2/me, with the OAuth 2.0 access token added to the Authorization: Bearer header.

Related

Private API gateway with IAM authentication not liking my security token

I have a private API gateway with a / endpoint and a /foo with IAM auth enabled.
I created a policy which I attached to my instance's role :
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:*:*:*"
]
}
]
}
I have some code to do the AWS signature stuff and also used Postman to create a snippet with the same key/secret/session token. Both give the same result on /foo. It always says :
{"message":"The security token included in the request is invalid"}
I had a concern that the docs do not say you can attach the policy to a role only a user or group.
https://aws.amazon.com/premiumsupport/knowledge-center/iam-authentication-api-gateway/
That whole page doesn't mention roles once... Can I attach a policy to a role to use it with IAM auth'ed API gateway??
The / endpoint returns me a 200 response, and my API GW resource policy denies/allows access to *. If I can get to /, I can get to /foo. (And if I disable the IAM auth, I can get /foo)
The VPC endpoint allows * on *.
In the execution logs I see nothing for the failed attempts.
The attempts to / log : API Key authorized because method 'GET /' does not require API Key. Request will not contribute to throttle or quota limits
And I can see the X-Amz-Security-Token in the payload.
But requests to /foo don't appear there, only the access logs. And I've added some fields but nothing that sheds any light on the problem.
Anything I'm forgetting?? And any ideas why isn't it working?
Here is my signing python, there may be a bug, but it is getting the same error as Postman, which makes me think not! Replace the host/endpoint and path to your own. I added a few print debug lines to show the intermediate steps because I did get some errors about the canonical URL being wrong to start with.
#!/usr/bin/python3
# This is based on the AWS General Reference
# Signing AWS API Requests top available at
# https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
# To use it :
# pip3 install requests
# To use it on instance with instance role :
# sudo yum -y -q install jq
# export AWS_ACCESS_KEY_ID=$(curl 169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance | jq -r .AccessKeyId)
# export AWS_SECRET_ACCESS_KEY=$(curl 169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance | jq -r .SecretAccessKey)
# export AWS_SESSION_TOKEN=$(curl 169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance | jq -r .Token)
# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
# This version makes a GET request and passes the signature
# in the Authorization header.
import sys, os, base64, datetime, hashlib, hmac
import requests # pip install requests
# ************* REQUEST VALUES *************
method = 'GET'
service = 'execute-api'
host = 'xxx.execute-api.eu-west-2.amazonaws.com'
region = 'eu-west-2'
endpoint = 'https://xxx.execute-api.eu-west-2.amazonaws.com'
path='/stage/foo/'
request_parameters = ''
# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def getSignatureKey(key, dateStamp, regionName, serviceName):
kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
kRegion = sign(kDate, regionName)
kService = sign(kRegion, serviceName)
kSigning = sign(kService, 'aws4_request')
return kSigning
# Read AWS access key from env. variables or configuration file. Best practice is NOT
# to embed credentials in code.
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
session_token = os.environ.get('AWS_SESSION_TOKEN')
if access_key is None or secret_key is None:
print('No access key is available.')
sys.exit()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
# ************* TASK 1: CREATE A CANONICAL REQUEST *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
# Step 1 is to define the verb (GET, POST, etc.)--already done.
# Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
canonical_uri = path
# Step 3: Create the canonical query string. In this example (a GET request),
# request parameters are in the query string. Query string values must
# be URL-encoded (space=%20). The parameters must be sorted by name.
# For this example, the query string is pre-formatted in the request_parameters variable.
canonical_querystring = request_parameters
# Step 4: Create the canonical headers and signed headers. Header names
# must be trimmed and lowercase, and sorted in code point order from
# low to high. Note that there is a trailing \n.
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n' 'x-amz-security-token:' + session_token + '\n'
# Step 5: Create the list of signed headers. This lists the headers
# in the canonical_headers list, delimited with ";" and in alpha order.
# Note: The request can include any headers; canonical_headers and
# signed_headers lists those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
signed_headers = 'host;x-amz-date;x-amz-security-token'
# Step 6: Create payload hash (hash of the request body content). For GET
# requests, the payload is an empty string ("").
payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()
# Step 7: Combine elements to create canonical request
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
print ("CANONICAL REQUEST : " + canonical_request)
print ()
# ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
print ("STRING TO SIGN : " + string_to_sign )
# ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
signing_key = getSignatureKey(secret_key, datestamp, region, service)
# Sign the string_to_sign using the signing_key
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# The signing information can be either in a query string value or in
# a header named Authorization. This code shows how to use a header.
# Create authorization header and add to request headers
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
# The request can include any headers, but MUST include "host", "x-amz-date",
# and (for this scenario) "Authorization". "host" and "x-amz-date" must
# be included in the canonical_headers and signed_headers, as noted
# earlier. Order here is not significant.
# Python note: The 'host' header is added automatically by the Python 'requests' library.
headers = {'x-amz-date':amzdate, 'Authorization':authorization_header, 'X-Amz-Security-Token':session_token}
# ************* SEND THE REQUEST *************
request_url = endpoint + path + canonical_querystring
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL = ' + request_url)
print('Headers = ' + str(headers))
r = requests.get(request_url, headers=headers)
print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)
Aha, I found an answer. I was pulling the credentials from the wrong endpoint. https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-categories.html shows "identity-credentials/ec2/security-credentials/ec2-instance" are "Internal use only". There is an iam/security-credentials/{role} that works a LOT better!!

Integrating Sagepay (Opayo) with Django - How to create a merchant session key

I am trying to integrate Opayo (SagePay) with Django and I am having problems generation the merchant session key (MSK).
From sagepays docs they say to use the below curl request and that I should receive the key in the response
curl https://pi-test.sagepay.com/api/v1/merchant-session-keys \
-H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=" \
-H "Content-type: application/json" \
-X POST \
-d '{
"vendorName": "sandbox"
}'
I have tried to implement this in my Django view with the following code but I receive a 422 response (Unprocessable Entity response).
import requests
def BasketView(request):
headers = {
"Authorization": "Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=",
"Content-type": "application/json",
}
data = {"vendorName": "sandbox"}
r = requests.post("https://pi-test.sagepay.com/api/v1/merchant-session-keys", headers=headers, params=data)
print(r)
Any ideas where I may be going wrong with this?
You are passing the wrong parameter to requests.post() you should use jsoninstead of params:
r = requests.post(
"https://pi-test.sagepay.com/api/v1/merchant-session-keys",
headers=headers,
json=data
)
By doing so, there is no need to specify the Content-Type header, it is added automatically.

how to authenticate in HTTPS by NetHTTPClient

Hello
I must stress that I dont want use curl, and I must use only Embarcadero compiler. (C++Builder and Delphi)
I want send a request to a server which need authentication.
The complete command by API documentation is:
curl -X POST "https://api.demo.website.com/api/2/something" -H "accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -d "symbol=BTC&side=buy&type=limit&timeInForce=GTC&quantity=0.1&price=4000"
Their Authentication style they provide is:
curl -u "publicKey:secretKey" https://api.demo.website.com/api/2/something
Their suggested code is: (which is not C++) :-))
import requests
session = requests.session()
session.auth = ("publicKey", "secretKey")
const fetch = require('node-fetch');
const credentials = Buffer.from('publicKey' + ':' + 'secretKey').toString('base64');
fetch('https://api.demo.website.com/api/2/something', {
method: 'GET',
headers: {
'Authorization': 'Basic ' + credentials
}
});
My Code is:
TCredentialsStorage::TCredential *MyCredential = new TCredentialsStorage::TCredential(
TAuthTargetType::Server, "", "",
UserNameEdit->Text, PasswordEdit->Text);
NetHTTPClient1->CredentialsStorage->AddCredential(*MyCredential);
StatMemo->Lines->Add(IntToStr(NetHTTPClient1->CredentialsStorage->Credentials.RefCount));
TMemoryStream *Response=new TMemoryStream;
TMemoryStream *bbkTMS =new TMemoryStream;
TNameValueArray nva;
NetHTTPRequest1->Post(URLEdit->Text, bbkTMS, Response, nva);
StatMemo->Lines->LoadFromStream(bbkTMS);
Memo1->Lines->LoadFromStream(Response);
The code is compiling but ot working... :-|
It said:
{"error":{"code":1004,"message":"Unsupported authorization method"}}
Any suggestion for me?
I find it out :-)
As I am using RAD Tool (Embarcadero) So I can use its VCL/FMX component:
THTTPBasicAuthenticator
Done!
But instead NetHTTP component group I start using RESTClient component group, much more better.

django oauth toolkit unsupported_grant_type error

I tried to add outh2 to my django app, so I used django oauth toolkit.
So I followed the tutorial, but if I try to get the users token it always sends me a unsupported_grant_type error. How can I fix this error?
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
)
}
OAUTH2_PROVIDER = {
# parses OAuth2 data from application/json requests
'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.api.urls')),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
client type: confidential
authorization grant type: Resource owner password-based
chrome advanced rest client
url : http://client_id:client_secret#localhost:8000/o/token/
requirements.txt
asgiref==3.2.5
autopep8==1.5
certifi==2019.11.28
chardet==3.0.4
Django==3.0.4
django-oauth-toolkit==1.3.0
djangorestframework==3.11.0
idna==2.9
oauthlib==3.1.0
pycodestyle==2.5.0
pytz==2019.3
requests==2.23.0
sqlparse==0.3.1
urllib3==1.25.8
Just remove the OAUTH2_BACKEND_CLASS in the OAUTH2_PROVIDER settings.
OAUTH2_PROVIDER = {
# parses OAuth2 data from application/json requests
# 'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
If you intend to use the OAUTH2_BACKEND_CLASS, you should send the body in JSON format.
{
"grant_type":"password",
"client_id":"<client_id>",
"client_secret":"<client_secret>",
"username":"<usename>",
"password":"<password>"
}
curl -X POST -d '{"grant_type":"password","client_id":"<client_id>","client_secret":"<client_secret>","username":"<username>","password":"<password>"}' http://localhost:8000/o/token/
1. you have to create application :
http://localhost:8000/o/applications/
Click on the link to create a new application and fill the form with the following data:
Name : just a name of your choice
Client Type : confidential
Authorization Grant Type : Resource owner password-based
and you give clientId and SecretClient
2. Get your token and use your API
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
example:
curl -X POST -d "grant_type=password&username=Alex&password=Won123" -u"cWS5WudFiBhHh6BZxcaOgRGfrZjhcP2rfQcWVyaU:puNJ1SgQbp39Ai1TmYJx0wL9LnC6FNarnY3dgYBA3Z7AgQR5zRcfw5U144zxJ6vndW0jtV4WWKip33kQnFUl4v73xt2IosLGHo7k1w35R7aK8aFL3ZBoMcQ3pyaWjkBT" http://127.0.0.1:8000/o/token/
The user_name and password are the credential of the users registered in your Authorization server and finally in response you give token and use token like this for your request :
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/users
pay attention for your application config and your user name and password.

Retrieving data from Streamsets Data Collector (SDC) protected by Kerberos

I am trying to retrieve data from the SDC API protected by Kerberos. Initially i am posting the credentials to the SCH login page and then using the cookies generated to access the SDC rest api. However, i am not able to post the credentials. Response code is 401 and hence not able to access api.
dpm_auth_creds = {"userName":"", "password":"" }
headers = {"Content-Type": "application/json", "X-Requested-By": "SDC"}
auth_request = requests.post("https://url:18641/sch/security/users" , data=json.dumps(dpm_auth_creds), headers=headers, verify="file.pem")
cookies = auth_request.cookies
print(auth_request.status_code)
print(auth_request.headers)
url = requests.get("https://url:18641/jobrunner/rest/v1/sdcs", cookies=cookies)
print(url.text)
Response code is 401: for auth_request.status_code
This is from the REST API page in Control Hub:
# login to Control Hub security app
curl -X POST -d '{"userName":"DPMUserID", "password": "DPMUserPassword"}' https://cloud.streamsets.com/security/public-rest/v1/authentication/login --header "Content-Type:application/json" --header "X-Requested-By:SCH" -c cookie.txt
# generate auth token from security app
sessionToken=$(cat cookie.txt | grep SSO | rev | grep -o '^\S*' | rev)
echo "Generated session token : $sessionToken"
# Call SDC REST APIs using auth token
curl -X GET https://cloud.streamsets.com/security/rest/v1/currentUser --header "Content-Type:application/json" --header "X-Requested-By:SCH" --header "X-SS-REST-CALL:true" --header "X-SS-User-Auth-Token:$sessionToken" -i
So your Python code should be more like:
dpm_auth_creds = {"userName":"", "password":"" }
headers = {"Content-Type": "application/json", "X-Requested-By": "SDC"}
auth_request = requests.post("https://url:18641/security/public-rest/v1/authentication/login" , data=json.dumps(dpm_auth_creds), headers=headers, verify="file.pem")
cookies = auth_request.cookies
print(auth_request.status_code)
print(auth_request.headers)
# Need to pass value of SS-SSO-LOGIN cookie as X-SS-User-Auth-Token header
headers = {
"Content-Type":"application/json",
"X-Requested-By":"SCH",
"X-SS-REST-CALL":"true",
"X-SS-User-Auth-Token":auth_request.cookies['SS-SSO-LOGIN']
}
url = requests.get("https://url:18641/jobrunner/rest/v1/sdcs", headers=headers)
print(url.text)