IdentityServer4 实现 OAuth 2.0(密码模式 - HTTP Post 方式)
之前寫了一篇文章:《IdentityServer4 實(shí)現(xiàn) OpenID Connect 和 OAuth 2.0》
上面這篇文章雖然詳細(xì),但都是點(diǎn)到為止的介紹,并沒有實(shí)際應(yīng)用的示例,所以,后面在真正去實(shí)現(xiàn)的時候,踩到了自己之前種下的很多坑。
業(yè)務(wù)場景:前后端分離項(xiàng)目,前端調(diào)用后端業(yè)務(wù)服務(wù)需要授權(quán)訪問(提供access_token),access_token在用戶登錄的時候(用戶名和密碼登錄),由授權(quán)中心生成access_token并返回給前端,這樣前端就可以拿到access_token,去調(diào)用后端業(yè)務(wù)服務(wù)了。
一開始,我使用的GrantTypes.Implicit模式,登錄頁面在授權(quán)中心,登錄成功之后會跳到callback.htm#access_token=*頁面,前端調(diào)用使用oidc-client組件,然后獲取access_token,當(dāng)時使用還沒什么,現(xiàn)在覺得真是一團(tuán)亂麻,前后端分離的項(xiàng)目,在授權(quán)中心居然把登錄頁面放在服務(wù)中了,但我后面還是沒有意識到GrantTypes.Implicit的問題,而是嘗試在這種模式下,寫HTTP Post請求授權(quán)中心(提供用戶名和密碼),然后沒然后,一團(tuán)糟。。。
使用 IdentityServer4 實(shí)現(xiàn)上面的業(yè)務(wù)場景,其實(shí)很簡單,只要使用GrantTypes.GrantTypes.ResourceOwnerPassword模式,就可以了。
Startup.ConfigureServices配置代碼:
var builder = services.AddIdentityServer(); builder.AddTemporarySigningCredential()//.AddInMemoryIdentityResources(Config.GetIdentityResources()).AddInMemoryApiResources(Config.GetApiResources()).AddInMemoryClients(new List<Client>{new Client{ClientId = "client_id_1",AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,AllowOfflineAccess = true,AccessTokenLifetime = 3600 * 6, //6小時SlidingRefreshTokenLifetime = 1296000, //15天ClientSecrets ={new Secret("secret".Sha256())},AllowedScopes ={IdentityServerConstants.StandardScopes.OfflineAccess, "api1"}}}); builder.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();ResourceOwnerPasswordValidator示例代碼:
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator {private readonly IUserService _userService;public ResourceOwnerPasswordValidator(IUserService userService){_userService = userService;}public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context){var userId = await _userService.Login(context.UserName, context.Password);if (userId != 0){context.Result = new GrantValidationResult(userId.ToString(), OidcConstants.AuthenticationMethods.Password);}} }使用ResourceOwnerPasswordValidator的作用,就是自定義用戶登錄的用戶名密碼判斷,而不是使用 IdentityServer4 的TestUser。
請求示例:IdentityServer4 Token Endpoint
獲取access_token請求示例:
刷新access_token請求示例:
也可以服務(wù)端進(jìn)行請求,示例代碼:
private async Task<TokenResponse> GetToken(string clientId, string clientSecret, string grantType, string userName, string password, string scope) {var client = new DiscoveryClient($"http://localhost:5001");client.Policy.RequireHttps = false;var disco = await client.GetAsync();var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);return await tokenClient.RequestResourceOwnerPasswordAsync(userName, password, scope); }private async Task<TokenResponse> GetRefreshToken(string clientId, string clientSecret, string grantType, string refreshToken) {var client = new DiscoveryClient($"http://localhost:5001");client.Policy.RequireHttps = false;var disco = await client.GetAsync();var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);return await tokenClient.RequestRefreshTokenAsync(refreshToken); }參考資料:
- ASP.NET CORE IDENTITYSERVER4 RESOURCE OWNER PASSWORD FLOW WITH CUSTOM USERREPOSITORY
- IResourceOwnerPasswordValidator isn't being called?
- Client scope definition with IResourceOwnerPasswordValidator
- Resource Owner Password Validation
- IdentityServer4 .netCore RefreshToken Example
- IdentityServer4 Refresh Tokens
- IdentityServer4 Client
- IdentityServer4 Discovery Endpoint
總結(jié)
以上是生活随笔為你收集整理的IdentityServer4 实现 OAuth 2.0(密码模式 - HTTP Post 方式)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces 809A - Do
- 下一篇: 使用OKHttp3实现下载(断点续传、显