【问题标题】:.Net Core 3.1 SPA authorize failed.Net Core 3.1 SPA 授权失败
【发布时间】:2020-08-02 05:02:36
【问题描述】:

我在从 React SPA 调用授权 api 时遇到问题。如果删除控制器/动作中的 [Authorize] 属性,它就可以工作,但是一旦添加到属性中,响应就会转到 SPA 主页。

项目结构

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

  • 登录(使用 IdentityServer 进行身份验证并将身份验证回调到 Portal)

  • Portal(.net core 3.1 react SPA,使用IdentityServer4.AccessTokenValidation进行验证

反应

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 控制器没有“授权”属性,则有效,但一旦添加,则将继续未经授权。

【问题讨论】:

  • 如何配置客户端认证库,调用web api时是否使用引用令牌作为http请求头?也可以使用 fiddler 跟踪 web api 请求,检查是否返回任何详细的错误信息。
  • 我们能看到控制器代码吗?特别是 [Route] 属性,你是在它前面添加 /api/ 吗?
  • @PabloRecalde,感谢您的帮助。是我的错误,在身份服务器中缺少配置会导致问题。
  • @NanYu,感谢您的帮助。是我的错误,在身份服务器中缺少配置会导致问题。

标签: c# asp.net-core identityserver4 asp.net-spa


【解决方案1】:

对不起,我错过了在 IdentityServer 中设置 ApiSecret 的错误。因此,它一直未经身份验证。

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

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2020-11-13
    • 2020-05-21
    • 2020-09-19
    • 2020-05-27
    • 1970-01-01
    • 2021-10-23
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多