IdentityServer4學習及簡單使用

本文,主要用來記錄IdentityServer4的簡單使用。javascript

一. IdentityServer的預備知識

要學習IdentityServer,須要瞭解下基於Token的驗證體系,其中涉及到Token, OAuth&OpenID,JWT,協議規範等。html

如圖過程,java

 

二.  IdentityServer簡單介紹

IdentityServer4 是一個基於OpenID ConnectOAuth 2.0的針對ASP.NET Core 2.0的框架,以中間件的形式存在。git

一般你能夠構建(或從新使用)包含登陸和註銷頁面的應用程序,IdentityServer中間件會向其添加必要的協議頭,以便客戶端應用程序可使用這些標準協議與其對話。github

咱們能夠用IdentityServer來作什麼?web

  1. 身份驗證服務:官方認證的OpenID Connect實現
  2. 單點登陸/註銷(SSO)
  3. 訪問受控的API : 爲不一樣的客戶提供訪問API的令牌,好比:MVC網站、SPAMobile APP
  4. ...等等

三.簡單項目示例

先列出目錄結構,以及建立順序,來方便閱讀json

IdentityServerDemo --> APIService1和APIService2 --> MVCClientapi

其中,處MVCClient是asp.net core web mvc項目外,其餘都是asp.net core web api 項目服務器

建立名爲IdentityServerDemo的認證服務

1. 建立一個asp.net core web api項目:IdentityServerDemocookie

注意,不要設置HTTPS,不然後面使用postman測試時,會no response

2. 添加InMemoryConfiguration

public class InMemoryConfiguration
    {
        public static IConfiguration Configuration { get; set; }
        /// <summary>
        /// Define which APIs will use this IdentityServer
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApiResources()
        { 
            return new[]
            {
                new ApiResource("clientservice", "CAS Client Service"),
                new ApiResource("productservice", "CAS Product Service"),
                new ApiResource("agentservice", "CAS Agent Service")
            };
        }

        /// <summary>
        /// Define which Apps will use thie IdentityServer
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "client.api.service",
                    ClientSecrets = new [] { new Secret("clientsecret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "clientservice" }
                },
                new Client
                {
                    ClientId = "product.api.service",
                    ClientSecrets = new [] { new Secret("productsecret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "clientservice", "productservice" }
                },
                new Client
                {
                    ClientId = "agent.api.service",
                    ClientSecrets = new [] { new Secret("agentsecret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "agentservice", "clientservice", "productservice" }
                }
            };
        }

        /// <summary>
        /// Define which uses will use this IdentityServer
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<TestUser> GetUsers()
        {
            return new[]
            {
                new TestUser
                {
                    SubjectId = "10001",
                    Username = "test1@hotmail.com",
                    Password = "test1password"
                },
                new TestUser
                {
                    SubjectId = "10002",
                    Username = "test2@hotmail.com",
                    Password = "test2password"
                },
                new TestUser
                {
                    SubjectId = "10003",
                    Username = "test3@hotmail.com",
                    Password = "test3password"
                }
            };
        }
    }
View Code

3. 使用nuget管理器,添加IdentityServer4 ,而且修改StartUp.cs

修改StartUp.cs中的Configure方法

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //啓用IdentityServer
            app.UseIdentityServer();
            app.UseMvc();
        }

修改StartUp.cs中的ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
        {
            //添加IdentityServer
            services.AddIdentityServer()
                       .AddDeveloperSigningCredential()
                       .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
                       .AddInMemoryClients(InMemoryConfiguration.GetClients())
                       .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

這個主要是爲了把IdentityServer註冊到容器中,須要對其進行配置,而這個配置主要包含三個信息:

  1. 哪些api可使用這個AuthorizationServer
  2. 哪些client可使用這個AuthorizationServer
  3. 哪些User能夠被這個AuthorizationServer識別並受權

這裏的AuthorizationServer 指的就是這個項目的服務:用來認證及受權使用的.

這裏是使用基於內存的方式。

對於Token簽名須要一對公鑰和私鑰,IdentityServer爲開發者提供了一個AddDeveloperSigningCredential()方法,它會幫咱們搞定這個事情而且存儲到硬盤。當切換到正式環境,須要使用真正的證書,更換爲

public void ConfigureServices(IServiceCollection services)
    {
        InMemoryConfiguration.Configuration = this.Configuration;

        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
            .AddInMemoryClients(InMemoryConfiguration.GetClients())
            .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());
    }
View Code

此項目,暫時不使用正式的證書了。

4.使用postman獲取token

啓動咱們的IdentityServerDemo 項目,

而後使用postman發送請求

5.引入QuickStartUI

IdentityServer爲咱們提供了一套UI以使咱們能快速的開發具備基本功能的認證/受權界面,下載地址:QuickStartUI

QuickStartUI引入到咱們的項目中,目錄結構以下:

5.修改StartUp.cs

修改Configure方法

添加靜態文件中間件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //啓用IdentityServer
            app.UseIdentityServer();
            //for QuickStart-UI 啓用靜態文件
            app.UseStaticFiles();
            //app.UseMvc();
            app.UseMvcWithDefaultRoute(); //這裏帶有默認的路由
        }

6.運行程序

登陸

點擊here

登出

 

IdentityServer集成API Service

1.  添加asp.net core web api項目

注意,這裏也是使用http方式;

2.nuget中安裝IdentityServer4.AccessTokenValidation 

3.修改StartUp.cs文件

修改configureServices方法

public void ConfigureServices(IServiceCollection services)
        {
            //IdentityServer
            services.AddMvcCore().AddAuthorization().AddJsonFormatters();
            services.AddAuthentication(Configuration["Identity:Scheme"])
                        .AddIdentityServerAuthentication(options =>
                        {
                            options.RequireHttpsMetadata = false; //是否須要https
                            options.Authority = $"http://{Configuration["Identity:IP"]}:{Configuration["Identity:Port"]}";  //IdentityServer受權路徑
                            options.ApiName = Configuration["Service:Name"];  //須要受權的服務名稱
                        });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

修改Configure方法

UseMvc()以前啓用Authentication中間件

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

            //啓用Authentication中間件
            app.UseAuthentication();

            app.UseMvc();
        }

修改appsettings.json文件

{
  "Service": {
    "Name": "clientservice", //本服務的名稱
    "Port": "53064",  //本服務的端口號,根據本身服務啓動時的端口號進行更改 "DocName": "clientservice",
    "Version": "v1",
    "Title": "CAS Client Service API",
    "Description": "CAS Client Service API provide some API to help you get client information from CAS",
    "Contact": {
      "Name": "CAS 2.0 Team",
      "Email": "EdisonZhou@manulife.com"
    },
    "XmlFile": "Manulife.DNC.MSAD.IdentityServer4Test.ApiService01.xml"
  },
  "Identity": { //去請求受權的Identity服務,這裏即IdentityServerDemo的服務啓動時的地址
    "IP": "localhost",
    "Port": "49363",  //IdentityServerDemo項目啓動時的端口號,根據實際狀況修改 "Scheme": "Bearer"
  }
}

 上面是APIService1的添加,對應的服務名稱是clientservice;

 APIService2與之相似,只是把appsettings.json中的clientservice改成productservice.

4. APIService1APIService2Controller添加[Authorize]特性

 [Authorize]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        ......
    }

 

5. 測試

注意,這裏模擬的是clientservice服務(APIService1)去認證服務器請求token的過程,因此請求到token,也應該在獲取clientservice相關受權的時候攜帶這個token.

 

 

若是在請求productservice的受權服務中,使用clientservicetoken則會顯示未受權

過程總結:

  1. 首先,在受權服務中,設置須要請求的ApiResource,client,user
  2. postman(至關於client)中,輸入client的相關信息(client_id,client_serect)去請求token
  3. 而後就能夠根據受權服務中相應client的AllowedScopes設置的範圍來請求服務了。

受權服務中的client設置

IdentityServer集成MVC Web Application

1. 新建一個ASP.NET Core MVC項目:MVCClient

 2.爲指定方法添加[Authorize]特性

咱們爲HomeController下的Privacy方法上添加Authorize特性

     [Authorize]
        public IActionResult Privacy()
        {
            return View();
        }

這個時候,直接訪問Privacy,會報錯

而咱們但願的效果是:當用戶第一次點擊Privacy,頁面重定向到驗證服務(IdentityServerDemo),當用戶登陸驗證受權後,再重定向到該網站。

此後必定時間範圍內的第二次,第三次點擊,都不須要再重定向到驗證服務,而是直接讀取保存的token.

3.  MVCClient項目添加OpenID Connect Authentication

而這部分主要集中於作Authentication(身份驗證)而非Authorization(受權)

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //這部分主要是作身份驗證的(Authentication),而不是受權(Authorization)
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc"; //oidc => open id connect
            })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = $"http://{Configuration["Identity:IP"]}:{Configuration["Identity:Port"]}";
                options.RequireHttpsMetadata = false;
                options.ClientId = "cas.mvc.client.implicit";
                options.ResponseType = "id_token token";  //容許返回access token
                options.SaveTokens = true;
            });

        }

這裏咱們使用的是implicit這個flow,它主要用於客戶端應用程序(主要指基於javascript的應用),它容許客戶端程序重定向到驗證服務(IdentityServerDemo),然後帶着token重定向回來。

另外,這裏的ResponseType爲」id_token token」,表示既獲取id_token也獲取access_token. 而SaveTokens設置爲true,表示會將從驗證服務返回的token持久化到cookie中,這樣就不用每次請求token了。

另在configure方法中,設置Authentication中間件:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseAuthentication();

            app.UseStaticFiles();
            app.UseCookiePolicy();

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

主要Authentication中間件,要再UseMvc以前。

4. 修改app.settings

{
  "Service": {
    "Name": "cas.mvc.client.implicit", //本服務的名稱
    "Port": "56458",  //服務端口號,根據實際狀況調整
    "DocName": "cas.mvc.client.implicit",
    "Version": "v1",
    "Title": "CAS Client Service API",
    "Description": "CAS Client Service API provide some API to help you get client information from CAS",
    "Contact": {
      "Name": "CAS 2.0 Team",
      "Email": "EdisonZhou@manulife.com"
    },
    "XmlFile": "Manulife.DNC.MSAD.IdentityServer4Test.ApiService01.xml"
  },
  "Identity": { //去請求受權的Identity服務
    "IP": "localhost",
    "Port": "49363"
  }
}

其中port根據本身此服務啓動後的端口號修改

5.在驗證服務(IdentityServerDemo)中添加MvcClient

修改 InMemoryConfiguration 中的GetClients方法:

public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "client.api.service",
                    ClientSecrets = new [] { new Secret("clientsecret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "clientservice" }
                },
                new Client
                {
                    ClientId = "product.api.service",
                    ClientSecrets = new [] { new Secret("productsecret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "clientservice", "productservice" }
                },
                new Client
                {
                    ClientId = "agent.api.service",
                    ClientSecrets = new [] { new Secret("agentsecret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "agentservice", "clientservice", "productservice" }
                },
                new Client { ClientId = "cas.mvc.client.implicit", ClientName = "CAS MVC Web App Client", AllowedGrantTypes = GrantTypes.Implicit, RedirectUris = { $"http://localhost:56458/signin-oidc" }, PostLogoutRedirectUris = { $"http://localhost:56458/signout-callback-oidc" }, AllowedScopes = new [] { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "agentservice", "clientservice", "productservice" }, AllowAccessTokensViaBrowser = true // can return access_token to this client
 },
            };
        }

這裏ClientId要和MvcClient中設置的同樣。

RedirectUris是指登陸成功之後須要重定向的地址(即重定向到MvcClient中的地址)

PostLogoutRedirectUris是指登出以後須要重定向的地址。

API Service Client的設置不一樣的就是AllowedScopes中給它增長了OpenIdProfile,由於咱們爲MvcClient設定的是oidc而不是bearer模式。

最後爲了使用這些OpenID Connect Scopes,須要設置這些Identity Resources。

 

InMemoryConfiguration 中增長GetIdentityResources方法:

public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

ConfigureServices方法中修改:

 public void ConfigureServices(IServiceCollection services)
        {
            //添加IdentityServer
            services.AddIdentityServer()
                       .AddDeveloperSigningCredential()
                       .AddInMemoryIdentityResources(InMemoryConfiguration.GetIdentityResources())
                       .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
                       .AddInMemoryClients(InMemoryConfiguration.GetClients())
                       .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

6. MvcClient項目的Privacy 頁面中修改以下:

@{
    ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>


@using Microsoft.AspNetCore.Authentication
<div>
    <strong>id_token</strong>
    <span>@await ViewContext.HttpContext.GetTokenAsync("id_token")</span>
</div>
<div>
    <strong>access_token</strong>
    <span>@await ViewContext.HttpContext.GetTokenAsync("access_token")</span>
</div>

<dl>
    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dd>@claim.Value</dd>
    }
</dl>

這裏,咱們會把id_token和access_token顯示出來

7. 爲了退出方便,暫時在HomeController下增長Logout方法

 public async Task Logout()
        {
            await HttpContext.SignOutAsync("Cookies");
            await HttpContext.SignOutAsync("oidc");
        } 

8. 簡單測試

啓動IdentityServerDemo這個驗證服務;

啓動MvcClient這個Mvc Web Application服務;

 

 

 

 

這裏沒有添加可點擊的按鈕,可直接在url中修改路徑來登出

 

 

參考網址:

https://www.cnblogs.com/edisonchou/p/identityserver4_foundation_and_quickstart_01.html

 另外推薦edisonchou微服務系列,感受很是棒

 https://github.com/Vincent-yuan/IdentityServerDemo

相關文章
相關標籤/搜索