如何使ASP.NET核心Web API身份返回未经授权的401



我正在尝试使ASP.NET核心Web API JSON Web代币身份验证正常工作。我必须与应用程序成功整合了IdentityServer4的地步,并且它正在成功地基于ASP.NET核心身份处理登录。

但是,每当身份验证失败时,API都会返回一个302结果,试图将客户端重定向到登录页面。但是,这是一个纯净的Web API,没有用户页面或用户应该直接与之交互的任何内容。

如何使系统返回401而不是试图重定向到登录页面?

配置服务的身份部分如下:

       // ASP.net Identity
        var identityBackingStoreConnectionString = configuration["identity:backingStore"];
        services
            .AddIdentityWithMongoStoresUsingCustomTypes<MyApplicationUser, IdentityRole>(
                identityBackingStoreConnectionString)
            .AddDefaultTokenProviders();
        services.AddSingleton<IClientStore, MyIdentityStore>();
        // IdentityServer4
        services.AddIdentityServer().AddTemporarySigningCredential()
            .AddInMemoryApiResources(MyResourceStore.GetAllResources())
            .AddAspNetIdentity<MyApplicationUser>()
            .AddTemporarySigningCredential();

和相关(我认为(配置的一部分如下:

        app.UseIdentity();
        app.UseIdentityServer();
        app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
        {
            Authority = "http://localhost:5000/",
            RequireHttpsMetadata = false,
            ApiName = "myapi",
            AutomaticAuthenticate = true,
            JwtBearerEvents = new JwtBearerEvents()
            {
                OnAuthenticationFailed = async context => context.Response.StatusCode = 401
            }
        });
        app.UseMvc();

您可以看到,我尝试超越了onauthenticationfailed事件,但无济于事。

关于如何使系统返回401的任何建议将不胜感激。

身份服务器使用Cookie身份验证,将401转换为302。

我认为您不能因此使app.UseIdentityServer()app.UseIdentityServerAuthentication()因此而同时生活在一起。

但是,您可以轻松找到解决方法。

最好的是在单独的应用程序中托管身份服务器(例如,身份服务器, localhost:5000 以及 localhost的应用程序:5001 (。它更适合开放ID连接的概念,您可以在官方Github

上享受大量示例

另外,您可以尝试将身份服务器和API放置在不同的子路径上,例如 localhost:5000/idsrv localhost:5000/api 使用app.UseWhen。例如

app.UseWhen(
    c => c.Request.Path.StartsWithSegments(new PathString("/api")), 
    branch => {
       branch.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
       {
           Authority = "http://localhost:5000/idsrv",
           RequireHttpsMetadata = false,
           ApiName = "myapi",
           AutomaticAuthenticate = true,
       } );
       branch.UseMvc();
   });
app.UseWhen(
    c => c.Request.Path.StartsWithSegments(new PathString("/idsrv")), 
    branch => {
       branch.UseIdentityServer();
       branch.UseMvc();
    } );

再次,这种方法更容易出错,我宁愿考虑单独的应用程序。

最新更新