O365 Authorization Code Grant Flow URL not loading - python

I'm trying to use the O365 pypl python library to receive a new auth token after changing my microsoft password. The authentication flow looks like this:
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
# the default authentication method will be "on behalf of a user"
account = Account(credentials)
if account.authenticate(scopes=['basic', 'message_all']):
print('Authenticated!')
I receive a message saying to visit the following URL to give consent. However, when I paste the URL, I am asked to login to microsoft and then nothing happens i.e. no permissions or consent page appears. My organization recently switched to Single Sign On so I'm wondering if this could potentially be causing the issue or if anyone else has experienced this? I'm new to this and very lost so any help is greatly appreciated! Thanks so much!!

To receive auth token, please check the following:
Register your application at Microsoft Application Registration Portal.
Login to the portal to get the access token.
To consent the application in order to access the resources first get the authorization URL like below:
url = account.connection.get_authorization_url()
Visit the above URL and grant consent for the application.
To perform authentication, create Account instance and authenticate using the authenticate method.
from pyo365 import Account
account = Account(credentials=('client_id', 'client_secret'))
result = account.authenticate(scopes=['basic', 'message_all'])
After requesting a token, app consent screen will appear where you have to give consent.
The user have to provide the result url after consent.
Token will be stored in the default location if all goes as expected.
For more information in detail, please refer below links:
https://github.com/janscas/pyo365#authentication
Question about get_authorization_url · Issue #13 · janscas/pyo365 · GitHub

Related

Get an Azure Active Directory token as a user

I want to be able getting access token while I act as a user (meaning I only have username and password).
In all the relevant topics I only see that they try getting the token as administrator of the application (for example, in order to know the clientId), but can I do the same while acting as the user of the application?
As suggested by #Thomas, you can make use of ROPC flow.
In order to get access token as a user, you still need to know values of client_id and tenant_id along with your UPN and password.
Client_Id - Your Application ID
Tenant_Id - Your Directory ID
You can get these values from the person who registered the application by:
Go to Azure Portal -> Azure Active Directory -> Your Application -> Overview
After getting those values, make use of Postman to generate the access token.
For that, POST an HTTP request like below that need tenant_id and parameters like below:
https://login.microsoftonline.com/your_tenant_id/oauth2/v2.0/token
In Postman, Go to Authorization tab and select type as Oauth2.0
Visit Headers tab and include Content-Type key with value as application/x-www-form-urlencoded
In Body tab, include parameters like client_id, grant_type, username, password and scope as below:
Make sure to grant admin consent to required API permissions defined in scope before sending the request.
Now, send the request and you can get the access token successfully like below:
To know more in detail, please refer below links:
Sign in with resource owner password credentials grant - Microsoft identity platform | Microsoft Docs
Azure registered app error: The user or administrator has not consented to use the application with ID - Stack Overflow

Python OAuth2 server with social networks for a RESTfull API

I'm trying to implement OAuth2 server for a RESTfull API with a login option through social platforms (Github, Facebook, Instagram) using Python and Falcon web framework.
But I've struggled to understand how this thing should work.
My current understanding led me to the following scheme:
1.1. On the API side, I'm creating an endpoint /auth/login/github which basically will tell the mobile app to redirect the client to the Github.com authorization page - github.com/login/oauth/authorize
1.2. On the Github authorization page user will be presented with the following screen:
1.3. After pressing Authorize user will be taken to the page specified in the callback parameter (Github OAuth service configuration) with the newly granted temporary authorization code. In my case URL will look like: my.api.com/auth/callback/github?code=AUTH_CODE
2.1. After receiving a callback request, I'm parsing/extracting passed Authorization Code and query Github.com from the backend in order to redeem Authorization Code and get Access Token (sending POST request using my Client ID and Client Secret to github.com/login/oauth/access_token)
2.2. If everything was successful Github will reply to my POST request with the Access Token, which I can use to get user profile details (e.g. e-mail)
3.1. Now that I know that authorization through the Github was successful (because I got users' email) I can grant my own Access Token to that user, so he can query my API endpoints. I do this just by adding randomly generating OAuth2 Token and inserting it into my database, simultaneously returning same token to the user by redirecting him to the mobile app using deep links (e.g.: myapp://token).
3.2. Finally mobile app can query my API endpoints by adding the following header to each request Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
Does that make sense and is this the correct way of doing the social authorization for RESTfull API's?
I'm using Falcon as the web framework for this project and Authlib as the OAuth2 library.
Its one way for sure. And it looks alright.
I'm going to make it simpler, and maybe its a bit clear whats happening.
1.1 [Mobile APP] redirects user to github.com/oauth/authorize?client_id=CLIENT_ID with the client id you registered with github
1.2 [Mobile APP] user comes via a redirect to fancy.app/callback/github?code=AUTH_CODE (this is the callback url you configure on github)
1.2.1 [Mobile APP] call your API endpoint with the AUTH_CODE
1.3 [API] confirm with github the AUTH_CODE is valid.
Up to this point we have user authentication; the user isn't a random guy, is user xxx on github.com and you have the information you requested.
Now, if you need to authorise this user on your API, after 1.3:
1.3.1 [API] generate a token
1.3.2 [API] store the token in some persistent storage
1.3.3 [API] define some expiration time for the token (actually the AUTH_CODE from github should have some expiration, use that)
1.3.4 [API] return the token to the mobile APP
This token we've generated is what the Mobile APP will use to authenticate the user on the API; no further calls to github (until expiration at least).
1.1. On the API side, I'm creating an endpoint /auth/login/github which basically will tell the mobile app to redirect the client to the Github.com authorization page - github.com/login/oauth/authorize
Instead of hard coding /auth/login/github, how about making it a query parameter on your API so that you can quickly integrate separate OAuth2 providers (Google, Facebook, etc.)
Your endpoint URL would now look like /auth/login/?provider=github and your backend can provide the correct redirect url for the mobile app to go to. This means you can simply add new buttons for Facebook /auth/login/?provider=facebook and it would be minimal work.
When you receive the callback request, the URL may then look something like my.api.com/auth/callback/?provider=github&code=AUTH_CODE. You may also want to insert a new user record to your own database (if you have one), so you can prompt for extra info if required, I would do this in Django for example, since I require extra info on top of the data that is provided by third-party OAuth2 providers.
Overall, the approach looks sound.

Django server RW access to self owned google calendar?

In a django application, I try to have RW access to a google calendar which I own myself.
Tried several ways with a service account & client secrets, but all resulting in authentication errors.
The API explorer works, but it requests consent in a popup window, which is obviously not acceptable.
Documentation on google OAuth2 describes several scenarios. Probably "web server application" applies here? It says:
"The authorization sequence begins when your application redirects a
browser to a Google URL; the URL includes query parameters that
indicate the type of access being requested. Google handles the user
authentication, session selection, and user consent. The result is an
authorization code, which the application can exchange for an access
token and a refresh token."
Again, we do not want a browser redirection, we want direct access to the google calendar.
So question is: how can a django server access a google calendar, on which I have full rights, view events and add events using a simple server stored key or similar mechanism?
With help of DalmTo and this great article, I got RW access to a google calendar working from python code. I will summarize the solution here.
Here are the steps:
First of all register for a google service account: Service accounts are pre-authorized accounts that avoid you need to get consent or refresh keys every time:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
(The part on G-suite can be ignored)
Download the service account credentials and store them safely. Your python code will need access to this file.
Go to your google calendar you want to get access to.
e.g. https://calendar.google.com/calendar/r/month
On the right side you see your calendars. Create an additional one for testing (since we'll write to it soon). Then point to this new calendar: click the 3 dots next to it and edit the sharing settings. Add the service account email address to the share under "share with specific people". (you can find the service account email address in the file downloaded previously under "client_email")
In the same screen, note the "calendar ID", you'll need it in below code.
Now you service account has the RW rights to the calendar.
Add at least one event to the calendar using the web UI (https://calendar.google.com/calendar/r/month) so we can read and change it from below code.
Then use following python code to read the calendar and change an event.
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = '<path to your service account file>'
CAL_ID = '<your calendar ID>'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials)
events_result = service.events().list(calendarId=CAL_ID).execute()
events = events_result.get('items', [])
event_id = events[0]['id']
event = events[0]
service.events().update(calendarId=CAL_ID, eventId=event_id, body={"end":{"date":"2018-03-25"},"start":{"date":"2018-03-25"},"summary":"Kilroy was here"}).execute()
And there you go... read an event and updated the event.

Google Apps customized google login page in appspot

I have an appspot application in python.
Requirement:
Custom login screen in application where Google users can Signin. Setting up appropriate sessions so that even if user tries to open Google Mail or any authenticated Google site it should open directly without asking username and password.
I dont want to redirect them to Google login page.
Things that I've tried so far :
1st Approach
1) Using ClientLogin, validate username and password in py
- Get Auth token
- Using Auth token retrieve Cookies
- Redirect to secured appspot url by setting up the Cookies.
Now this should ideally take me to the secured url of appspot application. But its showing the Google Login page.
Source code : [http://pastebin.com/wfZ8eDGM][1] [http://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-py][2]
2nd Approach
1) Plainly copied the html source from Google Login page and paste it in login.html as described here http://stackoverflow.com/questions/13815084/custom-google-apps-login-page/13815342#13815342
2) Upon clicking login button, its showing "Oops! Your browser seems to have cookies disabled. Make sure cookies are enabled or try opening a new browser window. ". But cookies are enabled in broswer.
Source code: [http://pastebin.com/N7thPc3u][3]
Is there anything that I am missing ? or Is there any other approach for doing this ?
For hosted google applications, you could use SAML (Google is the SP, and your service can act as the IDP)
https://developers.google.com/google-apps/sso/saml_reference_implementation

How to write a post to my facebook app's wall from app engine using python?

I have an app engine web app that would like to automatically write a post to the wall of a facebook application I control (i.e. every time a particular event occurs on the website I would like to update the wall of my facebook application).
This code will be called from a deferred task on the server.
I have been unable to find anything addressing this. Your help would be appreciated.
First thing I did was get my access token with the following code:
https://graph.facebook.com/oauth/access_token?client_id=FACEBOOK_APP_ID&client_secret=FACEBOOK_APP_SECRET&grant_type=client_credentials&scope=manage_pages,offline_access
Using the returned access token this is what I'm running on the server:
form_fields = {
"access_token": FACEBOOK_ACCESS_TOKEN,
"message": tgText
};
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url="https://graph.facebook.com/MYAPP_FACEBOOK_ID/feed",
payload=form_data,
method=urlfetch.POST,
validate_certificate=False,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
But calling this results in:
{"error":{"type":"OAuthException","message":"(#200) The user hasn't authorized the application to perform this action"}}
As an administrator you can grant access to third party apps (e.g. your python app) to post onto your App's Profile Page (http://www.facebook.com/apps/application.php?id=YOUR_APP_ID) using OAuth:
http://developers.facebook.com/docs/authentication/ (Section Page Login)
Once you received an access token you should be able to post to App Profile Page as described here:
http://developers.facebook.com/docs/reference/api/post/ (Section Publishing)
I have a similar app. Facebook can change the code that you're meant to submit as part of the process for gaining an access token. I wrote a simple web page that creates a form with hidden input fields that contain the data required to get Facebook to authorise an app with a user (see http://developers.facebook.com/docs/reference/dialogs/oauth/).
When the user clicks the submit button, the browser does an HTTP GET to Facebook, with an appropriate query string, where the Facebook user is prompted to login (if needed) and authorise the app. If authorised Facebook calls back your redirect_url with the code which you can store in the DataStore to retrieve when needed as part of the "give me an access token" flow.

Categories

Resources