Asp.net web api Core 2.0上的IdentityServer4从API获取401(未经授权)

Asp.net web api Core 2.0上的IdentityServer4从API获取401(未经授权),asp.net-web-api,access-token,identityserver4,asp.net-core-2.0,Asp.net Web Api,Access Token,Identityserver4,Asp.net Core 2.0,在尝试迁移到最新版本的IdentityServer4和.NET Core 2之后,我突然从我的web API项目中得到了401个错误。在过去的一周里,我做了很多改变,我不知道什么是对的或错的了 我有一个小型3项目解决方案: IDSRV: 网络应用程序: API应用程序: 以下是我的代码,用于配置存储在我的数据库中的IDSV: public class Config { public static IEnumerable<IdentityResource> GetIdentit

在尝试迁移到最新版本的IdentityServer4和.NET Core 2之后,我突然从我的web API项目中得到了401个错误。在过去的一周里,我做了很多改变,我不知道什么是对的或错的了

我有一个小型3项目解决方案:

  • IDSRV:
  • 网络应用程序:
  • API应用程序:
  • 以下是我的代码,用于配置存储在我的数据库中的IDSV:

    public class Config
    {
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }
    
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource(){
                    Name = "api.oc.com",
                    Description = "OC Api",
                    Scopes = new[] {new Scope("api.oc.com")}
                }
            };
        }
    
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "oc.com",
                    ClientName = "OC Website",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    AlwaysIncludeUserClaimsInIdToken = true,                    
                    ClientSecrets =
                    {
                        new Secret("SomeReallyStrongPassword1!".Sha256())
                    },
                    RedirectUris = { "https://localhost:44301/signin-oidc" },
                    PostLogoutRedirectUris = { "https://localhost:44301/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api.oc.com",
                        "offline_access"
                    },                    
                    AllowOfflineAccess = true
                }
            };
        }
    }
    
    这将我带到WEB前端,尝试对WEB API进行身份验证。 我用访问令牌和ID令牌都试过了,但似乎都不起作用

    使用访问令牌:

      var accessToken = await HttpContext.GetTokenAsync("access_token");
      var client = new HttpClient();
      client.SetBearerToken(accessToken);
      var result = await client.GetStringAsync("https://localhost:44302/api/text/welcome");
    
    或使用客户端凭据流:

      var disco = await DiscoveryClient.GetAsync("https://localhost:44300");
      var tokenClient = new TokenClient(disco.TokenEndpoint, "oc.com", "SomeReallyStrongPassword1!");
      var tokenResponse = await tokenClient.RequestClientCredentialsAsync();
    
      var client = new HttpClient();
      client.SetBearerToken(tokenResponse.AccessToken);
      var result = await client.GetStringAsync("https://localhost:44302/api/text/welcome");
    
    如果有人对此有任何煽动,我衷心感谢。看了这么久的安全代码,我的眼球都快爆炸了!哈哈

    谢谢,
    迈克·库什纳在多管闲事后。。并且添加了一个真正的证书,这似乎在我创建了一些策略之后才起作用,而不仅仅是使用[Authorize]属性注意,我还再次使用IdentityServer4.AccessTokenValidation。

        public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthorization((options) => {
                options.AddPolicy("MustBeValidUser", policybuilder =>
                {
                    policybuilder.RequireAuthenticatedUser();
                    policybuilder.Requirements = new[] { new MustBeValidUserRequirement() };
                });
            });
            services.AddSingleton<IAuthorizationHandler, MustBeValidUserHandler>();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44300";
                options.RequireHttpsMetadata = true;
                options.ApiName = "api.oc.com";
            });
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            app.UseDeveloperExceptionPage();
            app.UseAuthentication();
            app.UseMvc();
        }
    }
    
    公共类启动
    {
    public void配置服务(IServiceCollection服务)
    {
    services.AddMvc();
    services.AddAuthorization((选项)=>{
    options.AddPolicy(“MustBeValidUser”,policybuilder=>
    {
    policybuilder.RequireAuthenticatedUser();
    policybuilder.Requirements=new[]{new MustBeValidUserRequirement()};
    });
    });
    services.AddSingleton();
    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
    .AddIdentityServerAuthentication(选项=>
    {
    选项。权限=”https://localhost:44300";
    options.RequireHttpsMetadata=true;
    options.ApiName=“api.oc.com”;
    });
    }
    //此方法由运行时调用。请使用此方法配置HTTP请求管道。
    公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
    {
    loggerFactory.AddConsole();
    app.UseDeveloperExceptionPage();
    app.UseAuthentication();
    app.UseMvc();
    }
    }
    
    我要做的第一件事(在浪费时间编写所有代码之前)是查看API中的日志。它们将包含有用的信息。像往常一样,多米尼克。。。你真是个天才!:)有几件事,我不得不在ConfigureServices中设置策略并更改UseMVC的顺序。谢谢@leastprivilege,你让我走上了正确的道路,我的IDP现在正在工作!
        public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthorization((options) => {
                options.AddPolicy("MustBeValidUser", policybuilder =>
                {
                    policybuilder.RequireAuthenticatedUser();
                    policybuilder.Requirements = new[] { new MustBeValidUserRequirement() };
                });
            });
            services.AddSingleton<IAuthorizationHandler, MustBeValidUserHandler>();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44300";
                options.RequireHttpsMetadata = true;
                options.ApiName = "api.oc.com";
            });
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            app.UseDeveloperExceptionPage();
            app.UseAuthentication();
            app.UseMvc();
        }
    }