IdentityServer4使用教程1--搭建ID4网站。

简介

Identity Server 4(以下简称ID4)是一个基于oauth2和OpenID的身份认证组件,基于这个组件可以快速开发自己的身份认证网站,支持单点登录,快速完成工业级的身份认证系统。ID4也是dotnetcore推荐的身份认证组件。
本教程将基于dotnetcore1.1.2来实现一个完整的ID4身份网站,并搭配各种应用来使用这个认证系统。

目前ID4对于dotnetcore2.0.0的支持还有问题,在问题修复后,会升级到.net core 2.0.0

和core一样,ID4也完全支持linux和Mac,大家可以按照下面的步骤,在linux上运行。当然windows上有一个ubuntu的子系统,可以用来验证,就不需要单独去安装linux虚拟机了。关于windows上的ubuntu子系统,可以参看这个教程

环境准备

首先我们需要配置好环境,这里我们使用chocolatey来快速把环境准备好。 关于chocolatey的使用请参看chocolate使用教程。从上到下,我们安装了:

  1. curl用于下载文件.
  2. git用于管理代码,在本教程中主要是比较修改的文件。
  3. visualstudiocode主要是用于编辑代码。
  4. dotnetcore-sdk安装了两个,主要是ID4目前还不支持.net core 2.0.
 choco install cUrl -y
 choco install git -y
 choco install visualstudiocode -y
 choco install dotnetcore-sdk --version 1.1.2 -y
 choco install dotnetcore-sdk --version 2.0.0 -y

准备asp.net core MVC基础代码

  1. 使用管理员权限打开一个CMD窗口
  2. 创建目录并进入这个目录mkdir ID4.Learn && cd ID4.Learn
  3. 在根目录下创建global.json文件以便切换dotnet 2.0.0 到1.0.4版本
    {
        "sdk": { "version": "1.0.4"  }
     }
    

    也可以使用下面的命令从github直接下载这个文件
    curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/global.json

  4. 运行dotnet CLI命令创建一个带Identity的MVC框架程序ID4.Server
    dotnet new mvc -au Individual -o ID4.Server

    dotnet CLI的命令参数,可以通过dotnet -h来查看
    此处的-au Individual表示生成的MVC文件带有认证信息, -o ID4.Server表示输出到ID4.Server目录,项目名称也是ID4.Server.

  5. 转到ID4.Server目录下,运行下面命令来查看生成的MVC程序
    cd ID4.Server
    dotnet restore
    dotnet build
    dotnet run
    

    在dotnet 2.0以后,运行dotnet run的时候会自动运行dotnet restoredotnet build
    运行结果如下:

《IdentityServer4使用教程1--搭建ID4网站。》 运行输出

好了,web服务已经启动监听5000端口,我们打开浏览器访问
http://localhost:5000。结果如下图: asp.net core的网站已经成功跑起来了!!

《IdentityServer4使用教程1--搭建ID4网站。》 网站输出

添加ID4的支持

1. 添加ID4的组件

首先我们需要添加ID4的assembly, 在ID4.Server目录下运行dotnet add package IdentityServer4.AspNetIdentity。因为IdentityServer4.AspNetIdentity会引用IdentityServer4,所以我们不需要单独在添加它了。

2. 增加oauth2的配置信息

我们现在来为mvc程序添加ID4所需要的配置信息。主要是添加三个静态方法GetIdentityResources来返回支持的Claim种类。GetApiResources来返回支持的webapi资源,GetClients来返回支持的客户端信息。包括客户ID,密码等信息。

    public class Config
    {
        // scopes define the resources in your system
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("api1", "My API")
            };
        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            // client credentials client
            return new List<Client>
            {
                new Client
                {
                    ClientId = "mvc",
                    ClientName = "MVC Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    RequireConsent = false,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    RedirectUris           = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api1"
                    },
                    AllowOfflineAccess = true
                }
            };
        }
    }

运行下面的命令,可以直接从github下载上述config.cs
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/ID4.Server/Config.cs

3. 注册ID4的服务

准备好了ID4的配置文件后,现在需要来注入ID4的服务了。在startup.cs文件的ConfigureServices方法中注入IdentityService。

 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            // Adds IdentityServer
           services.AddIdentityServer()
                    .AddTemporarySigningCredential()
                    .AddInMemoryIdentityResources(Config.GetIdentityResources())
                    .AddInMemoryApiResources(Config.GetApiResources())
                    .AddInMemoryClients(Config.GetClients())
                    .AddAspNetIdentity<ApplicationUser>(); 
        }

4. 使用ID4的服务

在注入了ID4的服务后,我们需要使用ID4的服务了。在startup.cs文件的Configure方法中使用Identity。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Adds IdentityServer
            app.UseIdentityServer(); 

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

修改完成的Startup.cs文件,可以通过下面的命令直接下载
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/ID4.Server/Startup.cs

5. 重新编译运行

好了,所有的工作都做完了,我们可以运行新的网站了,使用下面的命令重新运行网站。

dotnet restore
dotnet build
dotnet run

检查确认ID4服务器已经配置好了。

在浏览器中访问http://localhost:5000/.well-known/openid-configuration地址,查看ID4的配置信息,如果返回结果类似于下图,那么恭喜,ID4的认证服务器已经成功建立!!😂

《IdentityServer4使用教程1--搭建ID4网站。》 OpenID信息

下一节,我们会配置一个MVC客户端来使用这个ID4认证服务器

    原文作者:灭蒙鸟
    原文地址: https://www.jianshu.com/p/84e96789d65a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞