
文中摘自微信公众平台「UP技术控」,作者conan5566。转截文中请联络UP技术控微信公众号。
简述
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
publicclassProfileService:IProfileService{publicasyncTaskGetProfileDataAsync(ProfileDataRequestContextcontext){varclaims=context.Subject.Claims.ToList();context.IssuedClaims=claims.ToList();}publicasyncTaskIsActiveAsync(IsActiveContextcontext){context.IsActive=true;}}
2、创建ResourceOwnerPasswordValidator,开展账户密码认证
publicclassResourceOwnerPasswordValidator:IResourceOwnerPasswordValidator{publicasyncTaskValidateAsync(ResourceOwnerPasswordValidationContextcontext){//依据context.UserName和context.Password与数据库查询的信息做校检,分辨是不是合理合法if(context.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 和AllowedScopes
client.AllowedGrantTypes=GrantTypes.ResourceOwnerPassword;List<string>aas=newList<string>();aas.AddRange(config.AllowedScopes);aas.Add(IdentityServerConstants.StandardScopes.OpenId);aas.Add(IdentityServerConstants.StandardScopes.Profile);client.AllowedScopes=aas.ToArray();
4、ConfigureServices提升AddInMemoryIdentityResources、AddResourceOwnerValidator、AddProfileService
//申请注册服务varidResources=newList<IdentityResource>{newIdentityResources.OpenId(),//务必要加上,不然报失效的scope不正确newIdentityResources.Profile()};varsection=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、修改地址,在网关ip新项目开展验证,检测取得成功

编码详细地址:
https://gitee.com/conanOpenSource_admin/Example