05-IdentityServer4

前面我们认识了jwt的token颁发模式,其中的应用场景和部分缺陷已经很是了解了。有些场合并不适合jwt,特别是针对第三方进行使用时,比如我们使用qq或者微信登陆博客园或其他第三方应用时。

Ids4的token颁发可以简单的概述为4中场景,客户端模式,密码模式,简化模式,授权码模式。还有一个混合模式。这些都是针对Ids4颁发的模式进行区分的,至于接口验证环节,是一样的。

1)控制器或者Action增加特性标签,

2)增加中间件app.UseAuthentication();//注意添加这一句,启用验证,解析信息--就是读取token,解密token

3)在ConfigureServices增加AddAuthentication方法,设置授权模式,可以采用Ids4,也可以是jwt或者是cookie等

4)可以扩展自定义的policy模式进行权限验证。

这里我们重点描述Ids4的4中常用认证模式,也就是说4种token颁发模式。

token颁发模式的实现

1)添加UseIdentityServer()中间件

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    #region 添加IdentityServer中间件
    app.UseIdentityServer();//拦截部分请求
    #endregion

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

2)在services中添加AddIdentityServer()

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    #region 客户端
    services.AddIdentityServer()//怎么处理
      .AddDeveloperSigningCredential()//默认的开发者证书--临时证书--生产环境为了保证token不失效,证书是不变的
      .AddInMemoryClients(ClientInitConfig.GetClients())//InMemory 内存模式
      .AddInMemoryApiResources(ClientInitConfig.GetApiResources());//能访问啥资源
    #endregion

    #region 密码模式
    //services.AddIdentityServer()
    //    .AddDeveloperSigningCredential()//默认的开发者证书 
    //   .AddInMemoryApiResources(PasswordInitConfig.GetApiResources())//API访问授权资源
    //   .AddInMemoryClients(PasswordInitConfig.GetClients())  //客户端
    //   .AddTestUsers(PasswordInitConfig.GetUsers());//添加用户
    #endregion

    #region 简化模式
    //services.AddIdentityServer()
    //    .AddDeveloperSigningCredential()//默认的开发者证书 
    //   .AddInMemoryApiResources(ImplicitInitConfig.GetApiResources()) //API访问授权资源
    //   .AddInMemoryClients(ImplicitInitConfig.GetClients())//客户端
    //   .AddTestUsers(ImplicitInitConfig.GetUsers()); //添加用户
    #endregion

    #region Code模式
    //services.AddIdentityServer()
    //    .AddDeveloperSigningCredential()//默认的开发者证书 
    //   .AddInMemoryApiResources(CodeInitConfig.GetApiResources()) //API访问授权资源
    //   .AddInMemoryClients(CodeInitConfig.GetClients())//客户端
    //   .AddTestUsers(CodeInitConfig.GetUsers()); //添加用户
    #endregion

    #region Hybrid模式
    //services.AddIdentityServer()
    //    .AddDeveloperSigningCredential()//默认的开发者证书 
    //    .AddInMemoryIdentityResources(HybridInitConfig.GetIdentityResources())//身份信息授权资源
    //   .AddInMemoryApiResources(HybridInitConfig.GetApiResources()) //API访问授权资源
    //   .AddInMemoryClients(HybridInitConfig.GetClients())//客户端
    //   .AddTestUsers(HybridInitConfig.GetUsers()); //添加用户
    #endregion
}

关于Ids4的4种模式,我们在之前的博客中已经进行了详细的描述,

根据我的项目经验,我们使用最多的是客户端模式和密码模式,很少使用另外的模式,另外的模式只是作为客户端来访问其他第三方的授权中心(比如qq,微信等),我们自己的授权中心作为其他的第三方登录情况极少。

原文地址:https://www.cnblogs.com/vigorous/p/13595957.html