.Net Core 3.1 SPA授权失败

.Net Core 3.1 SPA authorize failed

我在从 React SPA 调用授权 api 时遇到问题。如果删除 controller/action 中的 [Authorize] 属性,它会起作用,但一旦添加到该属性中,响应就会转到 SPA 主页。

项目结构

  • IdentityServer (.net core 3.1 mvc with IdentityServer4 *reference token type)

  • Login (authentication with IdentityServer and auth callback to Portal)

  • Portal (.net core 3.1 react SPA, use IdentityServer4.AccessTokenValidation to validate

反应

fetch('/api/test').then(async (response) => {  
  var data = await response.json();
  console.dir(response);
  console.dir(data);
});

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddControllersWithViews()
        .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; });

    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44302";
                options.ApiName = "api1";
                options.ApiSecret = "thisissecret";
            });

    services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; });
}

public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseStaticFiles();
    app.UseSpaStaticFiles();
    app.UseRouting();

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

    app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); });
    app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            if (_WebHostEnvironment.IsDevelopment())
            {
                spa.UseReactDevelopmentServer("start");
            }
        });
}

如果 api 控制器没有“授权”属性,则可以使用,但一旦添加,将保持未授权状态。

对不起各位,是我的错误,我没有在 IdentityServer 中设置 ApiSecret。因此,它一直处于未验证状态。

new ApiResource("api1", )
{
    // the missing part
    ApiSecrets = {
        new Secret("thisissecret".Sha256())
    }
}