Skip to content

Commit

Permalink
Code flow authentication for persistent session. Addresses #2
Browse files Browse the repository at this point in the history
- Add .githubattributes file to recognize .ipynb files as Python
  • Loading branch information
pranabdas committed Mar 11, 2022
1 parent 548a563 commit d4be988
Show file tree
Hide file tree
Showing 3 changed files with 281 additions and 15 deletions.
2 changes: 2 additions & 0 deletions .githubattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.ipynb linguist-language=Python

158 changes: 155 additions & 3 deletions OneDrive_Gaph_tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,19 @@
"import requests\n",
"import json\n",
"import urllib\n",
"import os"
"import os\n",
"from getpass import getpass\n",
"import time\n",
"from datetime import datetime"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get Access token"
"## Get Access token\n",
"\n",
"### Token flow authentication"
]
},
{
Expand Down Expand Up @@ -85,7 +90,154 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Looks all right. We have got the access token, and included in the HEADERS. You can print response to see more. "
"Looks all right. We have got the access token, and included in the HEADERS. You can print response to see more. Go ahead with OneDrive operations."
]
},
{
"source": [
"### Code flow authentication\n",
"\n",
"Code flow returns both `access_token` and `refresh_token` which can be used to\n",
"request new `access_token` and `refresh_token` for persistent session. If you \n",
"are using organization account, you might require consent of organization administrator. \n"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get code\n",
"URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'\n",
"client_id = \"362422eb-d9d6-4245-9eca-2be5cf256450\"\n",
"permissions = ['offline_access', 'files.readwrite', 'User.Read']\n",
"response_type = 'code'\n",
"redirect_uri = 'http://localhost:8080/'\n",
"scope = ''\n",
"for items in range(len(permissions)):\n",
" scope = scope + permissions[items]\n",
" if items < len(permissions)-1:\n",
" scope = scope + '+'\n",
"\n",
"print('Click over this link ' +URL + '?client_id=' + client_id + '&scope=' + scope + '&response_type=' + response_type+\\\n",
" '&redirect_uri=' + urllib.parse.quote(redirect_uri))\n",
"print('Sign in to your account, copy the whole redirected URL.')\n",
"code = getpass(\"Paste the URL here :\")\n",
"code = code[(code.find('?code') + len('?code') + 1) :]\n",
"\n",
"URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'\n",
"\n",
"response = requests.post(URL + '?client_id=' + client_id + '&scope=' + scope + '&grant_type=authorization_code' +\\\n",
" '&redirect_uri=' + urllib.parse.quote(redirect_uri)+ '&code=' + code)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get token\n",
"data = {\n",
" \"client_id\": client_id,\n",
" \"scope\": permissions,\n",
" \"code\": code,\n",
" \"redirect_uri\": redirect_uri,\n",
" \"grant_type\": 'authorization_code',\n",
" \"client_secret\": client_secret\n",
"}\n",
"\n",
"response = requests.post(URL, data=data)\n",
"\n",
"token = json.loads(response.text)[\"access_token\"]\n",
"refresh_token = json.loads(response.text)[\"refresh_token\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Refresh token\n",
"def get_refresh_token():\n",
" data = {\n",
" \"client_id\": client_id,\n",
" \"scope\": permissions,\n",
" \"refresh_token\": refresh_token,\n",
" \"redirect_uri\": redirect_uri,\n",
" \"grant_type\": 'refresh_token',\n",
" \"client_secret\": 'xxxx-yyyy-zzzz',\n",
" }\n",
"\n",
" response = requests.post(URL, data=data)\n",
"\n",
" token = json.loads(response.text)[\"access_token\"]\n",
" refresh_token = json.loads(response.text)[\"refresh_token\"]\n",
" last_updated = time.mktime(datetime.today().timetuple())\n",
"\n",
" return token, refresh_token, last_updated"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"token, refresh_token, last_updated = get_refresh_token()"
]
},
{
"source": [
"If you have a large data to upload, you may use below mock code inside your upload loop:\n",
"\n",
"```python\n",
"elapsed_time = time.mktime(datetime.today().timetuple()) - last_updated\n",
"\n",
"if (elapsed_time < 45*60*60):\n",
" do_something()\n",
"else if (elapsed_time < 59*60*60):\n",
" token, refresh_token, last_updated = get_refresh_token()\n",
"else:\n",
" go_to_code_flow()\n",
"```"
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"## OneDrive operations"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"URL = 'https://graph.microsoft.com/v1.0/'\n",
"\n",
"HEADERS = {'Authorization': 'Bearer ' + token}\n",
"\n",
"response = requests.get(URL + 'me/drive/', headers = HEADERS)\n",
"if (response.status_code == 200):\n",
" response = json.loads(response.text)\n",
" print('Connected to the OneDrive of', response['owner']['user']['displayName']+' (',response['driveType']+' ).', \\\n",
" '\\nConnection valid for one hour. Refresh token if required.')\n",
"elif (response.status_code == 401):\n",
" response = json.loads(response.text)\n",
" print('API Error! : ', response['error']['code'],\\\n",
" '\\nSee response for more details.')\n",
"else:\n",
" response = json.loads(response.text)\n",
" print('Unknown error! See response for more details.')"
]
},
{
Expand Down
Loading

0 comments on commit d4be988

Please sign in to comment.