diff --git a/README.md b/README.md index 5fb9a6a..7a08aa4 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,77 @@ -# Microsoft identity platform product documentation backing code +# Code samples for Microsoft identity platform documentation - Python -This repo contains code used to directly support the product documentation for the [Microsoft identity platform](https://docs.microsoft.com/azure/active-directory/develop/). It is a mono-repo that contains all of the referenced tutorials relating to Python-based implementations using the [Microsoft Autentication Library (MSAL) for Python](https://github.com/AzureAD/microsoft-authentication-library-for-python). +Welcome to the Microsoft Identity Platform Python Code Samples repository! -## Content +This repository provides a comprehensive set of end-to-end samples demonstrating how to integrate Microsoft Entra ID authentication and authorization into Python applications. The samples are organized by scenario and technology, making it easy to find the right starting point for your needs. -This repo contains the following code to directly support the product docs: +## 📁 Repository Structure -* Coming Soon! +The samples are grouped by application type and scenario: -## Resources +| Folder | App description | Authentication libraries | +|-------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------| +| [flask-web-app](./flask-web-app) | Multi-purpose Flask web application with Microsoft Entra sign-in, External ID, B2C support | ms-identity-python[flask]
MSAL Python | +| [django-web-app](./django-web-app) | Multi-purpose Django web application with Microsoft Entra sign-in, External ID, B2C support | ms-identity-python[django]
MSAL Python | +| [console-app-device-code](./console-app-device-code) | Console application using device code flow for user authentication | MSAL Python | +| [cli-access-protected-api](./cli-access-protected-api) | CLI application accessing protected APIs using client credentials | MSAL Python | +| [protect-function-app](./protect-function-app) | Azure Function protected with Easy Auth and scope validation | Azure Functions | +| [daemon-console-app](./daemon-console-app) | Daemon applications using client credentials (secret/certificate) | MSAL Python | +| [on-behalf-of-flow](./on-behalf-of-flow) | Multi-tier application demonstrating On-Behalf-Of (OBO) flow | MSAL Python | -- [Microsoft identity platform product documentation](https://docs.microsoft.com/azure/active-directory/develop/) -- [Microsoft Authentication Library (MSAL) documentation](https://docs.microsoft.com/azure/active-directory/develop/msal-overview) -- [Microsoft Authentication Library (MSAL) for Python](https://github.com/AzureAD/microsoft-authentication-library-for-python) -- [msal on PyPI](https://pypi.org/project/msal/) -- [Microsoft Authentication Library (MSAL) for Python SDK Docs](https://msal-python.readthedocs.io/en/latest/) -- [MSAL for Python Roadmap](https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Roadmap) +--- + +Each folder contains one or more samples, each with its own README and instructions. + +--- + +## 🚀 Getting Started + +1. Browse the folders above to find the app type/scenario that matches your use case. +2. Read the sample's README.md for prerequisites, setup instructions, and code walkthroughs. +3. Clone and run the sample following the provided steps. + +All samples are built with Python 3.8+ and the latest Microsoft Authentication Library (MSAL) for Python. + +--- + +## 📝 Configuration & Security + +- Configuration is managed via `.env` files and environment variables. +- Each sample includes multiple `.env.sample` templates for different identity providers (Entra ID, External ID, B2C). +- Secrets and credentials should never be committed to source control. Use environment variables or [Azure Key Vault](https://learn.microsoft.com/azure/key-vault/general/basic-concepts) for sensitive data. + +--- + +## 🤝 Contributing + +We welcome contributions! +Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on submitting new samples or improvements. + +--- + +## 📢 Support & Feedback + +- For questions, open an [issue](https://github.com/Azure-Samples/ms-identity-docs-code-python/issues). +- For Microsoft identity platform documentation, visit [learn.microsoft.com/entra/identity-platform](https://learn.microsoft.com/entra/identity-platform). + +--- + +## 📄 License + +This project is licensed under the [MIT License](LICENSE.md). + +--- + +## 📚 Resources + +- Documentation on learn.microsoft.com + - [Microsoft identity platform product documentation](https://learn.microsoft.com/entra/identity-platform/) + - [Microsoft Authentication Library (MSAL) documentation](https://learn.microsoft.com/entra/identity-platform/msal-overview) +- Authentication library source code on GitHub + - [Microsoft Authentication Library (MSAL) for Python](https://github.com/AzureAD/microsoft-authentication-library-for-python) + - [MSAL for Python SDK Docs](https://msal-python.readthedocs.io/en/latest/) +- Python Package Index + - [msal on PyPI](https://pypi.org/project/msal/) + - [ms-identity-python on PyPI](https://pypi.org/project/identity/) + +--- diff --git a/daemon-console-app/.gitignore b/daemon-console-app/.gitignore new file mode 100644 index 0000000..894a44c --- /dev/null +++ b/daemon-console-app/.gitignore @@ -0,0 +1,104 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ diff --git a/daemon-console-app/CODE_OF_CONDUCT.md b/daemon-console-app/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f9ba8cf --- /dev/null +++ b/daemon-console-app/CODE_OF_CONDUCT.md @@ -0,0 +1,9 @@ +# Microsoft Open Source Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +Resources: + +- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) +- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns diff --git a/daemon-console-app/LICENSE b/daemon-console-app/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/daemon-console-app/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/daemon-console-app/README.md b/daemon-console-app/README.md new file mode 100644 index 0000000..5f01668 --- /dev/null +++ b/daemon-console-app/README.md @@ -0,0 +1,68 @@ +--- +page_type: sample +languages: +- python +- powershell +products: +- azure-active-directory +description: "This sample demonstrates a Python daemon console app calling the Microsoft Graph that is secured using the Microsoft identity platform." +urlFragment: ms-identity-python-webapp +--- + +# A Python console daemon app calling Microsoft Graph + + + +## About this sample + +### Scenario + +You want to write a daemon application that consumes organizational data using Microsoft Graph and using **Microsoft Identity Platform** to acquire tokens. + +For details see [Daemon apps scenario](https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-overview). + +### Structure of the repository + +This repository contains a progressive tutorial made of two parts: + +Sub folder | Description +----------------------------- | ----------- +[1-Call-MsGraph-WithSecret](https://github.com/Azure-Samples/ms-identity-python-daemon/tree/master/1-Call-MsGraph-WithSecret) | This sample application shows how to use the Microsoft identity platform endpoint to access the data of Microsoft business customers in a long-running, non-interactive process. The daemon application proves its identity using a **client secret**. It uses the OAuth 2 client credentials grant to acquire an access token, which can be used to call the Microsoft Graph and access organizational data

![Topology](./1-Call-MsGraph-WithSecret/ReadmeFiles/topology.svg) +[2-Call-MsGraph-WithCertificate](https://github.com/Azure-Samples/ms-identity-python-daemon/tree/master/2-Call-MsGraph-WithCertificate) | This variation of the first sample shows how the application proves its identity using a **certificate**.

![Topology](./2-Call-MsGraph-WithCertificate/ReadmeFiles/topology.svg) + +## Prerequisites + +To run this sample, you'll need: + +> - [Python 2.7+](https://www.python.org/downloads/release/python-2713/) or [Python 3+](https://www.python.org/downloads/release/python-364/) +> - An Microsoft Entra tenant. For more information on how to get an Microsoft Entra tenant, see [how to get an Microsoft Entra tenant.](https://docs.microsoft.com/azure/active-directory/develop/quickstart-create-new-tenant) + +## Setup and run the sample + +Download and extract the repository .zip file or, from your shell or command line: + +```Shell +git clone https://github.com/Azure-Samples/ms-identity-python-daemon.git +``` + +Then, see the readme of each sub-folder to understand how to setup and run the samples, and learn key concepts. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/daemon-console-app/SECURITY.md b/daemon-console-app/SECURITY.md new file mode 100644 index 0000000..e0dfff5 --- /dev/null +++ b/daemon-console-app/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). + + diff --git a/flask-web-app/AppCreationScripts/AppCreationScripts.md b/flask-web-app/AppCreationScripts/AppCreationScripts.md index b19fa00..4c8ae67 100644 --- a/flask-web-app/AppCreationScripts/AppCreationScripts.md +++ b/flask-web-app/AppCreationScripts/AppCreationScripts.md @@ -118,7 +118,7 @@ Note that the script will choose the tenant in which to create the applications, - Open the [Microsoft Entra admin center](https://entra.microsoft.com) - Select the Microsoft Entra ID you are interested in (in the combo-box below your name on the top right of the browser window) -- Find the "Active Directory" object in this tenant +- Find the "Microsoft Entra" object in this tenant - Go to **Properties** and copy the content of the **Directory Id** property - Then use the full syntax to run the scripts: diff --git a/flask-web-app/AppCreationScripts/Cleanup.ps1 b/flask-web-app/AppCreationScripts/Cleanup.ps1 index d1b1fe6..b7fd13f 100644 --- a/flask-web-app/AppCreationScripts/Cleanup.ps1 +++ b/flask-web-app/AppCreationScripts/Cleanup.ps1 @@ -15,11 +15,11 @@ Function Cleanup { <# .Description - This function removes the Azure AD applications for the sample. These applications were created by the Configure.ps1 script + This function removes the Microsoft Entra applications for the sample. These applications were created by the Configure.ps1 script #> - # $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant - # into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Azure AD. + # $tenantId is the Microsoft Entra Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant + # into which you want to create the apps. Look it up in the Azure portal in the "Properties" of the Microsoft Entra. # Connect to the Microsoft Graph API Write-Host "Connecting to Microsoft Graph" diff --git a/flask-web-app/AppCreationScripts/Configure.ps1 b/flask-web-app/AppCreationScripts/Configure.ps1 index 3c58ced..a294056 100644 --- a/flask-web-app/AppCreationScripts/Configure.ps1 +++ b/flask-web-app/AppCreationScripts/Configure.ps1 @@ -7,8 +7,8 @@ param( ) <# - This script creates the Azure AD applications needed for this sample and updates the configuration files - for the visual Studio projects from the data in the Azure AD applications. + This script creates the Microsoft Entra applications needed for this sample and updates the configuration files + for the visual Studio projects from the data in the Microsoft Entra applications. In case you don't have Microsoft.Graph.Applications already installed, the script will automatically install it for the current user There are two ways to run this script. For more information, read the AppCreationScripts.md file in the same folder as this script. @@ -56,7 +56,7 @@ Function ConfigureApplications { $isOpenSSl = 'N' #temporary disable open certificate creation <#.Description - This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the + This function creates the Microsoft Entra applications for the sample in the provided Microsoft Entra tenant and updates the configuration files in the client and service project of the visual studio solution (App.Config and Web.Config) so that they are consistent with the Applications parameters #> diff --git a/on-behalf-of-flow/.gitignore b/on-behalf-of-flow/.gitignore new file mode 100644 index 0000000..8e335a4 --- /dev/null +++ b/on-behalf-of-flow/.gitignore @@ -0,0 +1,353 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +development.env +Pipfile.lock +db.sqlite3 + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ diff --git a/on-behalf-of-flow/CHANGELOG.md b/on-behalf-of-flow/CHANGELOG.md new file mode 100644 index 0000000..9824752 --- /dev/null +++ b/on-behalf-of-flow/CHANGELOG.md @@ -0,0 +1,13 @@ +## [project-title] Changelog + + +# x.y.z (yyyy-mm-dd) + +*Features* +* ... + +*Bug Fixes* +* ... + +*Breaking Changes* +* ... diff --git a/on-behalf-of-flow/CODE_OF_CONDUCT.md b/on-behalf-of-flow/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..6257f2e --- /dev/null +++ b/on-behalf-of-flow/CODE_OF_CONDUCT.md @@ -0,0 +1,9 @@ +# Microsoft Open Source Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +Resources: + +- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) +- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns \ No newline at end of file diff --git a/on-behalf-of-flow/CONTRIBUTING.md b/on-behalf-of-flow/CONTRIBUTING.md new file mode 100644 index 0000000..a9115cf --- /dev/null +++ b/on-behalf-of-flow/CONTRIBUTING.md @@ -0,0 +1,76 @@ +# Contributing to [project-title] + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + + - [Code of Conduct](#coc) + - [Issues and Bugs](#issue) + - [Feature Requests](#feature) + - [Submission Guidelines](#submit) + +## Code of Conduct +Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +## Found an Issue? +If you find a bug in the source code or a mistake in the documentation, you can help us by +[submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can +[submit a Pull Request](#submit-pr) with a fix. + +## Want a Feature? +You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub +Repository. If you would like to *implement* a new feature, please submit an issue with +a proposal for your work first, to be sure that we can use it. + +* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). + +## Submission Guidelines + +### Submitting an Issue +Before you submit an issue, search the archive, maybe your question was already answered. + +If your issue appears to be a bug, and hasn't been reported, open a new issue. +Help us to maximize the effort we can spend fixing issues and adding new +features, by not reporting duplicate issues. Providing the following information will increase the +chances of your issue being dealt with quickly: + +* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps +* **Version** - what version is affected (e.g. 0.1.2) +* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you +* **Browsers and Operating System** - is this a problem with all browsers? +* **Reproduce the Error** - provide a live example or a unambiguous set of steps +* **Related Issues** - has a similar issue been reported before? +* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be + causing the problem (line of code or commit) + +You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. + +### Submitting a Pull Request (PR) +Before you submit your Pull Request (PR) consider the following guidelines: + +* Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR + that relates to your submission. You don't want to duplicate effort. + +* Make your changes in a new git fork: + +* Commit your changes using a descriptive commit message +* Push your fork to GitHub: +* In GitHub, create a pull request +* If we suggest changes then: + * Make the required updates. + * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): + + ```shell + git rebase master -i + git push -f + ``` + +That's it! Thank you for your contribution! diff --git a/on-behalf-of-flow/LICENSE.md b/on-behalf-of-flow/LICENSE.md new file mode 100644 index 0000000..7965606 --- /dev/null +++ b/on-behalf-of-flow/LICENSE.md @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE \ No newline at end of file diff --git a/on-behalf-of-flow/README.md b/on-behalf-of-flow/README.md new file mode 100644 index 0000000..ceee8ec --- /dev/null +++ b/on-behalf-of-flow/README.md @@ -0,0 +1,376 @@ +--- +page_type: sample +languages: + - python +products: + - azure-active-directory + - microsoft-identity-platform + - msal-python +name: Enable your Python Flask API to call the Azure Management API on a user's behalf from your Python Django Web App with the Microsoft Identity Platform. +urlFragment: ms-identity-python-on-behalf-of +description: "This sample demonstrates a Python Django Web App calling a Python Flask Web API that is secured using Microsoft Entra" +--- +# Enable your Python Flask API to call the Azure Management API on a user's behalf from your Python Django Web App with the Microsoft Identity Platform + + 1. [Overview](#overview) + 1. [Scenario](#scenario) + 1. [Contents](#contents) + 1. [Prerequisites](#prerequisites) + 1. [Setup](#setup) + 1. [Registration](#registration) + 1. [Running the sample](#running-the-sample) + 1. [Explore the sample](#explore-the-sample) + 1. [About the code](#about-the-code) + 1. [Deployment](#deployment) + 1. [More information](#more-information) + 1. [Community Help and Support](#community-help-and-support) + 1. [Contributing](#contributing) + +## Overview + +This sample demonstrates a Python Django Web App calling a Python Flask Web API that is secured using Microsoft Entra using the [Microsoft Authentication Library \(MSAL\) for Python](https://github.com/AzureAD/microsoft-authentication-library-for-python). + +## Scenario + +1. The client Python Django Web App uses the Microsoft Authentication Library (MSAL) to sign-in and obtain an [Access Token](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) from **Microsoft Entra**. +2. The access token is used as a bearer token to authorize the user to call the Python Flask Web API protected by **Microsoft Entra**. +3. The Python Flask Web API then receives a token for **Azure Resource Management** API using the [On-Behalf-Of](https://docs.microsoft.coms/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow) flow. + +![Overview](./ReadmeFiles/topology.png) + +## Contents + +| File/folder | Description | +|-------------------|--------------------------------------------| +| `AppCreationScripts/`| Scripts to automatically configure Microsoft Entra app registrations.| +| `DjangoUI/`| The web app that signs the user in| +| `FlaskAPI/`| The protected resource API that performs the On-Behalf-Of flow.| +| `CHANGELOG.md` | List of changes to the sample. | +| `CONTRIBUTING.md` | Guidelines for contributing to the sample. | +| `LICENSE` | The license for the sample. | + +## Prerequisites + +- [Python 3.8](https://www.python.org/downloads/) +- A [virtual environment](https://docs.python.org/3/tutorial/venv.html) for each application to to work from +- If using VS Code, select the [Python interpreter](https://code.visualstudio.com/docs/languages/python) from the virtual environment +- An Microsoft Entra tenant. For more information on how to get an Microsoft Entra tenant, see [How to get an Microsoft Entra tenant](https://azure.microsoft.com/documentation/articles/active-directory-howto-tenant/) +- A user account in your own Microsoft Entra tenant. This sample will not work with a **personal Microsoft account**. If have not yet [created a user account](https://docs.microsoft.com/azure/active-directory/fundamentals/add-users-azure-active-directory) in your AD tenant yet, you should do so before proceeding + +> - Configure [VS Code](https://code.visualstudio.com/docs/python/python-tutorial) for debugging Python applications + +## Setup + +### Step 1: Clone or download this repository + +From your shell or command line: + +```console + git clone https://github.com/Azure-Samples/https://github.com/Azure-Samples/ms-identity-python-on-behalf-of.git +``` + +or download and extract the repository .zip file. + +> :warning: To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive. + +### Step 2: Install project dependencies + +1. Navigate to the folder where you cloned this project +2. If using VS Code, open each project sub-folder (`DjangoUI` and `FlaskAPI`) in separate VS Code instances. +3. Activate your Python 3 virtual environment (either directly in the [command line](https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments) or [VS Code](https://code.visualstudio.com/docs/languages/python)) +4. You will need to install dependencies using pip + 1. The below shell commands must be executed in both applications as they both have separate requirements.txt files + 2. There is also Pipfile included in both applications if you prefer to use [pipenv](https://pypi.org/project/pipenv/) instead + +In the 'FlaskAPI' sub-folder, use the following command: + + ```Shell + # start from the directory in which this sample is clone into + cd FlaskAPI + python3 -m venv venv # only required if you don't have a venv already + source venv/bin/activate + pip install -r requirements.txt + ``` + +In the 'DjangoUI' sub-folder, local execution only, use the following command: + + ```Shell + # start from the directory in which this sample is clone into + cd DjangoUI + python3 -m venv venv # only required if you don't have a venv already + Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force + . .\venv\Scripts\Activate.ps1 + pip install -r requirements.txt + ``` + +### Register the sample application(s) with your Microsoft Entra tenant + +There are two projects in this sample. Each needs to be separately registered in your Microsoft Entra tenant. To register these projects, you can: + +- follow the steps below for manually register your apps +- or use PowerShell scripts that: + - **automatically** creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you. + - modify the projects' configuration files. + +
+ Expand this section if you want to use this automation: + +> :warning: If you have never used **Azure AD Powershell** before, we recommend you go through the [App Creation Scripts](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step. + +1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory +1. If you have never used Azure AD Powershell before, we recommend you go through the [App Creation Scripts](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step. +1. In PowerShell run: + + ```PowerShell + Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force + ``` + +1. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly. +1. In PowerShell run: + + ```PowerShell + cd .\AppCreationScripts\ + .\Configure.ps1 + ``` + + > Other ways of running the scripts are described in [App Creation Scripts](./AppCreationScripts/AppCreationScripts.md) + > The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios. + +
+ +### Choose the Microsoft Entra tenant where you want to create your applications + +As a first step you'll need to: + +1. Sign in to the [Azure portal](https://portal.azure.com). +1. If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then **switch directory** to change your portal session to the desired Microsoft Entra tenant. + +### Register the service app (Python Flask Web API) + +1. Navigate to the [Azure portal](https://portal.azure.com) and select the **Microsoft Entra** service. +1. Select the **App Registrations** blade on the left, then select **New registration**. +1. In the **Register an application page** that appears, enter your application's registration information: + - In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example `Python Flask Web API`. + - Under **Supported account types**, select **Accounts in this organizational directory only**. +1. Select **Register** to create the application. +1. In the app's registration screen, find and note the **Application (client) ID**. You use this value in your app's configuration file(s) later in your code. +1. Select **Save** to save your changes. +1. In the app's registration screen, select the **Certificates & secrets** blade in the left to open the page where we can generate secrets and upload certificates. +1. In the **Client secrets** section, select **New client secret**: + - Type a key description (for instance `app secret`), + - Select one of the available key durations (**In 1 year**, **In 2 years**, or **Never Expires**) as per your security posture. + - The generated key value will be displayed when you select the **Add** button. Copy the generated value for use in the steps later. + - You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade. +1. In the app's registration screen, select the **API permissions** blade in the left to open the page where we add access to the APIs that your application needs. + - Select the **Add a permission** button and then, + - Ensure that the **Microsoft APIs** tab is selected. + - In the list of APIs, select the API `Azure Service Management`. + - In the **Delegated permissions** section, select the **user_impersonation** in the list. Use the search box if necessary. + - Select the **Add permissions** button at the bottom. +1. In the app's registration screen, select the **Expose an API** blade to the left to open the page where you can declare the parameters to expose this app as an API for which client applications can obtain [access tokens](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) for. +The first thing that we need to do is to declare the unique [resource](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow) URI that the clients will be using to obtain access tokens for this Api. To declare an resource URI, follow the following steps: + - Select `Set` next to the **Application ID URI** to generate a URI that is unique for this app. + - For this sample, accept the proposed Application ID URI (`api://{clientId}`) by selecting **Save**. +1. All APIs have to publish a minimum of one [scope](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code) for the client's to obtain an access token successfully. To publish a scope, follow the following steps: + - Select **Add a scope** button open the **Add a scope** screen and Enter the values as indicated below: + - For **Scope name**, use `access_as_user`. + - Select **Admins and users** options for **Who can consent?**. + - For **Admin consent display name** type `Access Python Flask Web API`. + - For **Admin consent description** type `Allows the app to access Python Flask Web API as the signed-in user.` + - For **User consent display name** type `Access Python Flask Web API`. + - For **User consent description** type `Allow the application to access Python Flask Web API on your behalf.` + - Keep **State** as **Enabled**. + - Select the **Add scope** button on the bottom to save this scope. +1. In the **Manifest** section, make sure to change the value fore *acceptedTokenVersion* to **2**. + +#### Configure the service app (Python Flask Web API) to use your app registration + +Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code. + +> In the steps below, "ClientID" is the same as "Application ID" or "AppId". + +1. In the 'FlaskAPI' sub-folder, open the `FlaskAPI\production.env` file and make a copy in the same directory called `development.env`. In this new file: +2. Find the key `CLIENT_ID` and replace the existing value with the application ID (clientId) of `Python Flask Web API` app copied from the Azure portal. +3. Find the key `CLIENT_SECRET` and replace the existing value with the key you saved during the creation of `Python Flask Web API` copied from the Azure portal. +4. Find the key `AUTHORITY` and replace the `ReplaceWithTenantID` portion with the tenant ID value that you obtained from the portal. +5. Find the key `ISSUER` and replace the `ReplaceWithTenantID` portion with the tenant ID value that you obtained from the portal. + +### Register the client app (Python Django Web App) + +1. Navigate to the [Azure portal](https://portal.azure.com) and select the **Microsoft Entra** service. +1. Select the **App Registrations** blade on the left, then select **New registration**. +1. In the **Register an application page** that appears, enter your application's registration information: + - In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example `Python Django Web App`. + - Under **Supported account types**, select **Accounts in this organizational directory only**. + - In the **Redirect URI (optional)** section, select **Web** in the combo-box and enter the following redirect URI: `http://localhost:8000/account/callback`. +1. Select **Register** to create the application. +1. In the app's registration screen, find and note the **Application (client) ID**. You use this value in your app's configuration file(s) later in your code. +1. Select **Save** to save your changes. +1. In the app's registration screen, select the **Certificates & secrets** blade in the left to open the page where we can generate secrets and upload certificates. +1. In the **Client secrets** section, select **New client secret**: + - Type a key description (for instance `app secret`), + - Select one of the available key durations (**In 1 year**, **In 2 years**, or **Never Expires**) as per your security posture. + - The generated key value will be displayed when you select the **Add** button. Copy the generated value for use in the steps later. + - You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade. +1. In the app's registration screen, select the **API permissions** blade in the left to open the page where we add access to the APIs that your application needs. + - Select the **Add a permission** button and then: + + - Ensure that the **My APIs** tab is selected. + - In the list of APIs, select the API `Python Flask Web API`. + - In the **Delegated permissions** section, select the **access_as_user** in the list. Use the search box if necessary. + - Select the **Add permissions** button at the bottom. + - Select the **Add a permission** button and then: + + - Ensure that the **Microsoft APIs** tab is selected. + - In the list of APIs, select the API `Microsoft Graph API`. + - In the **Delegated permissions** section, select the **openid** in the list. Use the search box if necessary. + - Select the **Add permissions** button at the bottom. +1. In the **Manifest** section, make sure to change the value fore *acceptedTokenVersion* to **2**. + +#### Configure the client app (Python Django Web App) to use your app registration + +Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code. + +> In the steps below, "ClientID" is the same as "Application ID" or "AppId". + +1. In the 'DjangoUI' sub-folder, open the `DjangoUI\production.env` file and make a copy in the same directory called `development.env`. In this new file: +2. Find the key `CLIENT_ID` and replace the existing value with the application ID (clientId) of `Python Django Web App` app copied from the Azure portal. +3. Find the key `CLIENT_SECRET` and replace the existing value with the key you saved during the creation of `Python Django Web App` copied from the Azure portal. +4. Find the key `DJANGO_SECRET_KEY` and replace the existing value with a Secret Key. +5. Find the key `AUTHORITY` and replace the `ReplaceWithTenantID` portion with the tenant Id value that you obtained from the portal. +6. Find the key `SCOPE` and replace the `Flask_API_Client_ID` portion of the existing value with with the client ID of the Flask app that you had copied from that portal in the previous section. +7. Find the key `API_SCOPE` and replace the `Flask_API_Client_ID` portion of the existing value with with the client ID of the Flask app that you had copied from that portal in the previous section. + +#### Configure Known Client Applications for service (Python Flask Web API) + +For a middle tier Web API (`Python Flask Web API`) to be able to call a downstream Web API, the middle tier app needs to be granted the required permissions as well. +However, since the middle tier cannot interact with the signed-in user, it needs to be explicitly bound to the client app in its **Microsoft Entra** registration. +This binding merges the permissions required by both the client and the middle tier Web Api and presents it to the end user in a single consent dialog. The user then consent to this combined set of permissions. + +To achieve this, you need to add the **Application Id** of the client app, in the Manifest of the Web API in the `knownClientApplications` property. Here's how: + +1. In the [Azure portal](https://portal.azure.com), navigate to your `Python Flask Web API` app registration, and select **Manifest** section. +1. In the manifest editor, change the `"knownClientApplications": []` line so that the array contains the Client ID of the client application (`Python Django Web App`) as an element of the array. + + For instance: + + ```json + "knownClientApplications": ["your-django-app-id"], + ``` + +1. **Save** the changes to the manifest. + +## Running the sample + +There are two applications in this repository. You must run both of them to use the sample. + +### FlaskAPI + +To run the FlaskAPI application, you can either use the command line or VS Code. For command line use, navigate to `/FlaskAPI` folder. Be sure your virtual environment with dependencies is activated ([Prerequisites](#prerequisites)). + +- On Linux/OSX via the terminal: + + ```Shell + # start from the folder in which the sample is cloned into + cd FlaskAPI + export FLASK_ENV="development" + export FLASK_APP="main.py" + flask run + ``` + +- On Windows: + + ```PowerShell + # start from the folder in which the sample is cloned into + cd FlaskAPI + $env:FLASK_ENV="development" + $env:FLASK_APP="main.py" + flask run + ``` + +- On VS Code: + + 1. Open VS Code in the FlaskAPI project folder + 2. Open the command palette (ctrl+shift+P) and select `Python: Select Interpreter` and choose the virtual environment that you installed the project into. + 3. Run the **Python: Flask** launch configuration + +### DjangoUI + +To run the DjangoUI application, you can either use the command line or VS Code. For command line use, navigate to `/DjangoUI` folder. Be sure your virtual environment with dependencies is activated ([Prerequisites](#prerequisites)). + +- On Linux/OSX via the terminal: + + ```Shell + # start from the folder in which the sample is cloned into + cd DjangoUI + export ENVIRONMENT="development" + python manage.py migrate + python manage.py runserver localhost:8000 + ``` + +- On Windows: + + ```PowerShell + # start from the folder in which the sample is cloned into + cd DjangoUI + $env:ENVIRONMENT="development" + python manage.py migrate + python manage.py runserver localhost:8000 + ``` + +- On VS Code: + + 1. Open VS Code in the DjangoUI project folder + 2. Open the command palette (ctrl+shift+P) and select `Python: Select Interpreter` and choose the virtual environment that you installed the project into. + 3. Run the **Python: Django: Run Migrations** launch configuration + 4. Run the **Python: Django** launch configuration + +### Open your browser + +Navigate to [http://localhost:8000](http://localhost:8000) in your browser (**Don't use** use 127.0.0.1) + +## Explore the sample + +- After starting the application, Follow the instructions on the next page to sign in with an account in the Microsoft Entra tenant. +- On the consent screen, note the scopes that are being requested. +- Note the screen should now display a JSON based array of all Azure subscriptions you have access to + +> :information_source: Did the sample not work for you as expected? Then please reach out to us using the [GitHub Issues](../../../issues) page. + +## We'd love your feedback! + +Were we successful in addressing your learning objective? Consider taking a moment to [share your experience with us](https://forms.office.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbR0TE6SUcVQZKq_Wiw2LQUqdUOUdIUExaSEk2TUFUQTNJSEJaMEpWQzZVQS4u). + +## About the code + +This sample uses the [Microsoft Authentication Library \(MSAL\) for Python](https://github.com/AzureAD/microsoft-authentication-library-for-python) to sign in a user and obtain a token for the Flask Web API, which will in turn call the Azure Management API on the user's behalf. The Django Web App first checks to see if the user has signed in before by attempting to find the user in the in-memory token cache. If the user is found, the MSAL acquire_token_silent function is first called to pull the user's access token from the token cache and then the Flask API is called. If the user is not found in the token cache, they will be redirect to account/login to sign in. Once called, the Flask API will validate the access token, using the validation logic from [authorization.py](/FlaskAPI/helpers/authorization.py), and will in turn create a new access token using the MSAL acquire_token_on_behalf_of function. This token will then be used to call the Azure Management API, subscriptions endpoint, on-behalf-of the user who initiated the request from the Django Web App. + +## More information + +- [Microsoft identity platform (Microsoft Entra for developers)](https://docs.microsoft.com/azure/active-directory/develop/) +- [Overview of Microsoft Authentication Library (MSAL)](https://docs.microsoft.com/azure/active-directory/develop/msal-overview) +- [Quickstart: Register an application with the Microsoft identity platform (Preview)](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app) +- [Quickstart: Configure a client application to access web APIs (Preview)](https://docs.microsoft.com/azure/active-directory/develop/quickstart-configure-app-access-web-apis) +- [Understanding Microsoft Entra application consent experiences](https://docs.microsoft.com/azure/active-directory/develop/application-consent-experience) +- [Understand user and admin consent](https://docs.microsoft.com/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant#understand-user-and-admin-consent) +- [Application and service principal objects in Microsoft Entra ID](https://docs.microsoft.com/azure/active-directory/develop/app-objects-and-service-principals) +- [National Clouds](https://docs.microsoft.com/azure/active-directory/develop/authentication-national-cloud#app-registration-endpoints) +- [MSAL code samples](https://docs.microsoft.com/azure/active-directory/develop/sample-v2-code) + +For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see [Authentication Scenarios for Microsoft Entra](https://docs.microsoft.com/azure/active-directory/develop/authentication-flows-app-scenarios). + +## Community Help and Support + +Use [Stack Overflow](http://stackoverflow.com/questions/tagged/msal) to get support from the community. +Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. +Make sure that your questions or comments are tagged with [`azure-active-directory` `azure-ad-b2c` `ms-identity` `adal` `msal`]. + +If you find a bug in the sample, raise the issue on [GitHub Issues](../../../issues). + +To provide feedback on or suggest features for Microsoft Entra ID, visit [User Voice page](https://feedback.azure.com/forums/169401-azure-active-directory). + +## Contributing + +If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md). + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/on-behalf-of-flow/cgmanifest.json b/on-behalf-of-flow/cgmanifest.json new file mode 100644 index 0000000..3254635 --- /dev/null +++ b/on-behalf-of-flow/cgmanifest.json @@ -0,0 +1,13 @@ +{"Registrations":[ + { + "component": { + "type": "git", + "git": { + "repositoryUrl": "https://github.com/Azure-Samples/ms-identity-python-webapi-azurefunctions/blob/master/Function/secureFlaskApp/__init__.py", + "commitHash": "f88a9466bb0ec0ce20c6742a21bc47a16e13652e" + } + } + } + ], + "Version": 1 +} \ No newline at end of file