当前位置: 首页 > 科技观察

每日一技能:在Ocelot网关中实现IdentityServer4密码模式

时间:2023-03-21 22:01:42 科技观察

本文转载自微信公众号《UP技控》,作者conan5566。转载本文请联系UP技控公众号。概述IdentityServer4是一个基于OpenIDConnect和OAuth2.0为ASP.NETCore2.系列量身定制的认证框架。在你的应用中部署identityserver,通过以下特性,你可以对你的应用(如网站、本地应用、移动端、服务)做集中的登录逻辑和工作流控制。IdentityServer完全实现了OpenIDConnect协议标准。对各种类型的应用程序实现单点登录和注销。为各种客户端颁发访问令牌,如服务到服务通信、网站应用、SPAS和本地应用或移动应用等。OAuth2.0默认有四种授权模式(GrantType):授权码模式(authorization_code)简化模式(implicit)密码模式(password)客户端模式(client_credentials)我们一般的项目在访问APIs访问接口的时候,大部分都是根据账号密码来访问的。比如app端的用户。下面来看看密码模式(password)是如何实现的。主要实现方式1、在认证项目中,创建ProfileServicepublicclassProfileService:IProfileService{publicasyncTaskGetProfileDataAsync(ProfileDataRequestContextcontext){varclaims=context.Subject.Claims.ToList();context.IssuedClaims=claims.ToList();}publicasyncTaskIsActiveAsync(IsActiveContextcontext){context.IsActive=true;}}2.创建ResourceOwnerPasswordValidator,用于账号密码认证UserName=="conan"&&context.Password=="123"){context.Result=newGrantValidationResult(subject:context.UserName,authenticationMethod:"custom",claims:newClaim[]{newClaim("Name",context.UserName),newClaim("UserId","111"),newClaim("RealName","conan"),newClaim("Email","373197550@qq.com")});}else{//认证失败败context.Result=newGrantValidationResult(TokenRequestErrors.InvalidGrant,"invalidcustomcredential");}}}3、调整AllowedGrantTypes和AllowedScopesclient.AllowedGrantTypes=GrantTypes.ResourceOwnerPassword;Listaas=newList();aas.AddRange(config.AllowedScopes);aas.Add(IdentityServerConstants.StandardScopes.OpenId);aas.Add(IdentityServerConstants.StandardScopes.Profile);client.AllowedScopes=aas.ToArray();4、ConfigureServices增加AddInMemoryIdentityResources、AddResourceOwnerValidator、AddProfileService//注册服务变量=newList{newIdentityResources.OpenId(),//必须要添加,否则报无效的范围错误newIdentityResources.Profile()};varsection=Configuration.GetSection("SSOConfig");services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryIdentityResources(idResources).AddInMemoryApiResources(SSOConfig.GetApiResources(section)).AddInMemoryClients(SSOConfig.GetClients(section)).AddResourceOwnerValidator().AddProfileService();services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest);5.在认证项目中验证,测试成功6.修改地址,在网关项目中认证,测试成功代码地址:https://gitee.com/conanOpenSource_admin/Example