0

I'm at my wit's end here trying to get Azure Active Directory user authentication for my Flask webapp. Before trying any of the user authentication stuff, it was working, but now I've followed all the examples I could find and I don't know what I'm doing wrong. Maybe I'm headed down the wrong path completely, but I could use some feedback if anyone can tell what I'm doing wrong. It won't work either on the local host or on the website itself. On the website, I just get a 500 error that the request timed out. On the local host, it'll get me the sign in request, but then it returns an error after that.

I've followed this documentation step by step:

https://github.com/Azure-Samples/active-directory-python-webapp-graphapi

I registered my webapp in the Azure Active Directory and I set the App IDU URI to:

https://{company_domain.com}/{appname}

Home Page URL to:

https://{appname}.azurewebsites.net

Reply URLs to:

https://{appname}.azurewebsites.net

Required Permissions to allow Delegated Permissions to "Sign in and read user profile"

In my code, I created a config.py file that looks like this:

RESOURCE = "https://{app_name}.azurewebsites.net"
TENANT = "{company_domain_name.com}"
AUTHORITY_HOST_URL = "https://login.microsoftonline.com"
CLIENT_ID = "{client_id}"  # copy the Application ID of your app from your Azure portal
CLIENT_SECRET = "{client_secret_key}"  # copy the value of key you generated when setting up the application

Then in my init.py file I have the following code:

from flask import Flask, render_template, Response, session, request, url_for, redirect
import adal
import config
import requests
import uuid

AUTHORITY_URL = config.AUTHORITY_HOST_URL + '/' + config.TENANT
REDIRECT_URI = 'https://{appname}.azurewebsites.net/getAtoken'
TEMPLATE_AUTHZ_URL = ('https://login.microsoftonline.com/{}/oauth2/authorize?' +
                      'response_type=code&client_id={}&redirect_uri={}&' +
                      'state={}&resource={}')
@app.route("/")
def main():
    login_url = 'http://<app_name>.azurewebsites.net/login'
    resp = Response(status=307)
    resp.headers['location'] = login_url
    return resp

@app.route("/login")
def login():
    auth_state = str(uuid.uuid4())
    session['state'] = auth_state
    authorization_url = TEMPLATE_AUTHZ_URL.format(
        config.TENANT,
        config.CLIENT_ID,
        REDIRECT_URI,
        auth_state,
        config.RESOURCE)
    resp = Response(status=307)
    resp.headers['location'] = authorization_url
    return resp

@app.route("/getAToken")
def main_logic():
    code = request.args['code']
    state = request.args['state']
    if state != session['state']:
        raise ValueError("State does not match")
    auth_context = adal.AuthenticationContext(AUTHORITY_URL)
    token_response = auth_context.acquire_token_with_authorization_code(code, REDIRECT_URI, config.RESOURCE,
                                                                        config.CLIENT_ID, config.CLIENT_SECRET)
    Flask.session['access_token'] = token_response['accessToken']

    return Flask.redirect('/index')

@app.route('/index')
def index():
    if 'access_token' not in session:
        return redirect(url_for('login'))
    endpoint = config.RESOURCE + '/' + config.API_VERSION + '/me/'
    http_headers = {'Authorization': session.get('access_token'),
                    'User-Agent': 'adal-python-sample',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'client-request-id': str(uuid.uuid4())}
    return render_template('index.html')
Emac
  • 1,098
  • 3
  • 18
  • 37

1 Answers1

1

On the local host, it'll get me the sign in request, but then it returns an error after that.

It indicates that the reply url is not matched. you could add the reply url (http://localhost:5000/getAToken) for registered Azure AD WebApp. If you want to run it in the local and azure platform, you could add both of then in the reply urls.

enter image description here

Test it locally

enter image description here

On the website, I just get a 500 error that the request timed out

It seems that the WebApp is not developed correctly. For more information about how to set up a Python environment on Azure App Service, please refer to this tutorial.

Tom Sun - MSFT
  • 24,161
  • 3
  • 30
  • 47
  • Thanks for your help. I'm out of town so I won't be able to try this until Tuesday, but I'll let you know what happens. As for the WebApp though, it works fine without the user authorization, it's once I implement the user authorization that it starts to time out. – Emac Sep 08 '18 at 15:19
  • I have finally gotten it to work on the Local Host, but it won't work once it is deployed. It worked before I tried the AAD stuff though, so something with the AAD is throwing it off. I don't know how to debug it since all I can get back is a 500 error of a timeout. – Emac Sep 11 '18 at 20:36
  • We could use the `WSGI_LOG` to debug our application in the Azure webApp. And you could use the kudu (https://github.com/projectkudu/kudu/wiki/Kudu-console) tool to get the detail run log. As I mentioned that you could refer to this [tutorial](https://learn.microsoft.com/en-us/visualstudio/python/managing-python-on-azure-app-service?view=vs-2017) and [SO thread](https://stackoverflow.com/questions/49087407/pyodbc-on-azure/49105747#49105747) to deploy the flask webapp to azure webapp. – Tom Sun - MSFT Sep 25 '18 at 08:01
  • Thanks for the reply. I got some help from Microsoft and finally resolved it. I also ended up going a different route and instead used Flask Dance. – Emac Sep 25 '18 at 12:27