<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AlbinR on Medium]]></title>
        <description><![CDATA[Stories by AlbinR on Medium]]></description>
        <link>https://medium.com/@albinronnkvist?source=rss-65dd4aa899d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by AlbinR on Medium</title>
            <link>https://medium.com/@albinronnkvist?source=rss-65dd4aa899d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:39:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@albinronnkvist/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Azure AD Client Credential Flow with ASP.NET Core Web API]]></title>
            <link>https://medium.com/@albinronnkvist/azure-ad-client-credential-flow-with-asp-net-core-web-api-f2a1f7b29532?source=rss-65dd4aa899d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2a1f7b29532</guid>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[webapi]]></category>
            <dc:creator><![CDATA[AlbinR]]></dc:creator>
            <pubDate>Sun, 11 Sep 2022 15:25:28 GMT</pubDate>
            <atom:updated>2022-09-11T15:25:28.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure AD Client Credentials Flow with ASP.NET Core Web API</h3><p>This tutorial will show you how to use the <a href="http://aka.ms/aadv2">Microsoft identity platform</a> (Azure AD) to access data from a protected Web API, without the need of user interaction. <br>We will use the <a href="https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow">OAuth 2 client credentials flow</a> to acquire an <a href="https://aka.ms/access-tokens">Access Token</a>, which is then used to call the protected Web API. This flow is commonly used for server-to-server interactions that must run in the background, without interaction with a user. These types of applications are often referred to as <em>daemons</em>. An example would be a Web API calling another Web API.</p><p>Inspired by: <a href="https://dev.to/alebrozzo/webapi-to-webapi-calls-authenticated-by-azure-2plg">https://dev.to/alebrozzo/webapi-to-webapi-calls-authenticated-by-azure-2plg</a></p><h3>Overview</h3><ol><li><strong>Azure AD setup:</strong> we will first work within the Azure Portal to setup Azure AD <em>App Registrations</em>.</li><li><strong>Web API setup and configuration:</strong> we will create a default ASP.NET Core Web API application and configure it to use Azure AD for authentication.</li><li><strong>Acquire Access Token:</strong> we will then use Postman to acquire an Access Token from Azure AD.</li><li><strong>Send requests to Web API with Access Token:</strong> lastly we will use Postman again to send a request, with the Access Token in the Authorization Header, to the Web API.</li></ol><h3>1. Azure AD setup</h3><p>We will setup two <em>app registrations </em>in Azure AD, one for the <em>Client(Postman)</em> and one for the <em>Resource Server(Web API)</em>. You can think of an Azure AD Application as a representation of your “real” application in Azure AD.</p><p>In the context of OAuth 2.0, a <em>resource server </em>(Web API) is an application that protects resources via OAuth tokens. These tokens are issued by an <em>authorization server </em>(Azure AD), typically to a <em>client application </em>(Postman). The job of the <em>resource server</em> is to validate the token before serving a resource to the <em>client</em>. <br><a href="https://www.baeldung.com/spring-security-oauth-resource-server">Read more about the terminology</a>.</p><p>Moving forward I will refer to Postman as “Client” (even though it is not a typical front-end client application). Note that Postman could be replaced with any other daemon application, like another Web API. <br>I will refer to the protected Web API we want to access as “Resource Server”.<br>And lastly Azure AD is the “Authorization Server”.</p><p><strong>Step 1.1: create app registrations</strong></p><ol><li>Login to Azure Portal and go to “Azure Active Directory”</li><li>In the menu on the left, go to “App registrations”</li><li>Click on “New registration”</li><li>Register an application<br>- Name: “Client”<br>- Supported account types: “Accounts in this organizational directory only (Default Directory only — Single tenant)”<br>- Ignore the Redirect URI, just leave it empty<br>- Click “Register”</li></ol><p>Repeat these steps for the Resource Server as well, I named it “ResourceServer”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpG4_RcKac26aJOmAk1IfA.png" /><figcaption>Register an application</figcaption></figure><p><strong>Step 1.2: create a secret in the <em>Client</em> registration</strong></p><ol><li>Go to the <em>Client</em> registration you created earlier</li><li>In the menu on the left, go to “Certificates &amp; secrets”</li><li>Click on “New client secret”<br>- Enter a name of your choice<br>- Enter an expiration date of your choice<br>- Click “Add”</li><li>Copy the value of the secret and store it in a safe location. <em>You will not be able to see nor copy the value again from the portal after leaving or refreshing this page.</em></li></ol><p>We have now created credentials that the <em>Client </em>can use to authenticate itself. Later when we make the call for obtaining an Access Token, the Client’s <em>Application (client) ID</em> together with this <em>secret</em>, becomes the credentials.</p><blockquote><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow">The OAuth 2.0 client credentials grant flow permits a web service (confidential client) to use its own credentials, instead of impersonating a user, to authenticate when calling another web service.</a></blockquote><p><em>Note that in a production environment, it is recommended to use certificates instead of secrets.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26aYzVdIdCXij7wZOqDKbA.png" /><figcaption>Create a secret</figcaption></figure><p><strong>Step 1.3: expose the <em>ResourceServer</em> registration</strong></p><ol><li>Go to the <em>ResourceServer </em>registration</li><li>In the menu on the left, go to “Expose an API”</li><li>At the top of the page, where it says “Application ID URI”, click “set”.<br>- Use the default value of “api://&lt;application-client-id&gt;” or another <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-app-manifest#identifieruris-attribute">supported App ID URI pattern</a>. <br>- Click “Save”</li></ol><p>The Application ID URI is a URI that uniquely identifies the application in your Azure Active Directory. This will later allow the <em>Client </em>registration to access this <em>ResourceServer </em>registration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hr2-jh962FRGjff1mainkA.png" /><figcaption>Expose an API</figcaption></figure><p><strong>Step 1.4: create an App Role in the <em>ResourceServer</em> registration</strong></p><ol><li>Go to the <em>ResourceServer </em>registration</li><li>In the menu on the left, go to “App roles”</li><li>At the top of the page, click “Create app role”<br>- Display name: any name of your choice, I went with “Weather.Read”<br>- Allow member types: “Applications”<br>- Value: “Weather.Read”<br>- Description: “Readers have the ability to read data”<br>- If not already checked, check the box “Do you want to enable this app role?”<br>- Click “Apply”</li></ol><p>This App Role will be used in the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cL0RNgZjq5ttOosAgpcBjQ.png" /><figcaption>Create App Role</figcaption></figure><p><strong>Step 1.5: add an application permission in the <em>Client </em>registration</strong></p><ol><li>Go to the <em>Client </em>registration</li><li>In the menu on the left, go to “API permissions”</li><li>Click “Add a permission”<br>- Select an API: “My APIs”<br>- Select “ResourceServer”<br>- What type of permissions does your application require?: select “Application permissions”<br>- Select the “Weather.Read” permission<br>- Click “Add permission”</li><li>Click “Grant admin consent for &lt;your-directory-name&gt;” and “Yes”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dd-KnAfCDLA7tViw4SV4A.png" /><figcaption>Add application permission</figcaption></figure><p>In step 1.4 the <em>ResourceServer </em>registration exposed an App Role called “Weather.Read”, which in this case specifies read only access that the <em>Resource Server (Web API)</em> has to enforce later in the code.<br>So this role specifies a portion of the <em>Resource Server’s</em> functionality that other applications can use.</p><p>In this step(1.5) we specified that the <em>Client </em>registration should get permission to read, by adding an application permission that references the App Role “Weather.Read”. <br>So the <em>Client </em>has now been granted permission to use that specific portion of the <em>Resource Server’s</em> functionality.</p><p>An important part to mention is that an administrator has to approve this permission for the <em>Client </em>to gain access. The <em>Client </em>should only have permission to do the things it needs / should have access to, and it is the administrators role to make sure of that. <br><a href="http://An application permission is granted to an application by an organization&#39;s administrator, and can be used only to access data owned by that organization and its employees.">Read more about Application Permissions and App Roles</a>. <br><a href="https://docs.microsoft.com/en-us/graph/auth-v2-service#2-configure-permissions-for-microsoft-graph">You could also read more here and see an example using Microsoft Graph</a>.</p><p>Later we will see that the “Weather.Read” role is added to the <em>roles claim</em> in the Access Token. This claim can be used by the <em>Resource Server (Web API)</em> to authorize the<em> Client (Postman)</em> requests.</p><h3>2. <strong>Web API setup and configuration</strong></h3><p>In this series of steps we will create a new ASP.NET Core Web API project (.NET 6) and configure it to use Azure AD for authentication.</p><p><strong>Step 2.1: create the Web API application<br></strong>If you don’t already have a Web API project, create a new “ASP.NET Core Web API” project from Visual Studio.<br>Or using dotnet CLI: “<em>dotnet new webapi --name &lt;your-project-name&gt;</em><strong>”</strong></p><p><strong>Step 2.2: add configuration in appsettings.json</strong></p><p>Add the following section in appsettings.json:</p><pre>&quot;AzureAd&quot;: {<br>    &quot;Instance&quot;: &quot;https://login.microsoftonline.com/&quot;,<br>    &quot;TenantId&quot;: &quot;&lt;your-tenant-id&gt;&quot;,<br>    &quot;ClientId&quot;: &quot;&lt;your-client-id&gt;&quot;, // from ResourceServer registration<br>}</pre><ul><li>Instance: the cloud instance for Azure public cloud</li><li>TenantId: the id for your tenant (the Azure AD instance your applications are registered within)</li><li>ClientId: the <em>Application (client) ID</em> of the <em>ResourceServer </em>registration</li></ul><p>The “TenantId” and “ClientId” can be found on the <em>overview page</em> in the <em>ResourceServer </em>registration in Azure Portal. The “Instance” can just be copy-pasted from this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mtk4s-gDKwLgNBS6KXROIQ.png" /><figcaption>Find TenantId and ClientId (+ Application ID URI)</figcaption></figure><p><strong>Step 2.3: add NuGet packages</strong><br>The only package we need is <em>Microsoft.Identity.Web.<br></em>Install it with dotnet CLI:<em> </em>“<em>dotnet add package</em> <em>Microsoft.Identity.Web</em>”</p><p><strong>Step 2.4: configure services in Program.cs</strong><br>Depending on your setup you would either do this in Program.cs or Startup.cs. In this example I use Program.cs:</p><pre>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)     .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(&quot;AzureAd&quot;));</pre><p>Here we say that we want to use the Microsoft identity platform (Azure AD) and the JWT Bearer Default scheme for authentication. We have to specify the configuration from the “AzureAd” section in appsettings.json.</p><p><strong>Step 2.5: add authentication and authorization middleware to the request pipeline</strong></p><pre>app.UseAuthentication();<br>app.UseAuthorization();</pre><p><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0#middleware-order">Remember that the order in which you register the middleware is important</a>.</p><p><strong>Step 2.6: add Authorize attribute on controller or action-method</strong></p><pre>[Authorize(Roles = &quot;<a href="https://portal.azure.com/#">Weather.Read</a>&quot;)] // &lt;-- add Authorize &amp; a role<br>[HttpGet(Name = &quot;GetWeatherForecast&quot;)]<br>public IEnumerable&lt;WeatherForecast&gt; Get()<br>{<br>  ...<br>}</pre><p>Now the Web API endpoint is protected and can only be accessed by an authorized client that has the “Weather.Read” role.<br>This role will be read from the role claim in the Access Token. But as of now, we have not yet acquired an Access Token. We will do that in the next step.</p><h3><strong>3. Acquire Access Token</strong></h3><p>We will use Postman to send a request to the Authorization Server (Azure AD) to acquire an Access Token. View the structure of the request below or <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#first-case-access-token-request-with-a-shared-secret">read the Microsoft documentation</a>.</p><p><strong>POST-request to URL:</strong> <br><a href="https://login.microsoftonline.com/%7Btenant-id%7D/oauth2/v2.0/token">https://login.microsoftonline.com/<em>&lt;tenant-id&gt;</em>/oauth2/v2.0/token</a></p><p><strong>Headers:</strong></p><ul><li>Host: login.microsoftonline.com</li><li>Content-Type: application/x-www-form-urlencoded</li></ul><p><strong>Body (x-www-form-urlencoded):</strong></p><ul><li><strong>client_id: <em>&lt;Application (client) Id&gt;</em></strong><em> <br></em>(value can be found in the <em>Client </em>registration)</li><li><strong>scope:</strong> <strong><em>&lt;Application ID URI&gt;</em>/.default</strong> <br>(value can be found in the <em>ResourceServer </em>registration)</li><li><strong>client_secret: <em>&lt;client secret&gt;</em></strong><em> <br></em>(the secret you created in step 1.2 above)</li><li><strong>grant_type: client_credentials</strong></li></ul><p>The <em>.default scope</em> is used to initiate admin consent. Its use is required in the <em>client credentials flow</em>.</p><p>In Postman it would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tw4--D1DU7QLgiDjo886Ew.png" /><figcaption>Request Access Token from Postman</figcaption></figure><p>When you send the request you will get an Access Token back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9AiAL99AczJinq2OhX1Jw.png" /><figcaption>Acquire Access Token in Postman</figcaption></figure><p>The Authorization Server (Azure AD) has now successfully verified the <em>Client</em> by its credentials (client_id &amp; client_secret) and sent back an Access Token that can be read from the “access_token” key in the response. The Access Token is just a JWT with information about the <em>Client</em>, specified as claims.</p><p>Copy the looong value from the “access_token” key. Paste it in the debugger on <a href="https://jwt.io/">https://jwt.io/</a> and view the content. You should see a “roles” claim with the value ”Weather.Read”. <br>If everything worked as expected, you now have an Access Token that will give you access to the Resource Server with read only rights. Lets try it out in the next step!</p><h3><strong>4. Send requests to Web API with Access Token</strong></h3><p>In the last step we simply add the<em> Access Token</em> to the <em>Authorization Header</em> and send a request to the Resource Server (Web API):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qosNY7VjbX95tezSr_W24A.png" /></figure><p>Don’t forget to:</p><ul><li>Start the Web API</li><li>Enter the correct URL (https://&lt;your-domain&gt;:&lt;your-port&gt;/&lt;your-endpoint&gt;)</li><li>Add “Bearer” before the token to specify its a Bearer token, since that is the scheme the Web API is expecting.</li></ul><p>If everything works as expected, you can now access the <em>Resource Server</em> (the protected Web API) from a<em> Client</em> (Postman or any other daemon application, like another Web API) using an Access Token acquired from an <em>Authorization Server</em> (Azure AD).</p><h3><strong>Sources for further exploration:</strong></h3><ul><li>Docs: <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow">Microsoft identity platform and the OAuth 2.0 client credentials flow</a></li><li>Docs:<a href="https://docs.microsoft.com/en-us/azure/active-directory-b2c/client-credentials-grant-flow?pivots=b2c-user-flow"> Set up OAuth 2.0 client credentials flow in Azure Active Directory B2C</a></li><li>Docs: <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-overview">Scenario: Daemon application that calls web APIs</a></li><li>Video: <a href="https://www.youtube.com/watch?v=7qt8asY33Aw&amp;ab_channel=ConceptsWork">Oauth 2.0 Client Credential Flow | Microsoft Graph</a></li><li>Video: <a href="https://www.youtube.com/watch?v=59YwW8FrLm8&amp;ab_channel=AzurePowerLunch">API Authentication with OAuth using Azure AD</a></li><li>Article: <a href="https://dev.to/425show/just-what-is-the-default-scope-in-the-microsoft-identity-platform-azure-ad-2o4d">Just what *is* the /.default scope in the Microsoft identity platform &amp; Azure AD?</a></li><li>Docs: <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope">The .default scope</a></li><li>Docs: <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps">Add app roles to your application and receive them in the token</a></li><li>Article: <a href="https://dotnetplaybook.com/secure-a-net-core-api-using-bearer-authentication/">Secure a .NET Core API using Bearer Authentication</a></li><li>Article: <a href="https://codemilltech.com/lets-talk-about-azure-ad/">LET’S TALK ABOUT AZURE AD AND MICROSOFT IDENTITY PLATFORM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2a1f7b29532" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>