joym8
joym8

Reputation: 4212

How to add Azure Active Directory authentication to a Razor Pages app?

From what I understand you create an Razor Pages app in Visual Studio 2019 by doing New Project > ASP.NET Core Web Application > [provide app name] > Web Application

The following tutorial shows how to add Azure Active Directory authentication to a MVC app. I got the sample MVC app to work.

I replicated all necessary code from this tutorial into a Razor Pages app (Program.cs and Startup.cs), but I don't get any authentication prompt. Does that mean Razor Pages are not supported? Or am I doing something wrong?

https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-webapp

Upvotes: 3

Views: 4345

Answers (1)

Shirin
Shirin

Reputation: 168

Basically, you need folowing 3 things in your code.

  1. Following changes into your ConfigurationServices.
       public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.AddRazorPages().AddMvcOptions(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
        }
  1. appsettings.json
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "<Your Domain>",
    "TenantId": "<Your TenantId>",
    "ClientId": "<ClientId>",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

  1. Make sure you have below code into Configure method in Startup.cs
   app.UseAuthentication();
   app.UseAuthorization();

Or if you create your dotnet core application using below command, you will get everything done and ready for you.

dotnet new razor --auth SingleOrg --client-id <applicationId> --tenant-id <domaintenantid> --domain <domain>

Upvotes: 9

Related Questions