IdentityServer4 学习笔记[1]-客户端授权

前言

本文内容来自IdentityServer4官网,官网有详细的介绍,并且有源码Demo
官网源码例子传送门

建立授权服务端


我们暂时不配置Https,选择空模板建立项目,项目建立后, 为了查看debug信息,我们使用控制台来启动,打开launchSettings.json,删除红色部分,其实也可以不删,选择运行按钮后的倒三角来选择也是可以的

好了,操作OK后,我们运行一下看看,端口监听OK,如果这一步失败的,看看端口是否被占用了,或者修改下端口

安装IdentityServer4

在项目上右键菜单里选择管理Nuget程序包,在左上角浏览里输入IdentityServer4,找到并且安装,当然也可以在程序包管理器控制台里面安装,后文不再介绍nuget包安装

在Startup中添加
$\color{red}{app.UseIdentityServer()}$
c# {.line-numbers} public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseIdentityServer(); }

配置授权服务端

IdentityServer现在也Use过了,但是我们没有数据,我也不打算从数据库获取,那怎么办呢?使用内存造点配置数据来模拟场景,生产场景配置数据应该从数据库或者配置文件获取新建Config.cs
```c# {.line-numbers}
public class Config
{
///


/// 模拟Api资源配置数据
///

///
public static IEnumerable GetApis()
{
return new List
{
new ApiResource("api1", "My API")
};
}

    /// <summary>
    /// 模拟客户端配置数据
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
             new Client
             {
                  ClientId = "client",
                  //授权方式为客户端授权,类型可参考GrantTypes枚举
                  AllowedGrantTypes = GrantTypes.ClientCredentials,
                  //授权密钥,客户端和服务端事先约定的一个Key
                  ClientSecrets =
                  {
                     new Secret("secret".Sha256())
                  },                     
                  //允许客户端访问的Scopes[作用域]
                  AllowedScopes = { "api1" }
             }
        };
    }

    /// <summary>
    /// 模拟授权资源
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new IdentityResource[]
        {
            new IdentityResources.OpenId()
        };
    }
}

```
IdentityServer有关的配置介绍,官网有介绍,本文就不再重复了,下面有链接
ApiResource
Client
IdentityResource

下面把IdentityServer以及配置注册到IOC容器中,如下代码所示
c# {.line-numbers} public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryClients(Config.GetClients()) .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryIdentityResources(Config.GetIdentityResources()); }

验证授权服务端

可以自己新建个控制台项目,安装IdentityModel的nuget包来测试也可以,这里我们使用postman来测试刚刚建立的服务端程序
好了,先运行

打开Postman,如果没有,可以自行下载安装
发现端点可通过/.well-known/openid-configuration相对于基地址获得

如上图红色所示,我们使用红色标示的地址去拿Token,Postman截图如下所示

我们获取到了Token,以及Token的过期时间,以及Token的类型,同时在控制台里看到
IdentityServer验证成功,也看到如ClientId,GrantType,Scopes,Raw等信息
如果把client_id 或者secret 故意填写错,再post的话获取Token会失败,如下所示
,所以client_id 和 secret 是客户端和服务端事先约定好的,必须一致,否则获取Token将失败

总结

本文介绍了IdentityServer4的基于客户端授权[客户端和服务端约定好client_id和client_secret的方式],这种方式适合那种没有用户参与的API的保护[]

猜你喜欢

转载自www.cnblogs.com/sarco/p/10603387.html