添加 Azure AD 身份验证时出现 CORS 错误

问题描述:

尝试将 Azure AD 身份验证添加到具有 .net core 2.1 后端的 Angular 7 Web 应用程序.

Trying to add Azure AD authentication to an Angular 7 webapp with a .net core 2.1 backend.

但是,我在请求期间收到 CORS 错误.

However, I get the CORS error during the request.

"在 'https://login.microsoftonline.com/ 处访问 XMLHttpRequest.......'(重定向自 'https://localhost:5001/api/auth/login') 来自 origin 'https://localhost:5001' 已被 CORS 策略阻止:没有 'Access-Control-Allow-请求的资源上存在 Origin' 标头."

"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

所以我尝试在启动管道中添加一些 CORS 策略.

So I tried adding some CORS policy in the startup pipe-line.

Startup.cs

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }    

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(config => config
             .AddPolicy("SiteCorsPolicy", builder => builder
               .AllowAnyHeader()
               .AllowAnyMethod()
               .AllowAnyOrigin()
               .AllowCredentials()
              )
           ); // <--- CORS policy - allow all for now

            services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;                
            })
            .AddOpenIdConnect(options =>
            {
                options.Authority = "https://login.microsoftonline.com/MY_AD_DOMAIN.onmicrosoft.com";   // ad domain            
                options.ClientId = "my_client_id"; // client guid
                options.ResponseType = OpenIdConnectResponseType.IdToken;
                options.CallbackPath = "/auth/signin-callback";
                options.SignedOutRedirectUri = "https://localhost:5000";
                options.TokenValidationParameters.NameClaimType = "name";
            }).AddCookie();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseCors("SiteCorsPolicy"); // <--- CORS policy
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

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

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }

角度身份验证服务

login() {        
    const url = this.baseUrl + "api/auth/login";
    this._http.get(url).subscribe(response => {
      console.log(response);
    });
  }

还是我走错了路?我应该使用一些第三方ADAL"npm 包(https://www.npmjs.com/package/adal-angular) 从客户端提取令牌,然后将令牌传递给服务器进行验证?

Or am I going the wrong way about it? Should I use some third pary "ADAL" npm package (https://www.npmjs.com/package/adal-angular) to extract the token from the client side and then pass the token to the server for validation?

如果我导航到登录 URL,例如:localhost:5000/api/auth/login --> 我将转到 AAD 登录页面,并在成功验证时重定向回来.但是如果我从代码中触发它,我会收到 CORS 错误.

If I navigate to the login URL, e.g: localhost:5000/api/auth/login --> I get set off to the AAD login page, and redirected back at successful authentication. But if I trigger it from code, I get the CORS error.

你的方法有点错误.您已配置 OIDC + Cookies,但想要使用 XHR 调用它.

Your approach is a bit wrong. You've configured OIDC + Cookies, yet want to call it with an XHR.

典型的方法是:

  • 在 API 上配置 JWT Bearer 令牌身份验证
  • 在前端使用 ADAL/MSAL 对用户进行身份验证 + 为后端获取访问令牌
  • 将访问令牌附加到 XHR 以对其进行身份验证

一些可能有帮助的示例/文章:

Some samples/articles that may help:

请记住,ADAL 只能用于 AAD v1 端点,MSAL 只能用于 v2 端点.

Keep in mind ADAL can only be used with the AAD v1 endpoint and MSAL with the v2 endpoint.