1、新建空的asp.net core 项目
目录结构
2、添加 IdentityServer4 相关类库
3、添加Config类
public static class Config { public static IEnumerable<IdentityResource> IdentityResources => new IdentityResource[] { new IdentityResources.OpenId() }; public static IEnumerable<ApiScope> ApiScopes => new ApiScope[] { new ApiScope("scope1"), new ApiScope("scope2"), }; public static IEnumerable<Client> Clients => new Client[] { new Client { ClientId="myclient", ClientSecrets=new []{new Secret("secret".Sha256()) }, AllowedGrantTypes=GrantTypes.ResourceOwnerPasswordAndClientCredentials, AllowedScopes=new [] { "scope1" } } }; public static List<TestUser> TestUsers => new List<TestUser> { new TestUser { Username="pc", Password="123", SubjectId="1" } }; }
4、修改Startup文件
public void ConfigureServices(IServiceCollection services) { var builder = services.AddIdentityServer() .AddTestUsers(Config.TestUsers) .AddInMemoryApiScopes(Config.ApiScopes) .AddInMemoryClients(Config.Clients); // not recommended for production - you need to store your key material somewhere secure builder.AddDeveloperSigningCredential(); services.AddAuthentication(); } // 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.UseRouting(); app.UseIdentityServer(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); }
5、启动程序
6、Postman访问