我正在尝试使用 IdentityServer4 保护 api。
IdentityServer 启动配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddInMemoryApiScopes(Config.GetApiScopes());
}
配置:
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("myAPI", "Test API")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "myAPI" }
}
};
}
public static IEnumerable<ApiScope> GetApiScopes()
{
return new List<ApiScope>
{
new ApiScope("myAPI", "Test API")
};
}
}
当我通过 Post 请求调用我的 IdentityServer 到 http://localhost:5000/connect/token
时,我收到了一个有效的令牌,所以它应该可以工作。
API 启动配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.Authority = "http://localhost:5000";
options.Audience = "myAPI";
options.RequireHttpsMetadata = false;
});
services.AddAuthorization();
services.AddDbContext<ApiContext>(options => options.UseInMemoryDatabase("ApiDb"));
services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
API 控制器具有 [Authorize]
属性。
我正在尝试使用从 IdentityServer 获得的令牌调用控制器。 不幸的是,尽管提供令牌作为不记名令牌,但我得到了 401 未授权。
我的配置是否有问题,或者为什么我仍然收到 401?
提前致谢
-- 编辑:API 的完整 Startup.cs
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
// base-address of your identityserver
options.Authority = "http://localhost:5000";
// if you are using API resources, you can specify the name here
options.Audience = "myAPI";
options.RequireHttpsMetadata = false;
});
services.AddAuthorization();
services.AddDbContext<ApiContext>(options => options.UseInMemoryDatabase("ApiDb"));
services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}