.Net Core 3.0 IdentityServer4 快速入門02

.Net Core 3.0 IdentityServer4 快速入門

—— resource owner password credentials(密碼模式)

一、前言

OAuth2.0默認有四種授權模式(GrantType):

2)簡化模式

3)密碼模式(resource owner password credentials)

4)客戶端模式(client_credentials)

上一小節 接受了 客戶端模式 ,本小節將介紹 密碼模式,OAuth2.0資源所有者密碼授權功能允許客戶端將用戶名和密碼發送到授權服務器,並獲得該用戶的訪問令牌

認證步驟:

.Net Core 3.0 IdentityServer4 快速入門02

1)用戶將用戶名和密碼提供給客戶端

2)客戶端再將用戶名和密碼發送給授權服務器(Id4)請求令牌

3)授權服務器(Id4)驗證用戶的有效性,返回給客戶端令牌

4)Api資源收到第一個(首次)請求之後,會到授權服務器(Id4)獲取公鑰,然後用公鑰驗證Token是否合法,如果合法將進行後面的有效性驗證,後面的請求都會用首次請求的公鑰來驗證(jwt去中心化驗證的思想)

Resource Owner 其實就是User,密碼模式相較於客戶端模式,多了一個參與者,就是User,通過User的用戶名和密碼向Identity Server 申請訪問令牌,這種模式下要求客戶端不得存儲密碼,但我們並不能確保客戶端是否存儲了密碼,所以該模式僅僅適用於受信任的客戶端。因此該模式不推薦使用

.Net Core 3.0 IdentityServer4 快速入門02

1)安裝Id4

.Net Core 3.0 IdentityServer4 快速入門02

2)創建一個Config類模擬配置要保護的資源和可以訪問的api客戶端服務器

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic;
namespace IdentityServer02
{
public static class Config
{

/// <summary>
/// 需要保護的api資源
/// /<summary>
public static IEnumerable<apiresource> Apis =>
new List<apiresource>
{
new ApiResource("api1","My Api")
};
public static IEnumerable<client> Clients =>
new List<client>
{
//客戶端
new Client
{
ClientId="client",
ClientSecrets={ new Secret("aju".Sha256())},
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,
//如果要獲取refresh_tokens ,必須在scopes中加上OfflineAccess
AllowedScopes={ "api1", IdentityServerConstants.StandardScopes.OfflineAccess},
AllowOfflineAccess=true
}
};
public static List<testuser> Users = new List<testuser>
{
new TestUser
{
SubjectId="001",
Password="Aju_001",
Username="Aju_001"
},
new TestUser
{
SubjectId="002",
Password="Aju_002",
Username="Aju_002"
}
};
}
}
/<testuser>/<testuser>/<client>/<client>/<apiresource>/<apiresource>

與客戶端模式不一致的地方就在於(AllowedGrantTypes=GrantTypes.ResourceOwnerPassword)此處設置為資源所有者(密碼模式)

3)配置StartUp

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace IdentityServer02
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer()
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
.AddTestUsers(Config.Users);19 builder.AddDeveloperSigningCredential();
}
// 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.UseRouting();
app.UseIdentityServer();
}
}
}

5)驗證配置是否成功

在瀏覽器中輸入(http://localhost:5000/.well-known/openid-configuration)看到如下發現文檔算是成功的

.Net Core 3.0 IdentityServer4 快速入門02

三、創建Api資源

2)安裝包

.Net Core 3.0 IdentityServer4 快速入門02

3)創建一個受保護的ApiController

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace Api02.Controllers
{
[Route("Api")]
[Authorize]
public class ApiController : ControllerBase
{

public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}

 4)配置StartUp

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Api02
{
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();
services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
}
// 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.UseRouting();
app.UseAuthentication();//認證
app.UseAuthorization();//授權
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

}
}

四、創建客戶端(控制檯 模擬客戶端)

using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Client02
{
class Program
{
static async Task Main(string[] args)
{
// Console.WriteLine("Hello World!");
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
var tokenResponse = await client.RequestPasswordTokenAsync(
new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "client",
ClientSecret = "aju",
Scope = "api1 offline_access",
UserName = "Aju",
Password = "Aju_password"
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\\n\\n");
//call api
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response = await apiClient.GetAsync("http://localhost:5001/api");
if (!response.IsSuccessStatusCode)

{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
Console.ReadLine();
}
}
}

五、驗證

1)直接獲取Api資源

.Net Core 3.0 IdentityServer4 快速入門02

出現了401未授權提示,這就說明我們的Api需要授權

2)運行客戶端訪問Api資源

.Net Core 3.0 IdentityServer4 快速入門02

六、自定義用戶驗證

在創建授權服務器的時候我們在Config中默認模擬(寫死)兩個用戶,這顯得有點不太人性化,那我們就來自定義驗證用戶信息

1)創建 自定義 驗證 類 ResourceOwnerValidator

using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Threading.Tasks;
namespace IdentityServer02
{
public class ResourceOwnerValidator : IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
if (context.UserName == "Aju" && context.Password == "Aju_password")
{
context.Result = new GrantValidationResult(
subject: context.UserName,
authenticationMethod: OidcConstants.AuthenticationMethods.Password);
}
else
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "無效的秘鑰");
}
return Task.FromResult("");
}
}
}

2)在授權服務器StartUp配置類中,修改如下:

.Net Core 3.0 IdentityServer4 快速入門02

3)在客戶端中將 用戶名 和 密碼 修改成 我們在自定義 用戶 驗證類 中寫的用戶名和密碼,進行測試

七、通過refresh_token 獲取 Token

1)refresh_token

獲取請求授權後會返回 access_token、expire_in、refresh_token 等內容,每當access_token 失效後用戶需要重新授權,但是有了refresh_token後,客戶端(Client)檢測到Token失效後可以直接通過refresh_token向授權服務器申請新的token

.Net Core 3.0 IdentityServer4 快速入門02

八、參考文獻

http://docs.identityserver.io/en/latest/index.html

如果對您有幫助,請點個推薦(讓更多需要的人看到哦)

.Net Core 3.0 IdentityServer4 快速入門02


分享到:


相關文章: