public async Task AddLoginAsync() { using (var uow = _unitOfWorkManager.Begin()) { var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.Normalize("john.nash")); user.ShouldNotBeNull(); user.Logins.ShouldNotContain(x => x.LoginProvider == "facebook" && x.ProviderKey == "john"); await _identityUserStore.AddLoginAsync(user, new UserLoginInfo("facebook", "john", "John Nash")); user.Logins.ShouldContain(x => x.LoginProvider == "facebook" && x.ProviderKey == "john"); await uow.CompleteAsync(); } }
public async Task <object> MiniAuth(WeChatMiniProgramAuthenticateModel loginModel, string appName) { var app = await _appProvider.GetOrNullAsync(appName); var appid = app["appid"] ?? throw new AbpException($"App:{appName} appid未设置"); var appSec = app["appsec"] ?? throw new AbpException($"App:{appName} appsec未设置"); var session = await _weixinManager.Mini_Code2Session(loginModel.code, appid, appSec); // 解密用户信息 var miniUserInfo = await _weixinManager.Mini_GetUserInfo(appid, loginModel.encryptedData, session.session_key, loginModel.iv); miniUserInfo.AppName = appName; // 更新数据库 await _capBus.PublishAsync("weixin.services.mini.getuserinfo", miniUserInfo); var token = ""; var user = await _identityUserStore.FindByLoginAsync($"unionid", miniUserInfo.unionid); if (user == null) { var userId = _guidGenerator.Create(); user = new IdentityUser(userId, miniUserInfo.unionid, $"{miniUserInfo.unionid}@somall.top", _currentTenant.Id) { Name = miniUserInfo.nickName }; using (var uow = _unitOfWorkManager.Begin(requiresNew: true)) { var passHash = _passwordHasher.HashPassword(user, "1q2w3E*"); await _identityUserStore.CreateAsync(user); await _identityUserStore.SetPasswordHashAsync(user, passHash); await _identityUserStore.AddLoginAsync(user, new UserLoginInfo($"unionid", miniUserInfo.unionid, "unionid")); await _identityUserStore.AddLoginAsync(user, new UserLoginInfo($"{appid}_openid", miniUserInfo.openid, "openid")); await _unitOfWorkManager.Current.SaveChangesAsync(); await uow.CompleteAsync(); } } var serverClient = _httpClientFactory.CreateClient(); var disco = await serverClient.GetDiscoveryDocumentAsync(_configuration["AuthServer:Authority"]); var result = await serverClient.RequestTokenAsync( new TokenRequest { Address = disco.TokenEndpoint, GrantType = "UserWithTenant", ClientId = _configuration["AuthServer:ClientId"], ClientSecret = _configuration["AuthServer:ClientSecret"], Parameters = { { "user_id", $"{user.Id}" }, { "tenantid", $"{user.TenantId}" }, { "scope", "SoMall" } } }); token = result.AccessToken; return(await Task.FromResult(new { AccessToken = token, ExternalUser = miniUserInfo, SessionKey = session.session_key })); }
public async Task <object> MiniAuth(WeChatMiniProgramAuthenticateModel loginModel) { var appId = await _setting.GetOrNullAsync(WeixinManagementSetting.MiniAppId); var appSec = await _setting.GetOrNullAsync(WeixinManagementSetting.MiniAppSecret); var session = await _weixinManager.Mini_Code2Session(loginModel.code, appId, appSec); // 解密用户信息 var miniUserInfo = await _weixinManager.Mini_GetUserInfo(appId, loginModel.encryptedData, session.session_key, loginModel.iv); // 更新数据库 await _capBus.PublishAsync("weixin.services.mini.getuserinfo", miniUserInfo); var token = ""; var user = await _identityUserStore.FindByLoginAsync($"{appId}_unionid", miniUserInfo.unionid); if (user == null) { var userId = Guid.NewGuid(); user = new IdentityUser(userId, miniUserInfo.unionid, $"{miniUserInfo.unionid}@somall.top", _currentTenant.Id); using (var uow = _unitOfWorkManager.Begin()) { var passHash = _passwordHasher.HashPassword(user, "1q2w3E*"); await _identityUserStore.CreateAsync(user); await _identityUserStore.SetPasswordHashAsync(user, passHash); await _identityUserStore.AddLoginAsync(user, new UserLoginInfo($"{appId}_unionid", miniUserInfo.unionid, "unionid")); await _identityUserStore.AddLoginAsync(user, new UserLoginInfo($"{appId}_openid", miniUserInfo.openid, "openid")); await _unitOfWorkManager.Current.SaveChangesAsync(); await uow.CompleteAsync(); return(await Task.FromResult(new { AccessToken = "retry", ExternalUser = miniUserInfo, SessionKey = session.session_key })); } } var serverClient = _httpClientFactory.CreateClient(); var disco = await serverClient.GetDiscoveryDocumentAsync("https://localhost:44380"); var result = await serverClient.RequestTokenAsync( new TokenRequest { Address = disco.TokenEndpoint, GrantType = "password", ClientId = "SoMall_App", ClientSecret = "1q2w3e*", Parameters = { { "UserName", user.UserName }, { "Password", "1q2w3E*" }, { "scope", "SoMall" } } }); token = result.AccessToken; return(await Task.FromResult(new { AccessToken = token, ExternalUser = miniUserInfo, SessionKey = session.session_key })); }
public async Task <MpAuthenticateResultModel> MiniAuth(MpAuthenticateModel loginModel) { try { //var app = await _appProvider.GetOrNullAsync(appName); //var appid = app["appid"] ?? throw new AbpException($"App:{appName} appid未设置"); //var appSec = app["appsec"] ?? throw new AbpException($"App:{appName} appsec未设置"); if (_options == null) { throw new AbpException("小程序未配置"); } var appid = _options.AppId ?? throw new AbpException($"App:{loginModel.appName} appid未设置"); var appSec = _options.AppSecret ?? throw new AbpException($"App:{loginModel.appName} appsec未设置"); var session = await _weixinManager.Mini_Code2Session(loginModel.code, _options.AppId, _options.AppSecret); // 解密用户信息 var miniUserInfo = await _weixinManager.Mini_GetUserInfo(appid, loginModel.encryptedData, session.session_key, loginModel.iv); //miniUserInfo.AppName = appName; // 更新数据库 //await _capBus.PublishAsync("weixin.services.mini.getuserinfo", miniUserInfo); // todo: 如果对应主体下只有一个微信小程序账号,那是获取不到unionId的,只能获得openId // 所以,下面的代码可能需要修正一下 // 当unionid为空的时候, 第一个参数loginProvider可以考虑设置为appid_openid // 对应的 providerKey的值的格式为 {appid}_{OpenId} IdentityUser user = null; if (!String.IsNullOrEmpty(miniUserInfo.unionId)) { user = await _identityUserStore.FindByLoginAsync($"unionid", miniUserInfo.unionId); } if (user == null && !String.IsNullOrEmpty(miniUserInfo.openId)) { user = await _identityUserStore.FindByLoginAsync($"appid_openid", $"{appid}_{miniUserInfo.openId}"); } if (user == null) { var userId = _guidGenerator.Create(); var userName = string.Empty; if (!string.IsNullOrWhiteSpace(miniUserInfo.unionId)) { userName = miniUserInfo.unionId; } else { userName = $"{appid}_{miniUserInfo.openId}"; } user = new IdentityUser(userId, userName, $"{userName}@somall.top", _currentTenant.Id) { Name = miniUserInfo.nickName }; using (var uow = _unitOfWorkManager.Begin(requiresNew: true)) { var passHash = _passwordHasher.HashPassword(user, "1q2w3E*"); await _identityUserStore.CreateAsync(user); await _identityUserStore.SetPasswordHashAsync(user, passHash); if (!string.IsNullOrWhiteSpace(miniUserInfo.unionId)) { await _identityUserStore.AddLoginAsync(user, new UserLoginInfo($"unionid", miniUserInfo.unionId, "unionid")); } await _identityUserStore.AddLoginAsync(user, new UserLoginInfo("appid_openid", $"{appid}_{miniUserInfo.openId}", "openid")); await _unitOfWorkManager.Current.SaveChangesAsync(); await uow.CompleteAsync(); } } var serverClient = _httpClientFactory.CreateClient(); var authServerUrl = _configuration["AuthServer:Authority"]; //var disco = await serverClient.GetDiscoveryDocumentAsync(_configuration["AuthServer:Authority"]); var disco = await serverClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest { Address = authServerUrl, Policy = { ValidateIssuerName = false, ValidateEndpoints = false } }); if (disco.IsError) { throw new AbpException(disco.Error); } var result = await serverClient.RequestTokenAsync( new TokenRequest { Address = disco.TokenEndpoint, GrantType = "UserWithTenant", ClientId = _configuration["AuthServer:ClientId"], ClientSecret = _configuration["AuthServer:ClientSecret"], Parameters = { { "user_id", $"{user.Id}" }, { "tenantid", $"{user.TenantId}" }, { "scope", "BookStore" } } }); var token = result.AccessToken; if (string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token)) { throw new AbpException("从IdentityServer获取Token失败。"); } return(await Task.FromResult(new MpAuthenticateResultModel { AccessToken = token, ExternalUser = miniUserInfo, SessionKey = session.session_key })); } catch (Exception ex) { Log.Logger.Error(ex, "小程序登录验证失败。"); throw; } }