using IdentityServer4.Models; using IdentityServer4.Validation; using QM.AuthServer.IRepository; using QM.AuthServer.Models.Users; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using WS; using WS.Helper; namespace QM.AuthServer.Auth { /// /// 资源所有者密码验证程序 /// public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { private IAuthorizationRepository authorizationRepository; private ISysUserRepository _ISysUserRepository; public ResourceOwnerPasswordValidator( IAuthorizationRepository _authorizationRepository, ISysUserRepository ISysUserRepository ) { this.authorizationRepository = _authorizationRepository; this._ISysUserRepository = ISysUserRepository; } public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { SysUser loginUser = null; if (context.Password == "@AUTH@") { loginUser = _ISysUserRepository.Get(t=>t.uid == context.UserName); //同步 if(loginUser == null) { } } else { loginUser = authorizationRepository.Login(new LoginDto() { Id = context.UserName, Pwd = context.Password }); } if (loginUser == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Invalid client credential"); } else { context.Result = new GrantValidationResult( subject: context.UserName, authenticationMethod: "custom", claims: new Claim[] { new Claim("UserId", loginUser.uid), new Claim("UserName", loginUser.name), new Claim("UserImg", loginUser.img) } ); } } public async Task ValidateAsync2(ResourceOwnerPasswordValidationContext context) { SysUser loginUser = null; var mode = ConfigHelper.Configuration["Auth:Mode"]; if(mode.ToUpper() == "PT") { var url = ConfigHelper.Configuration["Auth:PT_Ticket"]; using (HttpClient http = new HttpClient()) { var result = await http.GetAsync(url + context.Password); if (result.IsSuccessStatusCode) { string msg = await result.Content.ReadAsStringAsync(); var res = msg.ToModel(); if (res.code == 200) loginUser = new SysUser() { uid = res.data.userInfo.NO, name = res.data.userInfo.NAME }; } } } else { loginUser = authorizationRepository.Login(new LoginDto() { Id = context.UserName, Pwd = context.Password }); } if (loginUser == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Invalid client credential"); } else { context.Result = new GrantValidationResult( subject: context.UserName, authenticationMethod: "custom", claims: new Claim[] { new Claim("UserId", loginUser.uid), new Claim("UserName", loginUser.name), new Claim("UserImg", loginUser.img) } ); } } } }