【问题标题】:How to add Azure Active Directory authentication to a Razor Pages app?如何将 Azure Active Directory 身份验证添加到 Razor Pages 应用程序?
【发布时间】:2020-11-10 05:38:30
【问题描述】:

据我了解,您通过执行 New Project > ASP.NET Core Web Application > [provide app name] > Web Application 在 Visual Studio 2019 中创建 Razor Pages 应用程序

以下教程展示了如何将 Azure Active Directory 身份验证添加到 MVC 应用程序。我得到了示例 MVC 应用程序。

我将本教程中的所有必要代码复制到了 Razor Pages 应用程序(Program.cs 和 Startup.cs)中,但我没有收到任何身份验证提示。这是否意味着不支持 Razor 页面?还是我做错了什么?

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

【问题讨论】:

    标签: asp.net-mvc azure asp.net-core azure-active-directory razor-pages


    【解决方案1】:

    基本上,您需要在代码中遵循 3 件事。

    1. 在您的 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. 确保您在 Startup.cs 中的 Configure 方法中有以下代码
       app.UseAuthentication();
       app.UseAuthorization();
    

    或者,如果您使用以下命令创建 dotnet 核心应用程序,您将完成所有工作并为您准备好。

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

    【讨论】:

    • 由 VS 创建的 Razor Pages 应用程序没有附带任何控制器。你的意思是我需要添加新的控制器吗?在名为 Controllers 的文件夹下?
    • 对不起,我虽然你有 MVC Web 应用程序。我修改了我原来的答案。
    • 很棒的反应,简单/精确和准确。我能够关注并实施authentication。在我的场景中,只有一个页面需要authentication,而其他页面不需要。如何从请求authentication 中排除其他页面。
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多