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

3.Client Credentials

客户端使用客户端凭据授予类型来获取用户上下文之外的访问令牌。

这通常被客户端用来访问关于他们自己的资源,而不是访问用户的资源。

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资源