您现在的位置是:亿华云 > 系统运维

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

亿华云2025-10-02 18:42:00【系统运维】5人已围观

简介概述IdentityServer4 是为ASP.NET Core 2.系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 认证框架。将identityserver部署在你的应

概述

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、在认证项目中,创建ProfileService

public 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 和AllowedScopes

client.AllowedGrantTypes = GrantTypes.ResourceOwnerPassword;                     List<string> aas = new List<string>();                     aas.AddRange(config.AllowedScopes);                     aas.Add(IdentityServerConstants.StandardScopes.OpenId);                     aas.Add(IdentityServerConstants.StandardScopes.Profile);                     client.AllowedScopes = aas.ToArray(); 

4、ConfigureServices增加AddInMemoryIdentityResources、AddResourceOwnerValidator、AddProfileService

//注册服务             var idResources = new List<IdentityResource>             {                new IdentityResources.OpenId(), //必须要添加,否则报无效的 scope 错误               new IdentityResources.Profile()             };             var section = Configuration.GetSection("SSOConfig");             services.AddIdentityServer()          .AddDeveloperSigningCredential()            .AddInMemoryIdentityResources(idResources)          .AddInMemoryApiResources(SSOConfig.GetApiResources(section))          .AddInMemoryClients(SSOConfig.GetClients(section))               .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()             .AddProfileService<ProfileService>();             services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest); 

5、在认证项目进行验证,测试成功

6、修改地址,在网关项目进行认证,测试成功

代码地址: 

https://gitee.com/conanOpenSource_admin/Example

很赞哦!(83)