connecting to my app on kinvey using rest - python-2.7

I am trying to connect to my app on kinvey. From a browser, I can simply use:
https://baas.kinvey.com/appdata/<app_key>?app_secret=<secret>
I do get prompted to enter app_key and app_secret as uid and password but at least I get:
{
version: "3.8.13",
kinvey: "hello <my app name>",
appName: "<My app name>",
environmentName: "Development"
}
but, from python, I cannot. The closest I got was with:
requests.get('https://baas.kinvey.com/', headers={'app_key': app_key, 'app_secret': secret})
That takes me to a generic kinvey 'hello' but not to my app.
I also tried with
requests.get('https://baas.kinvey.com/' + app_key, headers={'app_key': app_key, 'app_secret': secret})
If i try to add the app_key + '?app_secret=' + secret to the url I get an error on malformed header/missing credentials.
Thoughts?

The correct way to add credentials to a Kinvey mbaas request is by setting a Basic Auth header, as explained here. Using the headers that you describe is not supported.
The steps here are that you use a base64-encoded appkey/appsecret to build a Basic Auth header in order to get to the "login" endpoints, after which you'll get a Kinvey token for the session authentication corresponding to the active user. There is no such thing as anonymous access to your app, apart from getting to the login endpoint.
Basically, this is not trivial. This is why using the REST API directly is not recommended, and using a specific SDK for your platform is. There's SDK's for many platforms including java/android, javascript, C#/xamarin, xcode/swift, etc. In those SDK's, you simply call functions like "Kinvey.login" or "Kinvey.appdata.get" and all auth and all offline, caching, etc. is taken care for you.

Related

Using Postman to access Google Indexing APIs

I would like to test Google Indexing API with Postman.
I have already configured the api correctly on https://console.cloud.google.com/ for using it on a wordpress site with the plugin Instant indexing and everything works ok.
Now I simply want to do a POST call with Postman, in particular I did not found anything clear about the type of authentication (Oauth 2) to use for the call.
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"method": "google.indexing.v3.UrlService.PublishUrlNotification",
"service": "indexing.googleapis.com"
}
}
]
}
}
Anyone can provide me an example? Thank you.
As stated in the comments, Google API's normally use OAuth2. Some exceptions might use an API key, but even then most of those still limit the data you can access with an API key versus what you can access using OAuth2
This particular API does indeed use OAuth2 as per the docs. This means you need an access token (as the error message states), so you will need to generate one.
Easiest would be to use a library for one of the many programming languages, as per the docs here.
I'll give a simple example in python as that is my preferred language. The following code uses the google-auth library (docs). It's the base library to deal with credential objects. You will need to download the JSON representation for the service account you created. See the relevant docs. Note that you should handle this file as if it were a password, same as with the access token itself, although the access token has a default lifetime of 3600 seconds, AKA 1h.
If you get an error message that the token is expired, create a new one. Read up on refresh tokens for that, but that's beyond the scope of this question.
Code was tested on a virtualenv for python 3.10
requirements.txt
google-auth
requests
main.py
from google.oauth2 import service_account
import google.auth.transport.requests
# create credentials object
creds= service_account.Credentials.from_service_account_file("/path/to/serviceaccount.json")
# we need a scoped credentials object as per
# https://developers.google.com/search/apis/indexing-api/v3/prereqs#requirements
scoped_creds = creds.with_scopes(['https://www.googleapis.com/auth/indexing'])
# create a request object for the refresh method
request = google.auth.transport.requests.Request()
# make the library do it's magic and get a token
scoped_creds.refresh(request)
print(scoped_creds.token)
This will print out an access token. (if it prints with dots (....) at the end, remove them.
Another easy option would be to (ab)use the gcloud command line tool. There's a couple of steps to this to get to work. You can use the cloud shell as an easy way to do this.
Download or copy the serviceaccount JSON file I mentioned above.
Activate the serviceaccount in gcloud using:
gcloud auth activate-service-account SERVICE_ACCOUNT#DOMAIN.COM --key-file=/path/key.json
Print the access token with this command:
gcloud auth print-access-token
The hard and masochistic way would be to use something like CURL or HTTPS requests manually to generate the token. Feel free to do so, but I'm just going to point you to the docs for that. It's a bit of a pain in the posterior.
You can test the token as explained in this answer.
Now that you have the access token, you can use it in POSTMAN by setting it in the header for the call. See this nice answer, but basically add the following request header key/value pair, replacing TOKEN with the generated token.
KEY: Authorization
VALUE: Bearer TOKEN
For anyone interested I managed to make it work by following these steps:
To obtain the authentication token with Postman first go to https://console.cloud.google.com/apis/credentials and in your web application ID client set https://oauth.pstmn.io/v1/callback as Authorized redirect URIs
Now in Postman Application in Authorization tab select OAuth 2.0 and configure the fields according to your client_secret.json (image)
Now click on 'Get new access Token' and you should get it
Specify the url and type as raw json body (image)

MS Graph API - Get Access Token w/ Multi-Factor Authentication Required

I'm attempting to use Postman to "Get User Access Token" with Microsoft Graph API; however, my org recently enabled multi-factor auth and this call is now failing, stating:
"error": "invalid_grant",
"error_description": "AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access...
 
The Microsoft documentation for MS Graph API using Postman is very well written, but it is missing clear instructions how to pass in this second factor to the request.
The error points to https://login.microsoftonline.com/error?code=50076, but this just gives the same info.
I have the MS authenticator app which gives me this key/second factor; however, I don't know how to add this into the body/headers. I'm trying to find the specific key name for passing in the additional security token (I've tried things like 'token,' 'pcToken,' 'key,' etc.)
.
I was in the same predicament so here is what I did to solve it:
Firstly, I got the information from:
https://github.com/microsoftgraph/microsoftgraph-postman-collections/issues/4
You will need to use the OAuth 2.0 authorisation in Postman. Using the same GET request, go to Authorization -> Change the type to 'OAuth 2.0' then click 'Get New Access Token'.
From there, you can input your own details:
(replace [TenantID] with your own)
Callback URL: The redirect URL you stated in your app authentication.
Auth URL:
https://login.microsoftonline.com/[TenantID]/oauth2/v2.0/authorize
Access Token URL: https://login.microsoftonline.com/[TenantID]/oauth2/v2.0/token
Client ID: You're application's ID.
Client Secret: You're Applications secret that you set under the 'Certificates & secrets' section.
Screenshot
Username Password Authentication is not supported for MFA because MFA requires interaction. But there is no interaction if you need to use Username Password Authentication to sign in.
See Username Password Authentication:
users who need to do MFA won't be able to sign-in (as there is no
interaction)
The answers above do not describe anything related to MFA by-passing via code.
MFA auth you need to use broker authentication where MS Authenticator app behaves as a broker.
If you integrate the proper libraries (ADAL, MSAL) your code will be able to interact with broker properly.
On Android and iOS, brokers enable:
Single Sign On (SSO). Your users won't need to sign-in to each
application
Device identification (by accessing the device
certificate which was created on the device when it was workplace
joined). We use Intune-managed devices for this purpose.
Application identification verification (is it really outlook which
calls me?). The way it works is when an application calls the broker,
it passes its redirect url, and the broker verifies it:
On iOS, the redirect URL is, for instance, ms-word://com.msft.com, the broker
parses and gets the appId (after the //) and verifies it's the same
as the appId of the calling app, which it knows (by the OS).
On Android the redirect URLs have the following form msauth://com.msft.word/.
To enable one of these features, the application developers need to set the UseBroker Boolean to true in the platform parameters. They also need to implement a delegate to react to the broker calling back the application as described in Platform parameters properties specific to brokers on Android and iOS.
Please refer to the MS docs for broker auth examples:
https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/leveraging-brokers-on-Android-and-iOS
https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-use-brokers-with-xamarin-apps
https://learn.microsoft.com/en-us/azure/active-directory/develop/brokered-auth

Credentials aren't allowed error when using Outlook REST API Oauth2 in AWS server

I'm trying to implement Outlook Oauth2 in our Django backend server which is hosted on an AWS instance.
I carefully followed the instructions in their python tutorial and it works 100% in my local machine. I am able to grab the authorization code which I then convert in my backend server to an access token.
The problem lies in our demo server which is an AWS instance. We have a button that redirects the users to Outlook authentication. The URL has the following format:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=<client-ID-here>&redirect_uri=<demo-server-redirect-url>&response_type=code&scope=openid+profile+offline_access+Calendars.ReadWrite&prompt=consent
I am receiving the following error whenever I convert the authorization code into an access token just after the consent screen:
{
'error': 'access_denied',
'error_description': 'Your credentials aren't allowed'
}
The weird thing is that if I use POSTMAN using the demo server Outlook credentials, I am able to retrieve an access token from Outlook.
Basically, it works for both in my local machine and using Postman. I really think that I'm just missing a very small piece of code/configuration here. Are there some extra settings that I need to do in order to make Outlook Oauth2 work in AWS?
We were able to fix the bug by adding User.Read into the scopes. Apparently, that's the only thing missing from all of this.

How to authenticate with third party system using RestAssured

I'm trying to hit a web service using RestAssured. I'm struggling with authentication which is actually performed by a third party system. Details are given below:
My web service requires session ID & Cookie in the request header. Otherwise the service call will be failed.
For that I need to fetch Session Id & Cookie after the authentication.
Authentication is done by third party service and it takes the windows credentials for authentication.
When I launch my app URL on browser, say: 'XYZ.com/dim' it will be redirected to authentication service using a URL like:
http://hantweb.DOMAIN.com/authenticate/encdefault.asp?location=XYZ.com/dim
After the authentication it will again be redirected to actual application back.
I tried below code but it says: "401 - Unauthorized: Access is denied due to invalid credentials." even though my credentials are correct.
RestAssured.given().auth().basic("userID", "password").get("http://hantweb.DOMAIN.com/authenticate/encdefault.asp?location=XYZ.com/dim")
I'm confused no idea what I've missed here..
I did some trial and error and finally understood that I need to use .auth().ntlm(userId, password,"","") as the authentication. Here I'm using windows credentials as basic or any other auth type won't work in this case.
This answer can help someone in need.

Generate an OAuth2 token in a view

Let's say I have an AngularJS application that consumes the REST API of a Django application.
The Django application has got a built-in OAuth2 provider that can be called to retrieve an access token and use the protected endpoints of the API. This provider is using django-oauth-toolkit.
Let's assume there is a registered client with "password" grant type, so that the end users only need to provide their credentials in the front-end in order to get an access token from the back-end.
At some point we want to add some support for social networks login and we decide to use python-social-auth (PSA) to that end. Here is the workflow I want to achieve:
The user logs in on Facebook from the front-end (via the Facebook SDK) and we get an access token back from the OAuth2 provider of Facebook.
We send the Facebook token to an endpoint of our REST API. This endpoint uses the Facebook token and django-social-auth to authenticate the user in our Django application (basically matching a Facebook account to a standard account within the app).
If the authentication succeeds, the API endpoint requests an access token from the OAuth2 provider for this newly authenticated user.
The Django access token is sent back to the front-end and can be used to access the REST API in exactly the same way that a regular user (i.e. logged in with his credentials) would do.
Now my problem is: how do I achieve step 3? I first thought I would register a separate OAuth2 client with Client Credentials Grant but then the generated token is not user-specific so it does not make sense. Another option is to use the TokenAuthentication from DRF but that would add too much complexity to my project. I already have an OAuth server and I don't want to set up a second token provider to circumvent my problem, unless this is the only solution.
I think my understanding of PSA and django-oauth-toolkit is not deep enough to find the best way of reaching my goal, but there must be a way. Help!
I managed to get something working using urllib2. I can't speak towards whether or not this is good practice, but I can successfully generate an OAuth2 token within a view.
Normally when I'd generate an access token with cURL, it'd look like this:
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
So we're tasked with making urllib2 accomplish this. After playing around for some bit, it is fairly straightforward.
import urllib, urlib2, base64, json
# Housekeeping
token_url = 'http://localhost:8000/auth/token/'
data = urllib.urlencode({'grant_type':'password', 'username':<username>, 'password':<password>})
authentication = base64.b64encode('%s:%s' % (<client_id>, <client_secret>))
# Down to Business
request = urllib2.Request(token_url, data)
request.add_header("Authorization", "Basic %s" % authentication)
access_credentials = urllib2.urlopen(request)
json_credentials = json.load(access_credentials)
I reiterate, I do not know if this is in bad practice and I have not looked into whether or not this causes any issues with Django. AFAIK this will do this trick (as it did for me).