简体   繁体   English

Azure AD 未在 .NET Core 3.1 中进行身份验证

[英]Azure AD Not Authenticating in .NET Core 3.1

I'm trying to get Azure AD working in an existing application.我正在尝试让 Azure AD 在现有应用程序中工作。 I've followed the instructions and looked at the sample code from Microsoft's site ( https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-webapp ) with no luck.我已经按照说明查看了来自 Microsoft 站点( https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-webapp )的示例代码,没有运气。 The sample code is using .NET Core 2.1.示例代码使用 .NET Core 2.1。 I can get it to work with .NET Core 2.1 but 3.1 is throwing a fit for a couple reasons.我可以让它与 .NET Core 2.1 一起使用,但 3.1 因几个原因而变得不合适。

  1. Compared to sample code one needs to set the EnableEndpointRouting to false.与示例代码相比,需要将 EnableEndpointRouting 设置为 false。
  2. Compared to sample code I tried removing the set compatibilityversion on AddMvc and also tried using it as being set to 3.0.与示例代码相比,我尝试删除 AddMvc 上的设置兼容性版本,并尝试将其设置为 3.0。

When I run it in .NET Core 3.1 all it does is load the page and never calls out/perform the authentication and is behaving as if there is not Authorize tag on the controller.当我在 .NET Core 3.1 中运行它时,它所做的只是加载页面并且从不调用/执行身份验证,并且表现得好像控制器上没有 Authorize 标记。

I have an Authorize tag on the class level in controller.我在控制器的类级别上有一个 Authorize 标签。

Startup.cs:启动.cs:

...
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";
                options.TokenValidationParameters.ValidateIssuer = false;
            });

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
                options.EnableEndpointRouting = false;
            });

Then down below in the Configure function:然后在下面的配置功能中:

...
app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

Then in my appsettings.json I have:然后在我的 appsettings.json 我有:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "domain.onmicrosoft.com",
    "TenantId": "guid",
    "ClientId": "guid",
    "CallbackPath": "/signin-oidc"
  },
...

My question is why is it treating the requests as if their is no authentication?我的问题是为什么它将请求视为没有身份验证? I have also tried using the UseAuthorization below the UseAuthentication.我还尝试使用 UseAuthentication 下面的 UseAuthorization。

Thanks!谢谢!

According to my test, if you want to configure Azure AD for .net core 3.1 web app, please refer to the following steps根据我的测试,如果要为.net core 3.1 web app配置Azure AD,请参考以下步骤

  1. Register Azure AD web application 注册 Azure AD Web 应用程序

  2. Configure application配置应用程序

    a.一种。 Install SDK Microsoft.AspNetCore.Authentication.AzureAD.UI安装 SDK Microsoft.AspNetCore.Authentication.AzureAD.UI

     <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
      </PropertyGroup>

      <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="3.1.1" />
      </ItemGroup>

    </Project>

b.Update appsettings.json更新 appsettings.json

      "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "domain.onmicrosoft.com",
    "TenantId": "guid",
    "ClientId": "guid",
    "CallbackPath": "/signin-oidc"
  },
...  

c. C。 Update startup.cs更新启动.cs

  • add the following code in ConfigureServices functionConfigureServices函数中添加以下代码

    public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Unspecified; }); services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => Configuration.Bind("AzureAd", options)); services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.Authority = options.Authority + "/v2.0/"; options.TokenValidationParameters.ValidateIssuer = false; }); services.AddControllersWithViews(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); services.AddRazorPages(); }
  • Add the following code in Configure FunctionConfigure函数中添加以下代码

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
     {
        ...
         app.UseHttpsRedirection();
         app.UseStaticFiles();

         app.UseRouting();

         app.UseCookiePolicy();
         app.UseAuthentication();
         app.UseAuthorization();

         app.UseEndpoints(endpoints =>
         {
             endpoints.MapControllerRoute(
                 name: "default",
                 pattern: "{controller=Home}/{action=Index}/{id?}");
         });
     }

在此处输入图片说明

For more details, please refer to the sample更多详情,请参考样本

暂无
暂无

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

相关问题 .NET Core Web Api Azure AD and Swagger not authenticating - .NET Core Web Api Azure AD and Swagger not authenticating ASP.NET Core 3.1 Azure AD 身份验证抛出 OptionsValidationException - ASP.NET Core 3.1 Azure AD Authentication throws OptionsValidationException 使用Azure AD进行身份验证时.NET Core在中间件中不显示用户声明 - .NET Core does not show user claims in middleware when authenticating with Azure AD Azure 使用 .net 核心 3.1 中的 azure 活动目录(单租户)的广告身份验证和授权? - Azure Ad authentication and authorization using azure active directory (single tenant) in .net core 3.1? ASP.NET MVC Core 3.1 中的自定义用户数据与 Azure AD 身份验证? - Custom User data in ASP.NET MVC Core 3.1 with Azure AD Authentication? 使用来自 Azure AD 的承载令牌保护 ASP.Net Core 3.1 API - Secure ASP.Net Core 3.1 API with Bearer Tokens from Azure AD .Net Core 3.1 - 如何为 Azure AD B2C 生成注册链接? - .Net Core 3.1 - how to generate Sign Up link for Azure AD B2C? 我们可以申请 ASP.NET Core 3.1 MVC Azure AD 认证使用 HTTP - Can we apply ASP.NET Core 3.1 MVC Azure AD authentication using HTTP ASP.NET Core 3.1 如何使用 Azure AD B2C 返回 401 Unauthorized 而不是 Challenge - ASP.NET Core 3.1 how to return 401 Unauthorized instead of Challenge with Azure AD B2C ASP.NET Core 3.1 + Azure AD 身份验证 - 如何披露“隐藏的电子邮件” - ASP.NET Core 3.1 + Azure AD Authentication - How to disclose “hidden email”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM