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

时间:2018-11-19 16:09:47

标签: angular azure-active-directory angular7 .net-core-2.1

尝试将Azure AD身份验证添加到具有.net core 2.1后端的Angular 7 Webapp中。

但是,在请求期间出现了CORS错误。

“从原点“ https://login.microsoftonline.com/”访问“ https://localhost:5001/api/auth/login .......”(从“ https://localhost:5001”重定向到XMLHttpRequest)已被CORS策略禁止:否请求的资源上显示“ Access-Control-Allow-Origin”标头。“

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

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);
    });
  }

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

如果我导航到登录URL,例如:localhost:5000 / api / auth / login->我进入AAD登录页面,并在身份验证成功后重定向回。但是,如果我从代码中触发它,则会收到CORS错误。

1 个答案:

答案 0 :(得分:4)

您的方法有点错误。 您已经配置了OIDC + Cookies,但想使用XHR进行调用。

典型的方法是:

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

一些样本/文章可能会有所帮助:

请记住,只能将ADAL与AAD v1端点一起使用,并将MSAL与v2端点一起使用。