IdentityServer4 授权实例(Client Credentials)
官网地址https://identityserver4.readthedocs.io/en/latest/
1.安装IdentityServer4模板
dotnet new -i IdentityServer4.Templates
、
测试 生产环境使用需要付费
结合Asp.Net Core Identity
空模板
使用了EFCore
使用内存存储配置信息和数据
只带UI
2.建立IdentityServer4项目(使用内存模式)
dotnet new is4inmem --name Idp
客户端使用客户端凭据授予类型来获取用户上下文之外的访问令牌。
这通常被客户端用来访问关于他们自己的资源,而不是访问用户的资源。
https://oauth.net/2/
4.实例
4.1修改Idp工程 Clients 配置
Api资源
客户端资源
4.2创建Api资源
修改Scope1Resource中StartUp的代码

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "https://localhost:5001"; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
修改Program的地址吗,防止测试的时候端口冲突
4.3创建控制台客户端
客户端需要安装安装IdentityModel
实现代码如下
认证服务 ---> 请求Access Token ---> SetBearerToken请求保护的Api资源

class Program { static async Task Main(string[] args) { // discovery endpoint var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001"); if (disco.IsError) { Console.WriteLine(disco.Error); return; } // request access token var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest() { Address = disco.TokenEndpoint, ClientId = "console client", ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",//错误的"111", Scope = "scope1"// "scope1 openid" }); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; } // call API // call Identity Resource API var apiClient = new HttpClient(); apiClient.SetBearerToken(tokenResponse.AccessToken); //var response = await apiClient.GetAsync(disco.UserInfoEndpoint); var response = await apiClient.GetAsync("https://localhost:6001/identity"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(JArray.Parse(content)); } Console.ReadKey(); } }
4.4认证 客户端 保护的Api资源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!