.NetCore使用客户端集成IdentityServer

  1. 在.vs code应用商店里先载入nuget-package-manager
  2. 进入目录使用命令dotnet new webapi --name IdentityServerCenter创建一个webapi项目(服务端)

    项目创建完成后,添加依赖。使用Ctrl+P打开命令窗口, 输入如图

    再输入IdentityServer4,如图

          回车键确认然后选择最新版本,安装完成后,在控制台输入命令dotnet restore以加载。

  3. 新建一个Config.cs文件,用于获取返回ApiResource和Client。

    using System.Collections;
    using System.Collections.Generic;
    using IdentityServer4.Models;
    
    namespace IdentityCenter
    {
        public class Config
        {
            public static IEnumerable<ApiResource> GetResources()
            {
                return new List<ApiResource>()
                {
                    new ApiResource("api","My Api")
                };
            }
    
            public static IEnumerable<Client> GetClients()
            {
                 return new List<Client>()
                 {
                    new Client()
                    {
                        ClientId="client",
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                        ClientSecrets = 
                        {
                            new  Secret("secret".Sha256())
                        },
                        AllowedScopes = {"api"}
                    }
                };
            }
        }
    }
  4. 进入Startup.cs文件添加依赖配置并注入管道,在ConfigureService方法内添加代码

     services.AddIdentityServer()
                    .AddDeveloperSigningCredential()
                    .AddInMemoryApiResources(Config.GetResources())
                    .AddInMemoryClients(Config.GetClients());

    然后在Config方法里注入管道

      app.UseIdentityServer();//注入管道
  5. 到这里,服务端已经配置好了,我们可以在Program文件的CreateWebHostBuilder方法里写定访问端口,因为默认的是使用5000/5001端口。写定端口为了在本机方便测试。

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseUrls("http://localhost:5000")
                    .UseStartup<Startup>();

    我们直接访问localhost:5000的话,会出错

这里有一个固定的地址访问:http://localhost:5000/.well-known/openid-configuration,使用PostMan访问结果如下,返回一些json数据

使用http://localhost:5000/connect/token,这个地址我们可以拿到token信息,使用PostMan访问这个地址Post方式需要传送3个参数以获得token信息,如图client_id、client_secret和grant_type三个参数,我们在前面已经配置好了client_idclient_secret,本次使用的grant_type类型是client_credentials


我们再创建一个客户端webapi项目,在项目内部简单引用IdentityServer就可以了,如上一样Ctrl+P打开命令窗口,输入>nuger ....选择,然后在新的命令搜索框内输入IdentityServer4.AccessTokenValidation(这里有可能搜索不到,这是vs coce的一个毛病,我们刷新项目随便点点项目文件),插件安装完后,在Startup.cs添加配置代码

  services.AddAuthentication("Bearer")
                    .AddIdentityServerAuthentication(options=>
                    {
                        options.Authority = "http://localhost:5000";
                        options.RequireHttpsMetadata = false;
                        options.ApiName = "api";
                    });

这里不难看懂,我们的授权token是从localhost:5000这个地址获取到。然后在Configure方法内注入

 app.UseAuthentication();

这里最好也把项目启动项目写定一下,否则会和刚才一个项目地址冲突,这个项目我们配置成5001端口

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:5001")
                .UseStartup<Startup>();

以上算配置好了,一个服务端一个客户端。从服务端获取到token信息,在客户端访问api的时候需要带上token信息。使用方法,在客户端的api控制器内加入[Authorize]即可。

猜你喜欢

转载自blog.csdn.net/zhangshineng/article/details/87823638
今日推荐