Angular 从客户端调用API时Identity server CORS错误

Angular 从客户端调用API时Identity server CORS错误,angular,api,cors,identityserver4,Angular,Api,Cors,Identityserver4,嗨,我创建了一个Angular应用程序,它连接到Identity Server 4进行身份验证。我向AllowedCorsOrigins注册了angular客户端,作用域正在访问API。我还有其他客户端“.net core MVC”,它们也有相同的作用域(访问API)。我对MVC客户端没有任何问题,但我得到了CORS错误 身份服务器客户端 new Client { ClientId = "clientangularSLO",

嗨,我创建了一个Angular应用程序,它连接到Identity Server 4进行身份验证。我向AllowedCorsOrigins注册了angular客户端,作用域正在访问API。我还有其他客户端“.net core MVC”,它们也有相同的作用域(访问API)。我对MVC客户端没有任何问题,但我得到了CORS错误

身份服务器客户端

new Client
        {
            ClientId = "clientangularSLO",
            ClientName = "Angular Client",
            AllowedGrantTypes = GrantTypes.Code,
            RequireClientSecret = false,
            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                "api1",
                "roles"
            },

            
            RedirectUris = new List<string> {"http://localhost:4200", "http://localhost:4300"},
            PostLogoutRedirectUris = new List<string> {"http://localhost:4200", "http://localhost:4300"},
            AllowedCorsOrigins = new List<string> { "http://localhost:4200", "http://localhost:4300" },

            AccessTokenLifetime = 120,  //2mins 
            RequireConsent= true,
            RequirePkce = true,
            AllowAccessTokensViaBrowser = true,
            AllowOfflineAccess = true,
            
        }
我试图在API中添加Cors,我不确定这是正确的wasy

API-->StartUp.cs

public void ConfigureServices(IServiceCollection services)
        {
            //services.AddCors(c =>
            //{
            //    c.AddPolicy("AllowOrigin", options => 
            //        options.WithOrigins("http://localhost:4200", "http://localhost:4300")
            //        .AllowAnyMethod()
            //        .AllowAnyHeader()                 
            //    );
            //});

           
            services.AddSingleton<ICorsPolicyService>((container) => {
                var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
                return new DefaultCorsPolicyService(logger)
                {
                    //AllowedOrigins = { "http://localhost:4200", "http://localhost:4300" }
                    AllowAll = true
                };
            });
            
            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("Apiscope", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("Scope", "api1");
                    
                });

            });
}


 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(options => options.AllowAnyOrigin());
            //app.UseCors(options => options.WithOrigins("http://localhost:4200", "http://localhost:4300"));

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();
        
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers()
                    .RequireAuthorization("ApiScope"); //checking the policy "Apiscope"
            });
        }
public void配置服务(IServiceCollection服务)
{
//services.AddCors(c=>
//{
//c.AddPolicy(“AllowOrigin”,选项=>
//选项。WithOriginates(“http://localhost:4200", "http://localhost:4300")
//.AllowAnyMethod()
//.AllowAnyHeader()
//    );
//});
services.AddSingleton((容器)=>{
var logger=container.GetRequiredService();
返回新的DefaultCorsPolicyService(记录器)
{
//AllowedOriginates={”http://localhost:4200", "http://localhost:4300" }
AllowAll=true
};
});
services.AddAuthorization(opt=>
{
opt.AddPolicy(“Apiscope”,policy=>
{
policy.RequireAuthenticatedUser();
政策要求回收(“范围”、“api1”);
});
});
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options=>options.AllowAnyOrigin());
//app.UseCors(options=>options.WithOrigins(“http://localhost:4200", "http://localhost:4300"));
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllers()
.RequireAuthorization(“ApiScope”);//检查策略“ApiScope”
});
}
要添加令牌的HttpInterceptor

 private getToken(){
    return this.oidcSecurityService.getToken();
  }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    
    if(this.tokenValue){
      request = request.clone( {
        setHeaders: {
          Authorization : `Bearer ${this.getToken()}`
        }
      })
    }

    return next.handle(request);
  }
private getToken(){
返回此.oidcSecurityService.getToken();
}
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
if(this.tokenValue){
请求=请求。克隆({
集合标题:{
授权:`Bearer${this.getToken()}`
}
})
}
下一步返回。处理(请求);
}
我正在使用Angular11和Identity server v4.0.0。请告诉我,解决这个问题的正确方法


我不能100%确定我是否完全理解上下文,但我怀疑为Angular应用程序服务的.NET Core后端服务没有使用端口4200上Angular development server的代理配置

因此,在
ConfigureServices(IServiceCollection services)
中基于.NET的Angular后端服务的
Startup.cs
中,需要进行以下配置:

services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/dist";
});
并在
Configure(IApplicationBuilder应用程序,IWebHostEnvironment环境)

详情如下:

我建议使用
dotnet new angular-o我的新应用程序生成一个项目
,并检查那里的配置。 如果我们希望使用
ng serve
独立运行Angular development server,通常使用这种方法来避免跨源调用


如果此方法已起作用,下一步是正确配置identity server。

请尝试将此“访问控制允许来源”:“*”添加到您的请求中。

谢谢大家的评论

这可以通过在API配置中添加AllowAnyHeader()AllowAnyMethod()来解决

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(options =>
            options.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            );

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                .RequireAuthorization("ApiScope"); //checking the policy "Apiscope"
        });
    }
services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "ClientApp/dist";
});
app.UseSpa(spa =>
{
    // To learn more about options for serving an Angular SPA from ASP.NET Core,
    // see https://go.microsoft.com/fwlink/?linkid=864501
     spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
    }
 });
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(options =>
            options.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            );

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
                .RequireAuthorization("ApiScope"); //checking the policy "Apiscope"
        });
    }