Core篇——初探IdentityServer4(客戶端模式,密碼模式)


Core篇——初探IdentityServer4(客戶端模式,密碼模式)

目錄

1、Oatuth2協議的客戶端模式介紹
2、IdentityServer4客戶端模式實現
3、Oatuth2協議的密碼模式介紹
4、IdentityServer4密碼模式實現

Oatuth2協議的客戶端模式介紹

    • Client Credentials Grant (客戶端模式)是Oauth2.0協議中,四種模式自建單的一種。它由兩部分構成,客戶端認證服務器。認證服務器確認客戶端無誤后返回一個token,客戶端請求帶着token訪問資源。(一般使用場景是在一個安全的環境下,例如我的同一個系統中,一個api請求另外一個api)。

    •  這里借用下阮一峰老師畫的圖(博客地址=》http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)

       

IdentityServer4客戶端模式實現

  • 首先我們創建一個core的api項目作為認證服務器,添加nuget程序包IdentityServer4,將啟動端口設置為5000
  • 接下來添加一個類,取名字叫做Config,我們用它來初始化Identityserver(配置要保護的資源和可以訪問該API的客戶端服務器)。
    代碼如下:
/// <summary>
/// Idnetity配置,初始化Identityserver
/// </summary>
public class Config
{
//定義要保護的資源(webapi)
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
//定義可以訪問該API的客戶端
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, //設置模式,客戶端模式
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
}
  • 接下來配置startup,將資源和客戶端的初始信息服務加入到DI容器,同時引用IdentityServer中間件。代碼如下所示:
        public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources()) //配置資源
.AddInMemoryClients(Config.GetClients()); //配置客戶端
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//使用identityserver中間件
app.UseIdentityServer();
app.UseMvc();
}
  • 再添加一個webapi項目,作為我們的資源服務器。添加nuget包,IdentityServer4.AccessTokenValidation,將啟動端口設置為5001
  • 2、配置startup,添加認證服務器地址,和apiname &&引用中間件,代碼如下:
        public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000"; //配置Identityserver的授權地址
options.RequireHttpsMetadata = false; //不需要https
options.ApiName = "api1"; //api的name,需要和config的名稱相同
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();// 添加認證中間件
app.UseMvc();
}
    • 將受保護資源controller添加[Authorize]。(因為資源服務器AddIdentityServerAuthentication 方法的參數和返回值都是AuthenticationBuilder(類似於一個中間件),所以可以多次調用AddIdentityServerAuthentication方法來控制這個api 資源可以讓誰訪問到。)
    • 最開始我們直接訪問資源服務器的api,返回401,因為我們的資源被保護了。
    • 這時候來到IdentityServer4的官網,官網給出了這么一個地址=》
    • 我們訪問這個地址時候,它會返回我們的Config配置=》
    • 其中有一個token_endpoint的url地址,我們帶着Client的配置來訪問它=》
    • 此時拿到Token,再帶着token去訪問我們的資源,爭取獲取到資源數據=》

Oatuth2協議的密碼模式介紹

    • 用戶會將用戶名,密碼給予客戶端,但是客戶端不保存此信息,客戶端帶着用戶的密碼請求認證服務器,認證服務器密碼驗證通過后后將token返回給客戶端。
    •  這里借用下阮一峰老師畫的圖(博客地址=》http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)

IdentityServer4密碼模式實現

  • 我們不需要修改資源服務器,我們在客戶端模式下的認證服務器的Config配置中,添加一個Client,允許我們使用密碼模式訪問授權服務器獲取token,再添加一個測試用戶。同時修改我們的startup,在ConfigureServices方法中配置測試用戶,代碼如下所示:
 //定義可以訪問該API的客戶端
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, //設置模式,客戶端模式
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
},
new Client()
{
ClientId="pwdClient",
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, //密碼模式
ClientSecrets= {new Secret("secret".Sha256()) },
AllowedScopes= { "api1" }
}
};
}
public static List<TestUser> GetTestUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId="1",
Username="lmc",
Password="123456"
}
};
}
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources()) //配置資源
.AddInMemoryClients(Config.GetClients()) //配置客戶端
.AddTestUsers(Config.GetTestUsers()); //配置測試用戶
services.AddMvc();
}

此時我們使用我們定義的用戶名和密碼來訪問我們的授權服務器(這里使用postman 要注意body的數據格式為x-www-form-urlencoded)=》

帶着我們拿到的token,去訪問資源=》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM