├── seamless
├── oauth
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── admin.py
│ ├── tests.py
│ ├── Templates
│ │ └── oauth
│ │ │ ├── step1.html
│ │ │ ├── step2.html
│ │ │ └── index.html
│ ├── urls.py
│ └── views.py
├── seamless
│ ├── __init__.py
│ ├── urls.py
│ ├── wsgi.py
│ └── settings.py
├── db.sqlite3
└── manage.py
├── djangoSite
├── aadrest
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── admin.py
│ ├── tests.py
│ ├── Templates
│ │ └── aadrest
│ │ │ ├── step5.html
│ │ │ ├── step5_live.html
│ │ │ ├── index.html
│ │ │ ├── step4_live.html
│ │ │ ├── step3.html
│ │ │ ├── step2.html
│ │ │ ├── step2_live.html
│ │ │ ├── step3_live.html
│ │ │ ├── step4.html
│ │ │ ├── step1.html
│ │ │ └── step1_live.html
│ ├── urls.py
│ ├── oauth.py
│ └── views.py
├── djangoSite
│ ├── __init__.py
│ ├── urls.py
│ ├── wsgi.py
│ └── settings.py
├── db.sqlite3
├── response.html
└── manage.py
├── .gitignore
├── README.md
└── LICENSE
/seamless/oauth/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/djangoSite/djangoSite/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/seamless/seamless/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/seamless/oauth/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/seamless/oauth/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
--------------------------------------------------------------------------------
/seamless/oauth/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/seamless/oauth/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/seamless/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sebastus/azure-python-authenticate/HEAD/seamless/db.sqlite3
--------------------------------------------------------------------------------
/djangoSite/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sebastus/azure-python-authenticate/HEAD/djangoSite/db.sqlite3
--------------------------------------------------------------------------------
/djangoSite/response.html:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sebastus/azure-python-authenticate/HEAD/djangoSite/response.html
--------------------------------------------------------------------------------
/seamless/oauth/Templates/oauth/step1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process (Seamless Step 1)
4 |
5 |
6 |
--------------------------------------------------------------------------------
/seamless/oauth/Templates/oauth/step2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process (Seamless Step 2)
4 |
5 | {{subscriptions}}
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step5.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Organizational Account
4 | Results
5 |
6 | Here's the token you wanted.
7 |
8 | {{token}}
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step5_live.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Microsoft Account
4 | Results
5 |
6 | Here's the token you wanted.
7 |
8 | {{token}}
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/seamless/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "seamless.settings")
7 |
8 | from django.core.management import execute_from_command_line
9 |
10 | execute_from_command_line(sys.argv)
11 |
--------------------------------------------------------------------------------
/seamless/oauth/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import patterns, include, url
2 | from django.contrib import admin
3 |
4 | urlpatterns = patterns('',
5 | url(r'^$', 'oauth.views.index', name='index'),
6 | url(r'^step1/$', 'oauth.views.step1', name='step1'),
7 | url(r'^step2/$', 'oauth.views.step2', name='step2'),
8 | )
--------------------------------------------------------------------------------
/djangoSite/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoSite.settings")
7 |
8 | from django.core.management import execute_from_command_line
9 |
10 | execute_from_command_line(sys.argv)
11 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process
4 |
5 | Using Organizational ID (@xxx.OnMicrosoft.com)
6 |
7 | Using Microsoft Account ID (@hotmail.com, @live.com, etc)
8 |
9 |
10 |
--------------------------------------------------------------------------------
/seamless/oauth/Templates/oauth/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process (Seamless)
4 |
5 | Using Organizational ID (@xxx.OnMicrosoft.com)
6 |
7 | Using Microsoft Account ID (@hotmail.com, @live.com, etc)
8 |
9 |
10 |
--------------------------------------------------------------------------------
/seamless/seamless/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import patterns, include, url
2 | from django.contrib import admin
3 |
4 | urlpatterns = patterns('',
5 | # Examples:
6 | # url(r'^$', 'seamless.views.home', name='home'),
7 | # url(r'^blog/', include('blog.urls')),
8 |
9 | url(r'^oauth/', include('oauth.urls')),
10 | url(r'^admin/', include(admin.site.urls)),
11 | )
12 |
--------------------------------------------------------------------------------
/djangoSite/djangoSite/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import patterns, include, url
2 | from django.contrib import admin
3 |
4 | urlpatterns = patterns('',
5 | # Examples:
6 | # url(r'^$', 'djangoSite.views.home', name='home'),
7 | # url(r'^blog/', include('blog.urls')),
8 |
9 | url(r'^aadrest/', include('aadrest.urls')),
10 | url(r'^admin/', include(admin.site.urls)),
11 | )
12 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step4_live.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Microsoft Account
4 | Step 4
5 |
6 | Here are the names of the subscriptions that were returned in Step 3. Following each subscription is the Tenant ID of the Azure AD tenant associated with it. There could be only one or several.
7 |
8 | {{subscriptions}}
9 |
10 | That's it!
11 |
12 |
13 |
--------------------------------------------------------------------------------
/seamless/seamless/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for seamless project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "seamless.settings")
12 |
13 | from django.core.wsgi import get_wsgi_application
14 | application = get_wsgi_application()
15 |
--------------------------------------------------------------------------------
/djangoSite/djangoSite/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for djangoSite project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoSite.settings")
12 |
13 | from django.core.wsgi import get_wsgi_application
14 | application = get_wsgi_application()
15 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step3.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Organizational Account
4 | Step 3
5 |
6 | Here's the access token that was returned in Step 2:
7 | {{token}}
8 |
9 | In this step, we'll use it to acquire a list of subscriptions that this ID has access to. This list is returned by the List Azure Subscriptions API.
10 |
11 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Organizational Account
4 | Step 2
5 |
6 | Here's the code returned in the previous step:
7 | {{aad_code}}
8 |
9 | In this step, we'll use it to acquire an access token with rights to execute methods in the Azure Service Management API. This access token comes from Azure AD by issuing a request to the token endpoint: https://login.windows.net/common/oauth2/token.
10 |
11 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import patterns, include, url
2 | from django.contrib import admin
3 |
4 | urlpatterns = patterns('',
5 | url(r'^$', 'aadrest.views.index', name='index'),
6 | url(r'^step1/$', 'aadrest.views.step1', name='step1'),
7 | url(r'^step2/$', 'aadrest.views.step2', name='step2'),
8 | url(r'^step3/$', 'aadrest.views.step3', name='step3'),
9 | url(r'^step4/$', 'aadrest.views.step4', name='step4'),
10 | url(r'^step1_live/$', 'aadrest.views.step1_live', name='step1_live'),
11 | url(r'^step2_live/$', 'aadrest.views.step2_live', name='step2_live'),
12 | url(r'^step3_live/$', 'aadrest.views.step3_live', name='step3_live'),
13 | url(r'^step4_live/$', 'aadrest.views.step4_live', name='step4_live'),
14 | )
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step2_live.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Microsoft Account
4 | Step 2
5 |
6 | Here's the code returned in the previous step:
7 | {{aad_code}}
8 |
9 | In this step, we'll use it to acquire an access token with rights to execute methods in the Azure Service Management API. This access token comes from Azure AD by issuing a request to the token endpoint: https://login.windows.net/**thatTenant**.onmicrosoft.com/oauth2/token.
10 |
11 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step3_live.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Microsoft Account
4 | Step 3
5 |
6 | The token returned in Step 2 is the one you need.
7 | Here's the access token:
8 | {{token}}
9 |
10 | In this step, we'll demonstrate using it to acquire a list of subscriptions that this Microsoft Account has access to. This list is returned by the List Azure Subscriptions API.
11 |
12 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step4.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Organizational Account
4 | Step 4
5 |
6 | Here are the names of the subscriptions that were returned in Step 3. Following each subscription is the Tenant ID of the Azure AD tenant associated with it. In my case I have two subscriptions associated with the same Azure AD tenant. With that tenant ID in hand, the required access token may be fetched from Azure AD through a process very similar to the one we just completed, this time using the tenant ID instead of Common.
7 |
8 | {{subscriptions}}
9 |
10 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # secrets
2 | AzureSubscriptions.xml
3 |
4 | # Byte-compiled / optimized / DLL files
5 | __pycache__/
6 | *.py[cod]
7 |
8 | # C extensions
9 | *.so
10 |
11 | # Distribution / packaging
12 | .Python
13 | env/
14 | build/
15 | develop-eggs/
16 | dist/
17 | downloads/
18 | eggs/
19 | lib/
20 | lib64/
21 | parts/
22 | sdist/
23 | var/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .cache
43 | nosetests.xml
44 | coverage.xml
45 |
46 | # Translations
47 | *.mo
48 | *.pot
49 |
50 | # Django stuff:
51 | *.log
52 |
53 | # Sphinx documentation
54 | docs/_build/
55 |
56 | # PyBuilder
57 | target/
58 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Organizational Account
4 | One of the key features of Azure AD is the simplicity of giving members of one tenant the rights to access the applications of another tenant. So, for example, a software company (Tenant A) can easily grant rights to its customer (Tenant B) to use one or more of its apps, as a guest. This is a classic example of multi-tenancy. But! According to the authentication steps outlined in this blog , the user's credentials are collected via a UI that is owned by Azure AD. You can't accept the credentials in your code and parse to determine which tenant is being accessed. Answer: the Common endpoint, as detailed in Vittorio Bertocci's blog.
5 |
6 | In this example, use an ID of the form user@tenant.onmicrosoft.com. To get started, a POST to https://login.windows.net/common/oauth2/authorize is performed. This redirects the user to the credentials UI and returns to the supplied Redirect_URI.
7 |
8 |
12 |
13 |
14 | {{output}}
15 |
16 |
17 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/Templates/aadrest/step1_live.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Multi-Tenant Azure AD REST AuthN Process - Microsoft Account
4 | One of the key features of Azure AD is the simplicity of giving members of one tenant the rights to access the applications of another tenant. So, for example, a software company (Tenant A) can easily grant rights to its customer (Tenant B) to use one or more of its apps, as a guest. This is a classic example of multi-tenancy. But! According to the authentication steps outlined in this blog , the user's credentials are collected via a UI that is owned by Microsoft Account / Live ID. Answer: in that same blog, Vittorio explains a couple of options. We'll implement option B - ask the user the name of his Azure AD tenant.
5 |
6 | In this example, use an ID of the form user@hotmail.com or some other Microsoft Account. To get started, the name of the Azure AD tenant is requested and a POST to https://login.windows.net/**thatTenant**.onmicrosoft.com/oauth2/authorize is performed. This redirects the user to the credentials UI and returns to the supplied Redirect_URI.
7 |
8 |
14 |
15 |
16 | {{output}}
17 |
18 |
19 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/oauth.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from requests_oauthlib import OAuth2, OAuth2Session
3 |
4 | class oauth_code:
5 | def __init__(self):
6 | self.url = ''
7 | self.status_code = ''
8 | self.history = ''
9 | self.authorization_response = ''
10 |
11 | self.client_id = '86cc9609-4c6e-41e8-b00b-8016aa9a1ef5'
12 | self.client_key = 'AkK47kyLNVCyn7n4llQpFqlY6QRJ67C/3RUsBCnWqxE='
13 | self.authorization_base_url = 'https://login.windows.net/common/oauth2/authorize'
14 | self.token_url = 'https://login.windows.net/common/oauth2/token'
15 | self.get_subscriptions_url = 'https://management.core.windows.net/subscriptions'
16 | self.x_ms_version = '2013-08-01'
17 | self.redirect_uri = 'http://localhost:8000/hello'
18 |
19 | self.azure_session = OAuth2Session(self.client_id, redirect_uri=self.redirect_uri, scope=['https://management.core.windows.net/subscriptions'])
20 |
21 | def do_common(self):
22 | # get the authorization url from the base url + creds
23 | authorization_url, state = self.azure_session.authorization_url(self.authorization_base_url)
24 | resp = requests.get(authorization_url)
25 |
26 | self.authorization_response = resp.url
27 | self.status_code = resp.status_code
28 | self.history = resp.history
29 |
30 | def get_subscriptions(self, token):
31 | header_dict = {'Authorization': 'Bearer ' + token}
32 | return requests.request('GET', self.get_subscriptions_url, headers = header_dict)
33 |
34 | def fetch_token(self, aad_code, auth_resp):
35 | print ('call fetch_token')
36 | token_dict = self.azure_session.fetch_token(self.token_url, client_secret=self.client_key, code=aad_code, authorization_response = auth_resp)
37 | print ('finished fetch_token')
38 | print (token_dict)
39 | return token_dict
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | azure-python-authenticate
2 | =========================
3 |
4 | Open source authentication sample for Microsoft Azure via Python/Django
5 | To run this sample to best effect, you'll need two subscriptions, each with a different associated directory. Otherwise, how would it be a demo of a multi-tenant app? I'll refer to the two tenants (directories) as TenantA and TenantB.
6 |
7 | To set up your environment to run this sample:
8 | 1. Create a web app inside your Azure AD tenant. (TenantA)
9 | * Capture the client id of that app.
10 | * If you don't have a record of the client key, create a new one and record it.
11 | * In the section at the bottom of the page "Windows Azure Service Management API", in the Delegated Permissions dropdown, check the box.
12 | * Add "http://localhost:8000/aadrest/step2/" to the list of acceptable Reply URL's.
13 | * Toggle to "yes" - Application is Multi-Tenant
14 | * Save the page.
15 |
16 | 2. Your dev box should have this directory structure after cloning the repo:
17 |
18 | azure-python-authenticate
19 | |_djangoSite
20 | |_djangoSite
21 | |_aadrest
22 | |_migrations
23 | |_Templates
24 | |_aadrest
25 |
26 | 3. Edit djangoSite\djangoSite\settings.py
27 | 1. client_id
28 | 2. client_key
29 | 3. redirect_uri - can usually be left alone, but if you change the port, make sure you edit Reply URL in the app definition page (above).
30 |
31 | To run the sample:
32 |
33 | 1. Start up the python dev web server environment. Docs on this are here:
34 | https://docs.djangoproject.com/en/dev/intro/tutorial01/
35 |
36 | Open a command prompt and navigate to: azure-python-authenticate\djangoSite.
37 | Enter the command: python manage.py runserver
38 |
39 | 2. Open a web browser. Navigate to: http://localhost:8000/aadrest
40 |
41 | 3. There are two pathways - Organizational Account or Microsoft Account. Pick one. Just follow the instructions on screen for each one.
42 |
43 | 4. When you click the button on the Step1 page, it will redirect you to the correct login page. Enter appropriate credentials.
44 |
45 | 5. (FYI) As part of the process, on the Azure AD pathway, Azure AD will present a permission request - asking if it's ok that the app from TenantA be listed in the apps list of TenantB. Click OK.
46 |
47 | 6. After authenticating, the app will display certain progress information as you click through the buttons on the pages.
48 |
49 | It is possible to run this demo with a single Azure AD tenant, if you don't happen to have access to two. There are no code changes.
50 |
51 |
--------------------------------------------------------------------------------
/seamless/seamless/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for seamless project.
3 |
4 | For more information on this file, see
5 | https://docs.djangoproject.com/en/1.7/topics/settings/
6 |
7 | For the full list of settings and their values, see
8 | https://docs.djangoproject.com/en/1.7/ref/settings/
9 | """
10 |
11 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
12 | import os
13 | BASE_DIR = os.path.dirname(os.path.dirname(__file__))
14 |
15 |
16 | # Quick-start development settings - unsuitable for production
17 | # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
18 |
19 | # SECURITY WARNING: keep the secret key used in production secret!
20 | SECRET_KEY = 'zixc1k$i$z17y&))$q7ta+(tb*8nt@e^vn5^dzrj*0-=l8oytj'
21 |
22 | # SECURITY WARNING: don't run with debug turned on in production!
23 | DEBUG = True
24 |
25 | TEMPLATE_DEBUG = True
26 |
27 | ALLOWED_HOSTS = []
28 |
29 |
30 | # Application definition
31 |
32 | INSTALLED_APPS = (
33 | 'django.contrib.admin',
34 | 'django.contrib.auth',
35 | 'django.contrib.contenttypes',
36 | 'django.contrib.sessions',
37 | 'django.contrib.messages',
38 | 'django.contrib.staticfiles',
39 | 'oauth',
40 | )
41 |
42 | MIDDLEWARE_CLASSES = (
43 | 'django.contrib.sessions.middleware.SessionMiddleware',
44 | 'django.middleware.common.CommonMiddleware',
45 | 'django.middleware.csrf.CsrfViewMiddleware',
46 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
47 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
48 | 'django.contrib.messages.middleware.MessageMiddleware',
49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
50 | )
51 |
52 | ROOT_URLCONF = 'seamless.urls'
53 |
54 | WSGI_APPLICATION = 'seamless.wsgi.application'
55 |
56 |
57 | # Database
58 | # https://docs.djangoproject.com/en/1.7/ref/settings/#databases
59 |
60 | DATABASES = {
61 | 'default': {
62 | 'ENGINE': 'django.db.backends.sqlite3',
63 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
64 | }
65 | }
66 |
67 | # my constants
68 | CONSTANTS = {
69 | 'CLIENT_ID': 'my app client id from azure ad',
70 | 'CLIENT_KEY': 'my app client key from azure ad',
71 | 'STEP_1_TEMPLATE_NAME': 'oauth/step1.html',
72 | 'STEP_2_TEMPLATE_NAME': 'oauth/step2.html',
73 | 'REDIRECT_URI': 'http://localhost:8000/oauth/step2/',
74 | 'AUTHORIZATION_BASE_URL': 'https://login.windows.net/%s/oauth2/authorize',
75 | 'BASE_TOKEN_URL': 'https://login.windows.net/%s/oauth2/token',
76 | 'RESOURCE_URI': 'https://management.core.windows.net/',
77 | 'GET_SUBSCRIPTIONS_URL': 'https://management.core.windows.net/subscriptions',
78 | 'MS_API_VERSION_HEADER': 'x-ms-version',
79 | 'MS_API_VERSION_HEADER_VALUE': '2013-08-01'
80 | }
81 |
82 | # Internationalization
83 | # https://docs.djangoproject.com/en/1.7/topics/i18n/
84 |
85 | LANGUAGE_CODE = 'en-us'
86 |
87 | TIME_ZONE = 'UTC'
88 |
89 | USE_I18N = True
90 |
91 | USE_L10N = True
92 |
93 | USE_TZ = True
94 |
95 |
96 | # Static files (CSS, JavaScript, Images)
97 | # https://docs.djangoproject.com/en/1.7/howto/static-files/
98 |
99 | STATIC_URL = '/static/'
100 |
--------------------------------------------------------------------------------
/seamless/oauth/views.py:
--------------------------------------------------------------------------------
1 | from xml.dom.minidom import parseString
2 | from django.shortcuts import render
3 | from requests_oauthlib import OAuth2Session
4 | from django.conf import settings
5 | import requests
6 | from django.shortcuts import render, redirect
7 |
8 | def getText(nodelist):
9 | rc = []
10 | for node in nodelist:
11 | if node.nodeType == node.TEXT_NODE:
12 | rc.append(node.data)
13 | return ''.join(rc)
14 |
15 | # Create your views here.
16 | def index(request):
17 | context = {'initialize':''}
18 | return render(request, 'oauth/index.html', context)
19 |
20 | def step1(request):
21 |
22 | # initialization
23 | constants = settings.CONSTANTS
24 | CLIENT_ID = constants['CLIENT_ID']
25 | STEP_1_TEMPLATE_NAME = constants['STEP_1_TEMPLATE_NAME']
26 | REDIRECT_URI = constants['REDIRECT_URI']
27 | AUTHORIZATION_BASE_URL = constants['AUTHORIZATION_BASE_URL']
28 |
29 | context = {'initialize':''}
30 |
31 | # GET as a result of initial invocation
32 | if request.method == 'GET':
33 |
34 | # create a 'requests' Oauth2Session
35 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
36 |
37 | # do the outreach to https://login.windows.net/common/oauth2/authorize
38 | authorization_url, state = azure_session.authorization_url(AUTHORIZATION_BASE_URL % 'common')
39 | resp = requests.get(authorization_url)
40 |
41 | # go to the login page of AAD & authenticate
42 | return redirect(resp.url)
43 |
44 | def step2(request):
45 |
46 | # initialization
47 | constants = settings.CONSTANTS
48 | STEP_2_TEMPLATE_NAME = constants['STEP_2_TEMPLATE_NAME']
49 | BASE_TOKEN_URL = constants['BASE_TOKEN_URL']
50 | REDIRECT_URI = constants['REDIRECT_URI']
51 | CLIENT_ID = constants['CLIENT_ID']
52 | CLIENT_KEY = constants['CLIENT_KEY']
53 | RESOURCE_URI = constants['RESOURCE_URI']
54 | GET_SUBSCRIPTIONS_URL = constants['GET_SUBSCRIPTIONS_URL']
55 | MS_API_VERSION_HEADER = constants['MS_API_VERSION_HEADER']
56 | MS_API_VERSION_HEADER_VALUE = constants['MS_API_VERSION_HEADER_VALUE']
57 |
58 | context = {'initialize':''}
59 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
60 |
61 | if request.method == 'GET':
62 |
63 | # get the code returned by AAD
64 | aad_code = request.GET.get('code','')
65 |
66 | # OAUTH STEP 2 - go fetch the token
67 | token_dict = azure_session.fetch_token(BASE_TOKEN_URL % 'common', code=aad_code, client_secret=CLIENT_KEY, resource=RESOURCE_URI)
68 |
69 | # OAUTH STEP 3 - go get the subscriptions (or whatever service management API you want to call - this is just a sample)
70 | resp = azure_session.get(GET_SUBSCRIPTIONS_URL, headers = {MS_API_VERSION_HEADER: MS_API_VERSION_HEADER_VALUE})
71 |
72 | # extract the juice
73 | dom = parseString(resp.content)
74 | subscriptions = dom.getElementsByTagName("Subscription")
75 | output = []
76 | tenantText = 'No subscriptions found in list.'
77 | for subscription in subscriptions:
78 | name = subscription.getElementsByTagName("SubscriptionName")[0]
79 | nameText = getText(name.childNodes)
80 | output.append(nameText)
81 |
82 | tenantid = subscription.getElementsByTagName("AADTenantID")[0]
83 | tenantText = getText(tenantid.childNodes)
84 | output.append(tenantText)
85 |
86 | # stick them in context & display
87 | context['subscriptions'] = output
88 |
89 | return render(request, STEP_2_TEMPLATE_NAME, context)
90 |
91 |
92 |
--------------------------------------------------------------------------------
/djangoSite/djangoSite/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for djangoSite project.
3 |
4 | For more information on this file, see
5 | https://docs.djangoproject.com/en/1.7/topics/settings/
6 |
7 | For the full list of settings and their values, see
8 | https://docs.djangoproject.com/en/1.7/ref/settings/
9 | """
10 |
11 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
12 | import os
13 | BASE_DIR = os.path.dirname(os.path.dirname(__file__))
14 |
15 |
16 | # Quick-start development settings - unsuitable for production
17 | # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
18 |
19 | # SECURITY WARNING: keep the secret key used in production secret!
20 | SECRET_KEY = '&&(@n=%^#nob=9ewfxgu&b7#2us_6ejomyr7_b#q@@hh#83a^x'
21 |
22 | # SECURITY WARNING: don't run with debug turned on in production!
23 | DEBUG = True
24 |
25 | TEMPLATE_DEBUG = True
26 |
27 | ALLOWED_HOSTS = []
28 |
29 |
30 | # Application definition
31 |
32 | INSTALLED_APPS = (
33 | 'django.contrib.admin',
34 | 'django.contrib.auth',
35 | 'django.contrib.contenttypes',
36 | 'django.contrib.sessions',
37 | 'django.contrib.messages',
38 | 'django.contrib.staticfiles',
39 | 'aadrest',
40 | )
41 |
42 | MIDDLEWARE_CLASSES = (
43 | 'django.contrib.sessions.middleware.SessionMiddleware',
44 | 'django.middleware.common.CommonMiddleware',
45 | 'django.middleware.csrf.CsrfViewMiddleware',
46 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
47 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
48 | 'django.contrib.messages.middleware.MessageMiddleware',
49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
50 | )
51 |
52 | ROOT_URLCONF = 'djangoSite.urls'
53 |
54 | WSGI_APPLICATION = 'djangoSite.wsgi.application'
55 |
56 |
57 | # Database
58 | # https://docs.djangoproject.com/en/1.7/ref/settings/#databases
59 |
60 | DATABASES = {
61 | 'default': {
62 | 'ENGINE': 'django.db.backends.sqlite3',
63 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
64 | }
65 | }
66 |
67 | # my constants
68 | CONSTANTS = {
69 | 'CLIENT_ID': '54da33ea-bd9b-4391-9863-33af3f005b53',
70 | 'CLIENT_KEY': 'gvky5/Jf2Ig4SCa472Gt0z82KWE6Bl9s+nH2BOYPlW8=',
71 | 'STEP_1_TEMPLATE_NAME': 'aadrest/step1.html',
72 | 'STEP_2_TEMPLATE_NAME': 'aadrest/step2.html',
73 | 'STEP_3_TEMPLATE_NAME': 'aadrest/step3.html',
74 | 'STEP_4_TEMPLATE_NAME': 'aadrest/step4.html',
75 | 'STEP_5_TEMPLATE_NAME': 'aadrest/step5.html',
76 | 'STEP_1_TEMPLATE_NAME_LIVE': 'aadrest/step1_live.html',
77 | 'STEP_2_TEMPLATE_NAME_LIVE': 'aadrest/step2_live.html',
78 | 'STEP_3_TEMPLATE_NAME_LIVE': 'aadrest/step3_live.html',
79 | 'STEP_4_TEMPLATE_NAME_LIVE': 'aadrest/step4_live.html',
80 | 'STEP_5_TEMPLATE_NAME_LIVE': 'aadrest/step5_live.html',
81 | 'REDIRECT_URI': 'http://localhost:8000/aadrest/step2/',
82 | 'REDIRECT_URI_LIVE': 'http://localhost:8000/aadrest/step2_live/',
83 | 'AUTHORIZATION_BASE_URL': 'https://login.windows.net/%s/oauth2/authorize',
84 | 'BASE_TOKEN_URL': 'https://login.windows.net/%s/oauth2/token',
85 | 'RESOURCE_URI': 'https://management.core.windows.net/',
86 | 'GET_SUBSCRIPTIONS_URL': 'https://management.core.windows.net/subscriptions',
87 | 'MS_API_VERSION_HEADER': 'x-ms-version',
88 | 'MS_API_VERSION_HEADER_VALUE': '2013-08-01'
89 | }
90 |
91 | # Internationalization
92 | # https://docs.djangoproject.com/en/1.7/topics/i18n/
93 |
94 | LANGUAGE_CODE = 'en-us'
95 |
96 | TIME_ZONE = 'UTC'
97 |
98 | USE_I18N = True
99 |
100 | USE_L10N = True
101 |
102 | USE_TZ = True
103 |
104 |
105 | # Static files (CSS, JavaScript, Images)
106 | # https://docs.djangoproject.com/en/1.7/howto/static-files/
107 |
108 | STATIC_URL = '/static/'
109 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/djangoSite/aadrest/views.py:
--------------------------------------------------------------------------------
1 | from xml.dom.minidom import parseString
2 | from django.shortcuts import render, redirect
3 | import requests
4 | from requests_oauthlib import OAuth2Session
5 | from django.conf import settings
6 | import logging
7 | logging.basicConfig(level=logging.INFO)
8 |
9 | def getText(nodelist):
10 | rc = []
11 | for node in nodelist:
12 | if node.nodeType == node.TEXT_NODE:
13 | rc.append(node.data)
14 | return ''.join(rc)
15 |
16 | def index(request):
17 | context = {'initialize':''}
18 | return render(request, 'aadrest/index.html', context)
19 |
20 | def step1(request):
21 |
22 | # initialization
23 | constants = settings.CONSTANTS
24 | CLIENT_ID = constants['CLIENT_ID']
25 | STEP_1_TEMPLATE_NAME = constants['STEP_1_TEMPLATE_NAME']
26 | REDIRECT_URI = constants['REDIRECT_URI']
27 | AUTHORIZATION_BASE_URL = constants['AUTHORIZATION_BASE_URL']
28 |
29 | context = {'initialize':''}
30 |
31 | # GET as a result of initial invocation
32 | if request.method == 'GET':
33 |
34 | # initial invocation, just render
35 | return render(request, STEP_1_TEMPLATE_NAME, context)
36 |
37 | # OAUTH STEP 1 - POST as a result of clicking the LogIn submit button
38 | elif request.method == 'POST':
39 |
40 | # create a 'requests' Oauth2Session
41 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
42 |
43 | # do the outreach to https://login.windows.net/common/oauth2/authorize
44 | authorization_url, state = azure_session.authorization_url(AUTHORIZATION_BASE_URL % 'common')
45 | resp = requests.get(authorization_url)
46 |
47 | # go to the login page of AAD & authenticate
48 | return redirect(resp.url)
49 |
50 | def step2(request):
51 |
52 | # initialization
53 | constants = settings.CONSTANTS
54 | STEP_2_TEMPLATE_NAME = constants['STEP_2_TEMPLATE_NAME']
55 | STEP_3_TEMPLATE_NAME = constants['STEP_3_TEMPLATE_NAME']
56 | BASE_TOKEN_URL = constants['BASE_TOKEN_URL']
57 | REDIRECT_URI = constants['REDIRECT_URI']
58 | CLIENT_ID = constants['CLIENT_ID']
59 | CLIENT_KEY = constants['CLIENT_KEY']
60 | RESOURCE_URI = constants['RESOURCE_URI']
61 |
62 | context = {'initialize':''}
63 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
64 |
65 | if request.method == 'GET':
66 |
67 | # get the code returned by AAD and save it in session
68 | aad_code = request.GET.get('code','')
69 | request.session['aad_code'] = aad_code
70 |
71 | # display the code
72 | context['aad_code'] = aad_code
73 |
74 | return render(request, STEP_2_TEMPLATE_NAME, context)
75 |
76 | elif request.method == 'POST':
77 |
78 | # get code back from session
79 | aad_code = request.session['aad_code']
80 |
81 | # OAUTH STEP 2 - go fetch the token
82 | token_dict = azure_session.fetch_token(BASE_TOKEN_URL % 'common', code=aad_code, client_secret=CLIENT_KEY, resource=RESOURCE_URI)
83 |
84 | # pass the token to the next step on session
85 | request.session['token'] = token_dict
86 |
87 | # display the token
88 | context['token'] = token_dict
89 |
90 | return render(request, STEP_3_TEMPLATE_NAME, context)
91 |
92 | def step3(request):
93 |
94 | # initialization
95 | constants = settings.CONSTANTS
96 | STEP_3_TEMPLATE_NAME = constants['STEP_3_TEMPLATE_NAME']
97 | STEP_4_TEMPLATE_NAME = constants['STEP_4_TEMPLATE_NAME']
98 | CLIENT_ID = constants['CLIENT_ID']
99 | REDIRECT_URI = constants['REDIRECT_URI']
100 | GET_SUBSCRIPTIONS_URL = constants['GET_SUBSCRIPTIONS_URL']
101 | MS_API_VERSION_HEADER = constants['MS_API_VERSION_HEADER']
102 | MS_API_VERSION_HEADER_VALUE = constants['MS_API_VERSION_HEADER_VALUE']
103 |
104 | context = {'initialize':''}
105 |
106 | if request.method == 'GET':
107 | return render(request, STEP_3_TEMPLATE_NAME, context)
108 |
109 | elif request.method == 'POST':
110 |
111 | # create a requests session with the token we got previously
112 | token = request.session['token']
113 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri = REDIRECT_URI, token=token)
114 |
115 | # OAUTH STEP 3 - go get the subscriptions
116 | resp = azure_session.get(GET_SUBSCRIPTIONS_URL, headers = {MS_API_VERSION_HEADER: MS_API_VERSION_HEADER_VALUE})
117 |
118 | # extract the juice
119 | dom = parseString(resp.content)
120 | subscriptions = dom.getElementsByTagName("Subscription")
121 | output = []
122 | tenantText = 'No subscriptions found in list.'
123 | for subscription in subscriptions:
124 | name = subscription.getElementsByTagName("SubscriptionName")[0]
125 | nameText = getText(name.childNodes)
126 | output.append(nameText)
127 |
128 | tenantid = subscription.getElementsByTagName("AADTenantID")[0]
129 | tenantText = getText(tenantid.childNodes)
130 | output.append(tenantText)
131 |
132 | # stick them in context & display
133 | context['subscriptions'] = output
134 |
135 | # store the tenant id in session
136 | request.session['tenantid'] = tenantText
137 |
138 | return render(request, STEP_4_TEMPLATE_NAME, context)
139 |
140 | def step4(request):
141 |
142 | # initialization
143 | constants = settings.CONSTANTS
144 | STEP_4_TEMPLATE_NAME = constants['STEP_4_TEMPLATE_NAME']
145 | STEP_5_TEMPLATE_NAME = constants['STEP_5_TEMPLATE_NAME']
146 | REDIRECT_URI = constants['REDIRECT_URI']
147 | BASE_TOKEN_URL = constants['BASE_TOKEN_URL']
148 | CLIENT_ID = constants['CLIENT_ID']
149 | CLIENT_KEY = constants['CLIENT_KEY']
150 | RESOURCE_URI = constants['RESOURCE_URI']
151 |
152 | context = {'initialize':''}
153 |
154 | if request.method == 'GET':
155 | return render(request, STEP_4_TEMPLATE_NAME, context)
156 |
157 | # OAUTH STEP 1 - POST as a result of clicking the LogIn submit button
158 | elif request.method == 'POST':
159 |
160 | # get the tenant id and AAD code
161 | tenantid = request.session['tenantid']
162 | aad_code = request.session['aad_code']
163 |
164 | # create a 'requests' Oauth2Session
165 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
166 |
167 | # OAUTH STEP 4 - go fetch the token for the tenant as opposed to Common
168 | token_dict = azure_session.fetch_token(BASE_TOKEN_URL % tenantid, code=aad_code, client_secret=CLIENT_KEY, resource=RESOURCE_URI)
169 |
170 | # put the token into context for display
171 | context['token'] = token_dict
172 |
173 | # present results
174 | return render(request, STEP_5_TEMPLATE_NAME, context)
175 |
176 | def step1_live(request):
177 |
178 | # initialization
179 | constants = settings.CONSTANTS
180 | CLIENT_ID = constants['CLIENT_ID']
181 | STEP_1_TEMPLATE_NAME = constants['STEP_1_TEMPLATE_NAME_LIVE']
182 | REDIRECT_URI = constants['REDIRECT_URI_LIVE']
183 | AUTHORIZATION_BASE_URL = constants['AUTHORIZATION_BASE_URL']
184 |
185 | context = {'initialize':''}
186 |
187 | # GET as a result of initial invocation
188 | if request.method == 'GET':
189 |
190 | # initial invocation, just render
191 | return render(request, STEP_1_TEMPLATE_NAME, context)
192 |
193 | # OAUTH STEP 1 - POST as a result of clicking the LogIn submit button
194 | elif request.method == 'POST':
195 |
196 | # get the tenant name
197 | tenant_name = request.POST['tenantname']
198 | logging.info('tenant name = ' + tenant_name)
199 | resource_name = tenant_name + '.onmicrosoft.com'
200 | request.session['resource_name'] = resource_name
201 |
202 | # create a 'requests' Oauth2Session
203 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
204 |
205 | # do the outreach to https://login.windows.net/common/oauth2/authorize
206 | authorization_url, state = azure_session.authorization_url(AUTHORIZATION_BASE_URL % resource_name)
207 | resp = requests.get(authorization_url)
208 |
209 | # go to the login page of AAD & authenticate
210 | return redirect(resp.url)
211 |
212 | def step2_live(request):
213 |
214 | # initialization
215 | constants = settings.CONSTANTS
216 | STEP_2_TEMPLATE_NAME = constants['STEP_2_TEMPLATE_NAME_LIVE']
217 | STEP_3_TEMPLATE_NAME = constants['STEP_3_TEMPLATE_NAME_LIVE']
218 | BASE_TOKEN_URL = constants['BASE_TOKEN_URL']
219 | REDIRECT_URI = constants['REDIRECT_URI_LIVE']
220 | CLIENT_ID = constants['CLIENT_ID']
221 | CLIENT_KEY = constants['CLIENT_KEY']
222 | RESOURCE_URI = constants['RESOURCE_URI']
223 |
224 | context = {'initialize':''}
225 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
226 |
227 | if request.method == 'GET':
228 |
229 | # get the code returned by AAD and save it in session
230 | aad_code = request.GET.get('code','')
231 | request.session['aad_code'] = aad_code
232 |
233 | # display the code
234 | context['aad_code'] = aad_code
235 |
236 | return render(request, STEP_2_TEMPLATE_NAME, context)
237 |
238 | elif request.method == 'POST':
239 |
240 | # get code back from session
241 | aad_code = request.session['aad_code']
242 | resource_name = request.session['resource_name']
243 |
244 | # OAUTH STEP 2 - go fetch the token
245 | token_dict = azure_session.fetch_token(BASE_TOKEN_URL % resource_name, code=aad_code, client_secret=CLIENT_KEY, resource=RESOURCE_URI)
246 |
247 | # pass the token to the next step on session
248 | request.session['token'] = token_dict
249 |
250 | # display the token
251 | context['token'] = token_dict
252 |
253 | return render(request, STEP_3_TEMPLATE_NAME, context)
254 |
255 | def step3_live(request):
256 |
257 | # initialization
258 | constants = settings.CONSTANTS
259 | STEP_3_TEMPLATE_NAME = constants['STEP_3_TEMPLATE_NAME_LIVE']
260 | STEP_4_TEMPLATE_NAME = constants['STEP_4_TEMPLATE_NAME_LIVE']
261 | CLIENT_ID = constants['CLIENT_ID']
262 | REDIRECT_URI = constants['REDIRECT_URI_LIVE']
263 | GET_SUBSCRIPTIONS_URL = constants['GET_SUBSCRIPTIONS_URL']
264 | MS_API_VERSION_HEADER = constants['MS_API_VERSION_HEADER']
265 | MS_API_VERSION_HEADER_VALUE = constants['MS_API_VERSION_HEADER_VALUE']
266 |
267 | context = {'initialize':''}
268 |
269 | if request.method == 'GET':
270 | return render(request, STEP_3_TEMPLATE_NAME, context)
271 |
272 | elif request.method == 'POST':
273 |
274 | # create a requests session with the token we got previously
275 | token = request.session['token']
276 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri = REDIRECT_URI, token=token)
277 |
278 | # OAUTH STEP 3 - go get the subscriptions
279 | resp = azure_session.get(GET_SUBSCRIPTIONS_URL, headers = {MS_API_VERSION_HEADER: MS_API_VERSION_HEADER_VALUE})
280 |
281 | # extract the juice
282 | dom = parseString(resp.content)
283 | subscriptions = dom.getElementsByTagName("Subscription")
284 | output = []
285 | tenantText = 'No subscriptions found in list.'
286 | for subscription in subscriptions:
287 | name = subscription.getElementsByTagName("SubscriptionName")[0]
288 | nameText = getText(name.childNodes)
289 | output.append(nameText)
290 |
291 | tenantid = subscription.getElementsByTagName("AADTenantID")[0]
292 | tenantText = getText(tenantid.childNodes)
293 | output.append(tenantText)
294 |
295 | # stick them in context & display
296 | context['subscriptions'] = output
297 |
298 | # store the tenant id in session
299 | request.session['tenantid'] = tenantText
300 |
301 | return render(request, STEP_4_TEMPLATE_NAME, context)
302 |
303 | def step4_live(request):
304 |
305 | # initialization
306 | constants = settings.CONSTANTS
307 | STEP_4_TEMPLATE_NAME = constants['STEP_4_TEMPLATE_NAME_LIVE']
308 | STEP_5_TEMPLATE_NAME = constants['STEP_5_TEMPLATE_NAME_LIVE']
309 | REDIRECT_URI = constants['REDIRECT_URI_LIVE']
310 | BASE_TOKEN_URL = constants['BASE_TOKEN_URL']
311 | CLIENT_ID = constants['CLIENT_ID']
312 | CLIENT_KEY = constants['CLIENT_KEY']
313 | RESOURCE_URI = constants['RESOURCE_URI']
314 |
315 | context = {'initialize':''}
316 |
317 | if request.method == 'GET':
318 | return render(request, STEP_4_TEMPLATE_NAME, context)
319 |
320 | # OAUTH STEP 1 - POST as a result of clicking the LogIn submit button
321 | elif request.method == 'POST':
322 |
323 | # get the tenant id and AAD code
324 | tenantid = request.session['tenantid']
325 | aad_code = request.session['aad_code']
326 |
327 | # create a 'requests' Oauth2Session
328 | azure_session = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI)
329 |
330 | # OAUTH STEP 4 - go fetch the token for the tenant as opposed to Common
331 | token_dict = azure_session.fetch_token(BASE_TOKEN_URL % tenantid, code=aad_code, client_secret=CLIENT_KEY, resource=RESOURCE_URI)
332 |
333 | # put the token into context for display
334 | context['token'] = token_dict
335 |
336 | # present results
337 | return render(request, STEP_5_TEMPLATE_NAME, context)
338 |
--------------------------------------------------------------------------------