Microsoft 365 Consent Application

Overview

This application is a simple set of ASP.NET pages designed to facilitate the OAuth 2.0 authorization code grant flow for Microsoft 365 services. It allows a user to grant consent, and the application retrieves and securely stores a refresh token for offline access.

Authentication Flow & Consent

The process uses a standard OAuth 2.0 flow called the Authorization Code Grant. This is a secure way to allow an application to access data on a user's behalf without the application ever handling the user's password.

Flow Diagram


+-----------------+     1. Request Consent     +----------------------+     2. Log In & Grant      +---------------------------+
|  User's Browser | ------------------------> |  Web Application     | ---------------------> |   Microsoft Identity      |
|                 | <------------------------ |  (link.aspx)         | <--------------------- |   (Login & Consent Page)  |
+-----------------+     3. Redirect w/ Code   +----------------------+     4. Redirect Back     +---------------------------+
       |
       | 5. Exchange Code for Tokens
       v
+----------------------+
|  Web Application     |
|  (redirect.aspx)     | --- 6. POST Request w/ Code & Secret --> +---------------------------+
|                      | <-- 7. Return Refresh & Access Tokens --- |   Microsoft Identity      |
+----------------------+                                           |   (Token Endpoint)        |
                                                                   +---------------------------+

       |
       | 8. Save Refresh Token
       v
+----------------------+
|  refresh_token.txt   |
+----------------------+

Step-by-Step Explanation

  1. The user navigates to link.aspx.
  2. The web application redirects the user to a Microsoft identity login page, sending along its own Client ID.
  3. The user securely logs in with Microsoft and is shown the permissions the application is requesting (e.g., "Read your user profile"). The user grants consent.
  4. Microsoft redirects the user back to the application's specified redirect URI, redirect.aspx, providing a temporary, one-time-use authorization code.
  5. The server-side code in redirect.aspx takes this authorization code.
  6. It then makes a direct, back-channel request to the Microsoft identity token endpoint. This request includes the authorization code, its own Client ID, and its Client Secret (to prove its identity).
  7. Microsoft validates this information and returns a refresh token and an initial access token.
  8. The web application saves the permanent refresh token to refresh_token.txt for future use.

User-Side Cleanup (Revoking Consent)

The user who granted consent has full control and can revoke the application's permission at any time. Revoking consent will invalidate the refresh token, and the application will no longer be able to gain access.

How to Revoke Access:

  1. Go to the Microsoft "My Apps" portal: https://myapps.microsoft.com
  2. Sign in with the same account that granted the consent.
  3. Click on your profile picture or initials in the top-right corner, and select "Profile".
  4. In the profile view, select "Manage your apps".
  5. You will see a list of all applications you have granted permissions to. Find the application by its name (or Client ID) and click "Revoke permissions".

Once permissions are revoked, any attempt to use the old refresh token will fail with an "invalid_grant" error.

File Structure

  • link.aspx: The entry point of the application. This page presents the user with a button to initiate the consent process.
  • redirect.aspx: The redirect URI for the OAuth flow. It exchanges the authorization code for a refresh token and saves it to refresh_token.txt.
  • Web.config: The configuration file for the application. It securely stores the Client ID and Client Secret.
  • Get-AccessToken.ps1: A PowerShell script that watches for refresh_token.txt and automatically redeems the refresh token for an access token.
  • refresh_token.txt: A plain text file where the retrieved refresh token is stored.
  • access_token_*.txt: Text files containing access tokens, generated by the PowerShell script.

Configuration

Before running the application, you must configure your application's credentials in the Web.config file.

Is the Web.config File Secure?

Yes. Storing secrets in Web.config is a standard practice, and the file is protected by multiple layers of security:

  • IIS Request Filtering: The web server (IIS) has a built-in rule that explicitly blocks any direct web request for a file ending in .config. Any attempt to navigate to it will result in a "404 Not Found" error.
  • ASP.NET Handler: The ASP.NET framework itself is configured to treat .config files as code, not as content to be served. This prevents them from ever being displayed as plain text.

Important: You must replace the placeholder values with your actual Application (client) ID and Client Secret from the Azure Active Directory portal.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ClientId" value="d61307e8-4215-4825-a180-f1305fd294f0" />
    <add key="ClientSecret" value="YOUR_CLIENT_SECRET_HERE" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
</configuration>

Entra ID (Azure AD) App Registration

To get the required ClientId and ClientSecret, you must register the application in the Microsoft Entra admin center.

Registration Steps:

  1. Navigate to the Microsoft Entra admin center.
  2. Go to Identity > Applications > App registrations and select "New registration".
  3. Fill out the registration form with the following parameters:
    • Name: A descriptive name for your application (e.g., "WebApp Refresh Token App").
    • Supported account types: Select "Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)".
    • Redirect URI:
      • Select Web as the platform.
      • Enter the public URL for the redirect page: https://[your-domain]/applications/redirect.aspx.
  4. Click "Register".

Getting the Credentials:

  • Client ID: After registering, the Application (client) ID will be displayed on the application's "Overview" page. This is the value for the ClientId key in Web.config.
  • Client Secret:
    1. Go to the "Certificates & secrets" section for your app.
    2. Click "New client secret", give it a description, and set an expiration period.
    3. Crucial: Immediately after creation, copy the secret's Value (not the Secret ID). This is your only chance to see it. This value is for the ClientSecret key in Web.config.

Web Application Setup Guide

To run the ASP.NET application, you need a Windows server with Internet Information Services (IIS) enabled.

Prerequisites

  • Windows Server with IIS
  • .NET Framework 4.7.2 or later

Deployment Steps

  1. Copy the following files to your web directory (e.g., C:\inetpub\wwwroot\applications):
    • link.aspx
    • redirect.aspx
    • Web.config
  2. Open IIS Manager and ensure you have a web site pointing to the parent directory (e.g., `C:\inetpub\wwwroot`).
  3. Ensure the Application Pool for the site is configured to use .NET Framework v4.0 or later.
  4. In Azure Active Directory, when registering your application, ensure the Redirect URI is set to `https://[your-domain]/applications/redirect.aspx` and is configured as a "Web" platform.
  5. Fill in the `ClientId` and `ClientSecret` values in your Web.config file.

PowerShell Script Installation (C:\tokens)

This guide explains how to run the PowerShell script and its related files from the C:\tokens directory.

Installation Steps

  1. Create a new folder at C:\tokens.
  2. Copy the following files from the web application directory to C:\tokens:
    • Get-AccessToken.ps1
    • Web.config (this file contains the Client ID and Secret the script needs)
  3. Your C:\tokens directory should now contain both the script and its configuration file.

Running the Script from C:\tokens

  1. Open a new PowerShell terminal.
  2. Navigate to the new directory: cd C:\tokens
  3. Run the script: .\Get-AccessToken.ps1
  4. The script will now be running from C:\tokens and will watch for the refresh_token.txt file to be created, processing it automatically.

Automated Token Redemption

The Get-AccessToken.ps1 script provides a robust way to automatically redeem the refresh token. It includes several key features:

  • Processes Existing Files: If refresh_token.txt already exists when the script starts, it will be processed immediately.
  • Watches for New Files: The script watches for the creation of a new refresh_token.txt file.
  • Watches for Modifications: If an existing refresh_token.txt is updated or overwritten, the script will trigger and re-process it.

How to Use:

  1. Open a PowerShell terminal and navigate to the application directory.
  2. Run the script using the command: .\Get-AccessToken.ps1
  3. The script will process any existing token file and then continue watching for new files or changes.
  4. When a token is redeemed, the new access token will be saved to a file named access_token_#####.txt.

If you encounter an error about scripts being disabled, you may need to set the execution policy for the current process by running:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process