private void btnDecryption_Click(object sender, EventArgs e) { if (txt1.Text.Length > 0 && txtKey.Text.Length == 32) { txt2.Text = AesHelper.AesDecrypt(txt1.Text, txtKey.Text); } }
private T Deserialize(byte[] buffer) { var data = buffer; if (_isEncrypted) { try { data = AesHelper.AesDecrypt(data, GetBytes(_encKey)); } catch (CryptographicException) { throw new ProtobufChannelEncryptionException( "Object integrity invalid, maybe supplied wrong encryption key?"); } } if (_isCompressed) { data = QuickLZ.decompress(data); } using (var ms = new MemoryStream(data)) { return(Serializer.Deserialize <T>(ms)); } }
/// <summary> /// 测试aes加密 /// </summary> public void TestAesHelper() { var testStr = "FreshMan"; var enCodeStr = AesHelper.AesEncrypt(testStr); var deCodeStr = AesHelper.AesDecrypt(enCodeStr); deCodeStr.IsEqualTo(testStr); }
private MySqlHelper() { try { this.ConnectionString = AesHelper.AesDecrypt(ConfigurationManager.AppSettings["mySqlStr"], _dbStrKey); } catch (Exception exception) { LogHelper.error("获取数据库连接字符串失败", exception); } }
public void OnAuthorization(AuthorizationFilterContext filterContext) { filterContextInfo = new FilterContextInfo(filterContext); if (filterContextInfo.ControllerName == "Base") { throw new Exception("禁止访问基类控制器"); } //不用检查 if (Anonymous) { return; } #region 检查认证 try { string token = filterContext.HttpContext.Request.Headers["cat-token"]; try { if (string.IsNullOrEmpty(token)) { throw new Exception("用户身份认证未通过[token不能为空],请求数据失败"); } token = AesHelper.AesDecrypt(token); var auth = Serializer.JsonDeserialize <Cat.M.Book.Models.ModelBinder.ReturnModels.BookAuth>(token); if (string.IsNullOrEmpty(auth.Openid)) { throw new Exception("用户身份认证未通过[找不到指定的openid],请求数据失败"); } } catch (Exception ex) { if (string.IsNullOrEmpty(ex.Message)) { throw new Exception("用户身份认证未通过,请求数据失败"); } else { throw ex; } } } catch (Exception ex) { Microsoft.AspNetCore.Mvc.ContentResult contentResult = new Microsoft.AspNetCore.Mvc.ContentResult(); contentResult.Content = ActionRes.Fail(ex.Message).ToJson(); filterContext.Result = contentResult; return; } #endregion }
/// <summary> /// 注入数据库上下文 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> public static void AddCustomDbContent(this IServiceCollection services, IConfiguration configuration) { services.AddSetting <DataSettings>(configuration.GetSection("DataSettings")); var dataSetting = services.BuildServiceProvider().GetService <IOptions <DataSettings> >().Value; DataSettingManager.IsInstalled = dataSetting.IsValid; if (dataSetting.IsValid) { if (dataSetting.DataProvider == DataProviderType.SqlServer) { string connectionString = AesHelper.AesDecrypt(dataSetting.ConnectionString, ConstDefine.DataSettingAesKey); //数据库配置 services.AddDbContextPool <Kj1012Context>(options => { options.UseSqlServer( connectionString, b => { b.MigrationsAssembly("KJ1012.Web"); }); }, 180); } } }
protected virtual async Task <LoginResultInfoModel> GetLoginResultAsync(LoginInput input) { var tenantId = CurrentTenant.Id; var tenantChanged = false; MiniProgram miniProgram; if (input.LookupUseRecentlyTenant) { using (_dataFilter.Disable <IMultiTenant>()) { miniProgram = await _miniProgramRepository.FirstOrDefaultAsync(x => x.AppId == input.AppId); } } else { miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); } var code2SessionResponse = await _loginService.Code2SessionAsync(miniProgram.AppId, miniProgram.AppSecret, input.Code); _signatureChecker.Check(input.RawData, code2SessionResponse.SessionKey, input.Signature); var openId = code2SessionResponse.OpenId; var unionId = code2SessionResponse.UnionId; if (input.LookupUseRecentlyTenant) { using (_dataFilter.Disable <IMultiTenant>()) { tenantId = await _miniProgramUserRepository.FindRecentlyTenantIdAsync(input.AppId, openId, true); } if (tenantId != CurrentTenant.Id) { tenantChanged = true; } } using var tenantChange = CurrentTenant.Change(tenantId); if (tenantChanged) { miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); } // 如果 auth.code2Session 没有返回用户的 UnionId if (unionId.IsNullOrWhiteSpace()) { if (!input.EncryptedData.IsNullOrWhiteSpace() && !input.Iv.IsNullOrWhiteSpace()) { // 方法1:通过 EncryptedData 和 Iv 解密获得用户的 UnionId var decryptedData = _jsonSerializer.Deserialize <Dictionary <string, object> >( AesHelper.AesDecrypt(input.EncryptedData, input.Iv, code2SessionResponse.SessionKey)); unionId = decryptedData.GetOrDefault("unionId") as string; } else { // 方法2:尝试通过 OpenId 在 MiniProgramUser 实体中查找用户的 UnionId // Todo: should use IMiniProgramUserStore unionId = await _miniProgramUserRepository.FindUnionIdByOpenIdAsync(miniProgram.Id, openId); } } string loginProvider; string providerKey; if (unionId.IsNullOrWhiteSpace()) { loginProvider = await _miniProgramLoginProviderProvider.GetAppLoginProviderAsync(miniProgram); providerKey = openId; } else { loginProvider = await _miniProgramLoginProviderProvider.GetOpenLoginProviderAsync(miniProgram); providerKey = unionId; } return(new LoginResultInfoModel { MiniProgram = miniProgram, LoginProvider = loginProvider, ProviderKey = providerKey, UnionId = unionId, Code2SessionResponse = code2SessionResponse }); }
/// <summary> /// 通过微信开放能力获取并给当前用户绑定手机号,更新信息:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html /// </summary> /// <param name="input"></param> /// <returns></returns> /// <exception cref="BusinessException"></exception> /// <exception cref="AbpIdentityResultException"></exception> public async Task BindPhoneNumberAsync(BindPhoneNumberInput input) { await _identityOptions.SetAsync(); var user = await _identityUserManager.GetByIdAsync(CurrentUser.GetId()); var miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); var response = await _loginService.Code2SessionAsync(miniProgram.AppId, miniProgram.AppSecret, input.Code); if (response.ErrorCode != 0) { throw new BusinessException(message: $"WeChat error: [{response.ErrorCode}]: {response.ErrorMessage}"); } var decryptedData = _jsonSerializer.Deserialize <Dictionary <string, object> >(AesHelper .AesDecrypt(input.EncryptedData, input.Iv, response.SessionKey)); var phoneNumber = decryptedData["phoneNumber"] as string; _identityUserManager.RegisterTokenProvider(TokenOptions.DefaultPhoneProvider, new StaticPhoneNumberTokenProvider()); var token = await _identityUserManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber); var identityResult = await _identityUserManager.ChangePhoneNumberAsync(user, phoneNumber, token); if (!identityResult.Succeeded) { throw new AbpIdentityResultException(identityResult); } }
public virtual async Task <string> LoginAsync(LoginInput input) { var miniProgram = await _miniProgramRepository.GetAsync(x => x.AppId == input.AppId); var code2SessionResponse = await _loginService.Code2SessionAsync(miniProgram.AppId, miniProgram.AppSecret, input.Code); _signatureChecker.Check(input.RawData, code2SessionResponse.SessionKey, input.Signature); var openId = code2SessionResponse.OpenId; var unionId = code2SessionResponse.UnionId; if (input.LookupUseRecentlyTenant) { Guid?tenantId; using (_dataFilter.Disable <IMultiTenant>()) { tenantId = await _miniProgramUserRepository.FindRecentlyTenantIdAsync(miniProgram.Id, openId); } using var tenantChange = CurrentTenant.Change(tenantId); } string loginProvider; string providerKey; // 如果 auth.code2Session 没有返回用户的 UnionId if (unionId.IsNullOrWhiteSpace()) { if (!input.EncryptedData.IsNullOrWhiteSpace() && !input.Iv.IsNullOrWhiteSpace()) { // 方法1:通过 EncryptedData 和 Iv 解密获得用户的 UnionId var decryptedData = _jsonSerializer.Deserialize <Dictionary <string, object> >( AesHelper.AesDecrypt(input.EncryptedData, input.Iv, code2SessionResponse.SessionKey)); unionId = decryptedData.GetOrDefault("unionId") as string; } else { // 方法2:尝试通过 OpenId 在 MiniProgramUser 实体中查找用户的 UnionId // Todo: should use IMiniProgramUserStore unionId = await _miniProgramUserRepository.FindUnionIdByOpenIdAsync(miniProgram.Id, openId); } } if (unionId.IsNullOrWhiteSpace()) { loginProvider = await _miniProgramLoginProviderProvider.GetAppLoginProviderAsync(miniProgram); providerKey = openId; } else { loginProvider = await _miniProgramLoginProviderProvider.GetOpenLoginProviderAsync(miniProgram); providerKey = unionId; } var identityUser = await _identityUserManager.FindByLoginAsync(loginProvider, providerKey) ?? await _miniProgramLoginNewUserCreator.CreateAsync(input.UserInfo, loginProvider, providerKey); await UpdateMiniProgramUserAsync(identityUser, miniProgram, unionId, openId, code2SessionResponse.SessionKey); await UpdateUserInfoAsync(identityUser, input.UserInfo); return((await RequestIds4LoginAsync(input.AppId, unionId, openId))?.Raw); }
public void OnAuthorization(AuthorizationFilterContext filterContext) { filterContextInfo = new FilterContextInfo(filterContext); if (filterContextInfo.ControllerName == "Base") { throw new Exception("禁止访问基类控制器"); } ////不用检查 //if (Anonymous) //{ // return; //} //当类和方法都被标记【ApiAuthorizeFilterAttribute】,只取最后一个筛选器配置。即如果类和方法都被标记,则取的是方法上的筛选器 var thisClassObj = filterContext.Filters.Where(w => w.ToString().EndsWith("ApiAuthorizeFilterAttribute")).Last() as ApiAuthorizeFilterAttribute; AuthorityIdentity = thisClassObj.AuthorityIdentity; //标记为“匿名”的方法或类不用检查 if (AuthorityIdentity == AuthorityIdentityEnum.Anonymous) { return; } ErrorCode errorCode = ErrorCode.Default; #region try { try { //检查认证 //string authority = filterContext.HttpContext.Request.Headers["cat-book-antd-pro-authority"]; //string userid = filterContext.HttpContext.Request.Headers["cat-book-antd-pro-userid"]; string token = ApiHelper.AuthToken; if (string.IsNullOrEmpty(token)) { errorCode = ErrorCode.user_no_authority; throw new Exception("用户身份认证未通过[token不能为空],请求数据失败"); } token = AesHelper.AesDecrypt(token); var auth = Serializer.JsonDeserialize <Cat.M.Book.Models.ModelBinder.ReturnModels.ApiAuth>(token); if (string.IsNullOrEmpty(auth.User_Id)) { errorCode = ErrorCode.user_no_authority; throw new Exception(""); } //if (auth.User_Id != userid) throw new Exception(); //检查用户状态 var user = Cat.M.Public.Services.AllServices.SysAccountService.GetSingle(w => w.User_Id == auth.User_Id); if (user == null) { errorCode = ErrorCode.user_not_found; throw new Exception("没有找到用户,可能已被删除"); } if (user.Disable == true) { errorCode = ErrorCode.user_disabled; throw new Exception("当前登录用户已被禁用,请找超级管理员解除"); } if ((user.Password.Substring(0, 5) + user.Password.Substring(user.Password.Length - 5, 5)) != auth.Pwd_Incomplete) { errorCode = ErrorCode.user_pwd_modified; throw new Exception("当前登录用户密码已修改,请重新登录"); } if ((DateTime.Now - auth.LoginTime).TotalDays > Cat.Foundation.ConfigManager.CatSettings.LogonCredentialSaveDay) { errorCode = ErrorCode.user_logon_overdue; throw new Exception("登录凭证已过期,您需要重新登录"); } //检查授权 if (!user.Authority.Split(",", StringSplitOptions.RemoveEmptyEntries).Contains(AuthorityIdentityEnum.Administrator.ToString().ToLower())) { //当前登录用户没有管理员权限 if (AuthorityIdentity == AuthorityIdentityEnum.Administrator) { //当前访问的类或方法被标记为管理员 throw new Exception("当前登录用户没有权限进行此操作"); } } } catch (Exception ex) { if (string.IsNullOrEmpty(ex.Message)) { throw new Exception("用户身份认证未通过,请求数据失败"); } else { throw ex; } } } catch (Exception ex) { Microsoft.AspNetCore.Mvc.ContentResult contentResult = new Microsoft.AspNetCore.Mvc.ContentResult(); contentResult.Content = ActionRes.Fail((int)errorCode, ex.Message).ToJson(); filterContext.Result = contentResult; return; } #endregion }