簡體   English   中英

Error: Internal server error in Azure AD authentication Web App deployed as docker container in Azure web App service

[英]Error : Internal server error in Azure AD authentication Web App deployed as docker container in Azure web App service

我有帶有 azure 廣告身份驗證的 aspnet core 2.1 web 應用程序。 當我以調試模式在本地運行我的應用程序時,一切都按預期工作。 而當我在 azure web 應用程序服務(Linux、Docker)中部署我的 web 應用程序時,它會在登錄后引發內部服務器錯誤 500 'txxxx。 下面是我的startup.cs和appsettings.json供參考

{ "身份驗證": { "ClientId": "我的客戶 ID",
"Authority": "https://login.microsoftonline.com/My tenant Id/",
"PostLogoutRedirectUri": "http://localhost:44372",
“CallbackPath”:“/signin-oidc”,“ClientSecret”:“”,“ResponseType”:“code id_token”}}

using System;
using System.Threading.Tasks;
using Core2AadAuth.Filters;
using Core2AadAuth.Options;
using Core2AadAuth.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace Core2AadAuth
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    private IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc(opts =>
      {
        opts.Filters.Add(typeof(AdalTokenAcquisitionExceptionFilter));
      }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

      //TODO: Set up Data Protection key persistence correctly for your env: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?tabs=aspnetcore2x
      //I go with defaults, which works fine in my case
      //But if you run on Azure App Service and use deployment slots, keys get swapped with the app
      //So you'll need to setup storage for keys outside the app, Key Vault and Blob Storage are some options
      services.AddDataProtection();

      //Add a strongly-typed options class to DI
      services.Configure<AuthOptions>(Configuration.GetSection("Authentication"));

      services.AddScoped<ITokenCacheFactory, TokenCacheFactory>();

      services.AddAuthentication(auth =>
      {
        auth.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
      })
      .AddCookie()
      .AddOpenIdConnect(opts =>
      {
        Configuration.GetSection("Authentication").Bind(opts);
        opts.Events = new OpenIdConnectEvents
        {
          OnRedirectToIdentityProvider = async n =>
          {
            n.ProtocolMessage.RedirectUri = "https://xxxxx.azurewebsites.net/signin-oidc";
            await Task.CompletedTask;
          },
          OnAuthorizationCodeReceived = async ctx =>
                {
                HttpRequest request = ctx.HttpContext.Request;
                      //We need to also specify the redirect URL used
                      string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                      //Credentials for app itself
                      var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

                      //Construct token cache
                      ITokenCacheFactory cacheFactory = ctx.HttpContext.RequestServices.GetRequiredService<ITokenCacheFactory>();
                TokenCache cache = cacheFactory.CreateForUser(ctx.Principal);

                var authContext = new AuthenticationContext(ctx.Options.Authority, cache);

                      //Get token for Microsoft Graph API using the authorization code
                      string resource = "https://graph.microsoft.com";
                AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                          ctx.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                      //Tell the OIDC middleware we got the tokens, it doesn't need to do anything
                      ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
              }
        };
      });

      services.Configure<HstsOptions>(o =>
      {
        o.IncludeSubDomains = false;
        o.Preload = false;
        o.MaxAge = TimeSpan.FromDays(365);
      });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      else
      {
        //Outside dev, require HTTPS and use HSTS
        app.UseHttpsRedirection();
        app.UseHsts();
      }



      app.UseStaticFiles();

      app.UseAuthentication();

      app.UseMvcWithDefaultRoute();
    }
  }
}

登錄后出錯

2021-05-02T09:33:20.315827397Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost 1 2021-05-02T09:33:20.315907498Z 請求開始 HTTP/1.1 GET Z80791B3AE70092FACB888:43AE70092FACB888 /mwp4.azurewebsites.net/ 2021-05-02T09:33:20.608016175Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3] 2021-05-02T09:33:20.608738579Z路線與 {action = "Index", controller = "Home"} 匹配。 在 controller Core2AadAuth.Controllers.HomeController (Core2AadAuth) 上執行帶有簽名 Microsoft.AspNetCore.Mvc.IActionResult Index() 的 controller 操作。 2021-05-02T09:33:20.745331263Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker 1 2021-05-02T09:33:20.745368864Z 執行動作方法Core2AadAuth.Controllers.HomeController。索引 (Core2AadAuth) - 驗證 state:有效 2021-05-02T09:33:20.755374821Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] 2021:-05-02T00] 2021:- 20.755394921Z 執行動作方法Core2AadAuth.Controllers.HomeController.Index(Core2AadAuth),0.8199ms返回結果Microsoft.AspNetCore.Mvc.ViewResult。 2021-05-02T09:33:20.831668759Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor 1 2021-05-02T09:33:20.831702459Z 執行 ViewResult,運行視圖索引。

2021-05-02T09:33:21.814197839Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4] 2021-05-02T09:33:21.814222039Z 執行的 ViewResult - 查看索引在1012.1419 毫秒。 2021-05-02T09:33:21.814531541Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] 2021-05-02T09:33:21.814560341Z 執行動作 Core2AadAuth.Controllers.HomeController .Index (Core2AadAuth) in 1186.6101ms 2021-05-02T09:33:21.834760456Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] 2021-05-02T09:33:21.834786356 Z 請求在 1554.1302ms 200 text/html 內完成; charset=utf-8 2021-05-02T09:33:24.456892780Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost 1 2021-05-02T09:33:24.456933081Z 請求啟動 HTTP/ 1.1 獲取http://mwp4.azurewebsites.net/Account/SignIn
2021-05-02T09:33:24.459599695Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3] 2021-05-02T09:33:24.459617195Z 路由匹配 {action = "登錄”,controller = “帳戶”}。 在 controller Core2AadAuth.Controllers.AccountController (Core2AadAuth) 上執行帶有簽名 Microsoft.AspNetCore.Mvc.IActionResult SignIn() 的 controller 操作。 2021-05-02T09:33:24.459623195Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker 1 2021-05-02T09:33:24.459628095Z 執行動作方法Core2AadAuth.Controllers.AccountController。登錄 (Core2AadAuth) - 驗證 state:有效 2021-05-02T09:33:24.459632395Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] 209:33:----- 24.459636995Z 執行動作方法Core2AadAuth.Controllers.AccountController.SignIn(Core2AadAuth),0.634ms返回結果Microsoft.AspNetCore.Mvc.ChallengeResult。 2021-05-02T09:33:24.476765988Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.ChallengeResult 1 2021-05-02T09:33:24.476797989Z 使用身份驗證方案執行 ChallengeResult ()。 2021-05-02T09:33:25.925815616Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12] 2021-05-02T09:33:25.925878418Z AuthenticationScheme:OpenIdConnect 受到挑戰。 2021-05-02T09:33:25.947421249Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] 2021-05-02T09:33:25.947478451Z 執行動作 Core2AadAuth.Controllers.AccountController .SignIn (Core2AadAuth) in 1488.4947ms 2021-05-02T09:33:25.965321140Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] 2021-05-02T09:33:25.965363141 Z 請求在 1500.8083 毫秒內完成 302

2021-05-02T09:33:29.811005026Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost 1 2021-05-02T09:33:29.811039125Z 請求開始 HTTP/1.1 POST Z80791B3AE7029FACB8888888 /mwp4.azurewebsites.net/signin-oidc application/x-www-form-urlencoded 2784 2021-05-02T09:33:29.905246546Z [40m[1m[33mwarn[39m[22m[49m:Microsoft.AspNetCore.Authentication.OpenIdConnect .OpenIdConnectHandler[15] 2021-05-02T09:33:29.905324345Z
'.AspNetCore.Correlation.OpenIdConnect.NKdEqhMMORt61fYDDm70J3AyzqpUmgMxsYxaQfuygWI' cookie 未找到。 2021-05-02T09:33:29.906978817Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4] 2021-05-02T09:33:29.906995617Z 來自 RemoteAuthentication 的錯誤:關聯失敗。 . 2021-05-02T09:33:29.976640649Z [41m[30mfail[39m[22m[49m: Microsoft.AspNetCore.Server.Kestrel[13] 2021-05-02T09:33:29.976668449Z 連接 ID“0HM8D9L7PD097”,請求 ID “0HM8D9L7PD097:00000001”:應用程序引發了未處理的異常。 2021-05-02T09:33:29.976674549Z System.Exception:處理遠程登錄時遇到錯誤。 ---> System.Exception:關聯失敗。 2021-05-02T09:33:29.976679149Z
--- 內部異常堆棧跟蹤結束 --- 2021-05-02T09:33:29.976691948Z 在 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler 1.HandleRequestAsync() 2021-05-02T09:33:29.976696448Z at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) 2021-05-02T09:33:29.976700648Z at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) 2021-05-02T09:33:29.976705048Z at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication 1 應用程序)2021-05-02T09:33:29.976709248Z [40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal. 2] 2021-05-02T09:33:29.976713648Z 請求在 157.9686ms 500 內完成

一個原因可能是您沒有跨部署保留數據保護密鑰環。 當數據保護 API 密鑰環丟失時,會生成一組新密鑰,現有的 cookies 將不再有效。 用於加密 cookies 的密鑰在不同部署中必須相同。

我之前在這里寫過關於一種方法的博客:

另請參閱此頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM