重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
本篇內容介紹了“如何在Ocelot網關中實現IdentityServer4密碼模式”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
概述
成都創新互聯公司主營平潭網站建設的網絡公司,主營網站建設方案,app開發定制,平潭h5微信小程序開發搭建,平潭網站營銷推廣歡迎平潭等地區企業咨詢
IdentityServer4 是為ASP.NET Core 2.系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 認證框架。將identityserver部署在你的應用中,具備如下的特點可以為你的應用(如網站、本地應用、移動端、服務)做集中式的登錄邏輯和工作流控制。IdentityServer是完全實現了OpenID Connect協議標準。在各種類型的應用上實現單點登錄登出。為各種各樣的客戶端頒發access token令牌,如服務與服務之間的通訊、網站應用、SPAS和本地應用或者移動應用等。
OAuth 2.0 默認四種授權模式(GrantType):
授權碼模式(authorization_code)
簡化模式(implicit)
密碼模式(password)
客戶端模式(client_credentials)
我們一般項目在api訪問的時候,大部分是基于賬號密碼的方式進行訪問接口。比如app端的用戶。
下面我們來看下怎么實現密碼模式(password)。主要實現方式
1、在認證項目中,創建ProfileServicepublic class ProfileService : IProfileService { public async Task GetProfileDataAsync(ProfileDataRequestContext context) { var claims = context.Subject.Claims.ToList(); context.IssuedClaims = claims.ToList(); } public async Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; } }
2、創建ResourceOwnerPasswordValidator,進行賬號密碼認證public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { //根據context.UserName和context.Password與數據庫的數據做校驗,判斷是否合法 if (context.UserName == "conan" && context.Password == "123") { context.Result = new GrantValidationResult( subject: context.UserName, authenticationMethod: "custom", claims: new Claim[] { new Claim("Name", context.UserName), new Claim("UserId", "111"), new Claim("RealName", "conan"), new Claim("Email", "373197550@qq.com") }); } else { //驗證失敗 context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential"); } } }
3、調整AllowedGrantTypes 和AllowedScopesclient.AllowedGrantTypes = GrantTypes.ResourceOwnerPassword; List
//注冊服務 var idResources = new List
5、在認證項目進行驗證,測試成功
6、修改地址,在網關項目進行認證,測試成功
代碼地址:
https://gitee.com/conanOpenSource_admin/Example