简体   繁体   English

如何将 Azure Active Directory 身份验证添加到 Razor Pages 应用程序?

[英]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 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.以下教程展示了如何将 Azure Active Directory 身份验证添加到 MVC 应用程序。 I got the sample MVC app to work.我让示例 MVC 应用程序工作。

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.我将本教程中的所有必要代码复制到 Razor Pages 应用程序(Program.cs 和 Startup.cs)中,但我没有收到任何身份验证提示。 Does that mean Razor Pages are not supported?这是否意味着不支持 Razor 页面? Or am I doing something wrong?还是我做错了什么?

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

Basically, you need folowing 3 things in your code.基本上,您需要在代码中遵循 3 件事。

  1. Following changes into your ConfigurationServices.对您的 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 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确保您在 Startup.cs 中的 Configure 方法中有以下代码
   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 核心应用程序,您将完成所有工作并为您准备好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM