认证受权:IdentityServer4

前言

  上一篇文章<学习OIDC>介绍了OIDC协议,本篇开始咱们就来具体来学习OIDC的具体实现IdentityServer4 学习。html

1、IdentityServer4 是什么?

   IdentityServer4是用于ASP.NET Core的OpenID Connect和OAuth 2.0框架。git

  能够构建(或从新使用)包含登陆和注销页面的应用程序,IdentityServer中间件会向其添加必要的协议头,以便客户端应用程序能够使用这些标准协议与其对话。github

   

   能够在应用程序中使用如下功能:web

    • 身份验证即服务

      全部应用程序(Web,本机,移动,服务)的集中式登陆逻辑和工做流。IdentityServer是OpenID Connect 的官方认证明现数据库

    • 单点登陆/退出

      多种应用程序类型的单点登陆(注销)api

    • API的访问控制

      为各类类型的客户端(例如,服务器到服务器,Web应用程序,SPA和本机/移动应用程序)的API发出访问令牌浏览器

    • 联合网关

      支持外部身份提供程序,例如Azure Active Directory,Google,Facebook等。这使您的应用程序免受如何链接到这些外部提供程序的详细信息的影响。服务器

2、简单使用示例

先建立项目目录结构(以下图)app

 一、IdentityServer 认证服务实现

  a) 建立一个空的WebApi项目-cz.IdentityServer,并添加IdentityServer4项目引用:以下图:框架

Install-Package IdentityServer4

  b) 要启用IdentityServer服务,不只要把 IdentityServer 注册到容器中, 还须要配置一下内容:

    •  Authorization Server 保护了哪些 API (资源);
    • 哪些客户端 Client(应用) 能够使用这个 Authorization Server;

    • 指定能够使用 Authorization Server 受权的 Users(用户)

    建立文件 InMemoryConfig.cs,用于设置以上相关内容:    

  View Code

    GetApiResources:这里指定了name和display name, 之后api使用authorization server的时候, 这个name必定要一致

    GetClients: 认证客户端列表

    Users: 这里的内存用户的类型是TestUser, 只适合学习和测试使用, 实际生产环境中仍是须要使用数据库来存储用户信息的, 例如接下来会使用asp.net core identity. TestUser的SubjectId是惟一标识.

   在Startup.cs中启用IdentityServer服务

       修改StartUp.cs中的ConfigureServices方法

复制代码
public void ConfigureServices(IServiceCollection services)
{
            services.AddControllersWithViews();
            services.AddIdentityServer()
              .AddDeveloperSigningCredential()
              .AddInMemoryApiResources(InMemoryConfig.GetApiResources())
              .AddTestUsers(InMemoryConfig.Users().ToList())
              .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResourceResources())
              .AddInMemoryClients(InMemoryConfig.GetClients());
}
复制代码

    修改StartUp.cs中的Configure方法    

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

            app.UseRouting();
       //启用IdentityServer
            app.UseIdentityServer();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
复制代码

   运行此项目,打开浏览器访问http://localhost:5600/.well-known/openid-configuration你将会看到IdentityServer的各类元数据信息。

    

  c) 引入QuickStartUI界面

   IdentityServer提供了一套UI以使咱们能快速的开发具备基本功能的认证/受权界面,下载地址:QuickStartUI

   下载后,把QuickStartUI中:wwwroot、Quickstart、Views拷贝到项目中,以下结构:、

   

   修改Statup.cs内容以下:

  View Code

   运行以下效果:

   

 二、IdentityServer 集成Api服务

   a)添加web api项目cz.Api.Order,并添加nuget中安装IdentityServer4.AccessTokenValidation ,以下图:  

命令:Install-Package IdentityServer4.AccessTokenValidation

    

 

   b) 修改StartUp.cs文件    

复制代码
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();

            //IdentityServer
            services.AddMvcCore()
                    .AddAuthorization();

            //配置IdentityServer
            services.AddAuthentication("Bearer")
                        .AddIdentityServerAuthentication(options =>
                        {
                            options.RequireHttpsMetadata = false; //是否须要https
                            options.Authority = $"http://localhost:5600";  //IdentityServer受权路径
                            options.ApiName = "order";  //须要受权的服务名称
                        });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
       //启用Authentication中间件
            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
复制代码

    c) 对cz.Api.Order项目中WebApi添加[Authorize]特性    

复制代码
[Route("identity")]
[ApiController]
[Authorize]
 public class IdentityController : ControllerBase
{
}
复制代码

   d) 此时调用该服务时提示401,以下图:

    

 

   e) 能够经过client信息获取token,而后经过Header传递token 调用weapi

  

 

    

3、总结

  经过上面的例子,很简单就实现了WepApi的认证受权效果;主要步骤以下:

  • 前往IdentityServer服务中,设置须要请求的ApiResource,Client,User内容
  • WebApi服务设置IdentityServerAuthentication地址(对接认证服务)
  • 调用WebApi时,先在IdentityServer中根据设置的方式获取access token,再带着access token请求接口才能正常访问

4、后续

  IdentityServer包含的内容有不少,准备从多个内容来学习记录使用IdentityServer的功能:SSO(单点登陆)、各类受权模式使用、三方帐号登陆……

  最后来实现一个本身的统一身份认证服务 诺顿教育