Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Requesting Microsoft Defender HTTP API with .NET and Refit

Requesting Microsoft Defender HTTP API with .NET and Refit
August 26, 2022 3 min read BEN ABT
Microsoft Defender API Refit

This article was written in 2022. Versions, tools and recommendations may have changed since then. Newer posts are collected under Blog.

The Microsoft Defender API - or Azure Security Center API - is an interface to obtain security-related information from its M365 or Azure tenant.

Attention: this API is still in preview - and you can definitely feel this. Endpoints or formats change regularly!

This API is therefore not part of the Azure SDK for .NET. It is therefore necessary to develop your own client. In principle, all endpoints of the Microsoft Defender API are OData-capable, but you can simply omit some of them.

Microsoft Defender

Unfortunately, Microsoft Defender is also a product that does not have a unified naming.
In the documentation, Microsoft Defender is listed as a Security Topic in the M365 universe . However, the API Audience is called Security Center (https://api.securitycenter.microsoft.com), which is a different Security Center than Azure Security Center!

Permissons

All necessary permissions are documented in the Microsoft Defender documentation.

In the case of Exposure Score , the API permission Score.Read.All from WindowsDefenderATP is required.

Refit

Refit is an open source project under the .NET Foundation hat that is perfect for any kind of HTTP based APIs.

The big advantage is that you only need to describe the API with the help of an interface; the actual code is generated during compilation using this contract (based on source code generators ).

Refit takes care of all the HTTP handling, as well as serializing it into a response model, which you then only need to specify as a return parameter.

C#
 1// API Response Model
 2public record class MicrosoftDefenderExposureScoreResponseModel
 3    (DateTimeOffset Time, double Score);
 4
 5// Refit API Contract
 6public interface IMicrosoftDefenderHttpApiClient
 7{
 8    [Get("/api/exposureScore")]
 9    Task<MicrosoftDefenderExposureScoreResponseModel> GetExposureScore(
10        [Authorize("Bearer")] string bearerToken);
11}

Refit offers several ways to enrich requests with bearer tokens or authentication headers.
On the one hand, there are handlers that authenticate each request immediately; however, the token can also be supplied dynamically using parameters.

In my case I have to query the exposure score of several tenants, so I cannot use an AuthHandler. I have to get the token manually.

C#
 1public class MicrosoftDefenderBearerTokenClientProvider
 2{
 3    private const string _authority = "https://login.microsoftonline.com";
 4    private const string _audience = "https://api.securitycenter.microsoft.com";
 5
 6    private static string[] s_scopes = new[] { $"{_audience}/.default" };
 7
 8    public async Task<AuthenticationResult> GetToken
 9        (string tenantId, string clientId, string secret)
10    {
11        IConfidentialClientApplication app =
12            ConfidentialClientApplicationBuilder
13                .Create(clientId).WithClientSecret(secret)
14                .WithAuthority($"{_authority}/{tenantId}").Build();
15
16        AuthenticationResult authResult =
17            await app.AcquireTokenForClient(s_scopes)
18                .ExecuteAsync().ConfigureAwait(false);
19
20        return authResult;
21    }
22}

The request

Now, in principle, all that is needed is two lines of code and we have full authenticated communication to the Microsoft Defender API with refit.

C#
 1public async Task Sample()
 2{
 3    string tenantId = "tenant id guid here";
 4    string clientId = "client id guid here";
 5    string clientSecret = "client secret string here";
 6
 7    // create client and token provider
 8    IMicrosoftDefenderHttpApiClient api =
 9        RestService.For<IMicrosoftDefenderHttpApiClient>
10            ("https://api.securitycenter.microsoft.com");
11    MicrosoftDefenderBearerTokenClientProvider provider = new();
12
13    // request token
14    AuthenticationResult auth = await provider
15        .GetToken(tenantId, clientId, clientSecret);
16
17    // call Microsoft Defender API
18    MicrosoftDefenderExposureScoreResponseModel model
19        = await api.GetExposureScore(auth.AccessToken);
20
21    Console.WriteLine("Score: " + model.Score);
22}

BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026
Problem Details in ASP.NET Core and .NET 11

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026
Resilience in .NET with Microsoft.Extensions.Resilience

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026
What Matters in ASP.NET Core 11

What Matters in ASP.NET Core 11

Sep 14, 2026

Tags

.NET (192) Csharp (96) ASP.NET Core (48) Azure (41) DevOps (17) Docker (14) Microsoft (14) EF Core (11) Microsoft MVP (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Security (9) Synology (9) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7) Bicep (6)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact