django oauth toolkit unsupported_grant_type error - django

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.

Related

Reset password by using cURL restAPIs in wso2 IS

In wso2-IS 5.11, trying Update Password Operation through cURL restAPI command.
I got reset password mail notification for below curl request,
$ curl -X POST -k -H "Authorization: Basic YWRxxxx=" -H "Content-Type: application/json" -d '{"user": {"username": "John","realm": "PRIMARY"},"properties": []}' "https://localhost:9445/api/identity/recovery/v0.9/recover-password?type=email&notify=true"
but instead of reset the password in reset-password-window , I need to pass the reset password values through cURL same like this, but this also requires Confirmation keycode with validity period and this is availlable in IDN_RecoveryDataTable as per this doc, so where this "IDN recovery data table" find out.? and shall I use same operation? or need to try some different use cases like , active and inactive user via cURL RestAPI ,and 3rd case Invalid password.
It seems you are following the blog [1] and referring to ii) Update Password step.
IDN_RECOVERY_DATA is a table of the identity database where WSO2IS stores information about the recovery flow. But you don't have to worry about the data stored in the database.
If you are just trying to change the password of a user without sending an email, you can use SCIM APIs.
Following is an example to update the password of a user when the existing password is provided.
curl -X PATCH 'https://localhost:9443/scim2/Me' \
-H 'accept: application/scim+json' \
-H 'Content-Type: application/scim+json' \
-H 'Authorization: Basic {base64(username:currentPassword)}' \
-d '{ "schemas": [ "urn:ietf:params:scim:api:messages:2.0:PatchOp" ], "Operations": [ { "op": "replace", "value": { "password": "newPassword" } } ]}'
If you want to send an email and void WSO2 UIs for creating the new password, you can change the email template to redirect the user to your UI once the user clicks the link in the email. Then use the confirmation code included in that link to invoke the password set-password API. The document [2] has information on the APIs related to the account recovery, available in WSO2 Identity Server 5.11.0.
For locking or disabling a user, you can use the SCIM APIs to patch the relevant user attributes.
[1] https://medium.com/#isurakarunaratne/password-recovery-wso2-identity-server-b80abe2bcc61
[2] https://docs.wso2.com/display/IS511/apidocs/account-recovery/

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 do akka http request for oauth2 access_token

I am trying to request auth server to get access_token . I have a working curl command , but am unable to implement using Akka HTTP.
curl -v -u CLIENT_ID:CLIENT_SECRET -k -X POST -d {} 'URL/oauth2/token?grant_type=client_credentials&scope=Scope'
or
curl -i -H 'Authorization: Basic Base64(CLIENT_ID:CLIENT_SECRET)' --request POST URL/oauth2/token -d 'grant_type=client_credentials&scope=scope'
i am getting 405 Method Not Allowed error while requesting using http.singleRequest
def getToken(url:String, user: String, pass: String, scope:String) = {
Http()
.singleRequest(
Post(
Uri(url),
Map("grant_type" -> "client_credentials", "scope" -> s"$scope"),
).withHeaders(
Authorization(BasicHttpCredentials(user, pass)),
),
)
}
val request = HttpRequest(
HttpMethods.POST,
config.authDomain,
entity = FormData
.apply(
Map(
"grant_type" -> s"${config.grant_type}",
"scope" -> s"${config.api_scope}",
),
)
.toEntity,
).withHeaders(Authorization(BasicHttpCredentials(config.access_id, config.access_secret)))

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)

{"error":"invalid_token","error_description":""} (Podbean api)

I am trying to use Podbean api in my Django application. As per the document provided, I am authenticating my app. I have followed all the steps but when I try to run the following code in terminal I get error:
curl -u username:password \
https://api.podbean.com/v1/oauth/debugToken \
-G -d 'access_token=t4dfcgf7eb2ba65a289a6e8a8993cb9785e877y4'
Error:
{"error":"invalid_token","error_description":""}
I have checked all my credentials and they are correct. What is the problem here?
Finally found out the mistake:
client_id = App ID
client_secert = App Secret
I was writing 'username' and 'password' for 'client_id' and 'client_secret'