private static void SetToCache(UserToken userToken, EntityToken entityToken, IReadOnlyCollection<PermissionType> permissionTypes, object cachingKey) { // Using RequestLifetimeCache and there for no thread locking /MRJ Dictionary<UserToken, Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>> permissionTypeCache; if (RequestLifetimeCache.HasKey(cachingKey)) { permissionTypeCache = RequestLifetimeCache.TryGet<Dictionary<UserToken, Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>>>(cachingKey); } else { permissionTypeCache = new Dictionary<UserToken, Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>>(); RequestLifetimeCache.Add(cachingKey, permissionTypeCache); } Dictionary<EntityToken, IReadOnlyCollection<PermissionType>> entityTokenPermissionTypes; if (!permissionTypeCache.TryGetValue(userToken, out entityTokenPermissionTypes)) { entityTokenPermissionTypes = new Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>(); permissionTypeCache.Add(userToken, entityTokenPermissionTypes); } if (!entityTokenPermissionTypes.ContainsKey(entityToken)) { entityTokenPermissionTypes.Add(entityToken, permissionTypes); } else { entityTokenPermissionTypes[entityToken] = entityTokenPermissionTypes[entityToken].Concat(permissionTypes).Distinct().ToList(); } }
public static void RemoveUserPermissionDefinition(UserToken userToken, string serializedEntityToken) { if (userToken == null) throw new ArgumentNullException("userToken"); if (string.IsNullOrEmpty(serializedEntityToken)) throw new ArgumentNullException("serializedEntityToken"); _resourceLocker.Resources.Plugin.RemoveUserPermissionDefinition(userToken, serializedEntityToken); }
public BasePage() { // // TODO: 在此处添加构造函数逻辑 // String RealName, NickName, OuterID, CustType, LoginAuthenName, LoginAuthenType; HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName]; if (cookie == null) { CommonBizRules.ErrorHappenedRedircet(result, ErrMsg, "您尚未登录,请登录", this.Context); return; } string strCIPToken = HttpContext.Current.Request.Cookies.Get(CookieName).Value; if (CommonUtility.IsEmpty(strCIPToken)) { CommonBizRules.ErrorHappenedRedircet(result, ErrMsg, "您尚未登录,请登录", this.Context); return; } SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(HttpContext.Current, "SPData"); string key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); UserToken UT = new UserToken(); result = UT.ParseUserToken(strCIPToken, key, out custID, out RealName, out userName, out NickName, out OuterID, out CustType, out LoginAuthenName, out LoginAuthenType, out ErrMsg); //如果验证成功则重新生成Cookie以更新超时时间 if (result == 0) { string UserTokenValue = UT.GenerateUserToken(CustID, RealName, UserName, NickName, OuterID, CustType, LoginAuthenName, LoginAuthenType, key, out ErrMsg); PageUtility.SetCookie(CookieName, UserTokenValue); } //this.custID = "117663768";//117663768,26251932 }
private void UserLoggedIn(AuthenticateCompletedEventArgs args) { currentUser = args.Result; LoginStatusChangedEvent loginEvent = eventAggregator.GetEvent<LoginStatusChangedEvent>(); loginEvent.Publish(currentUser); }
public TokenForm(UserToken token) { InitializeComponent(); this.Disposed += TokenForm_Disposed; _token = token; foreach (object v in Enum.GetValues(typeof(TokenLibrary.TokenIntegrityLevel))) { comboBoxIL.Items.Add(v); comboBoxILForDup.Items.Add(v); } UpdateTokenData(); comboBoxImpLevel.Items.Add(TokenLibrary.TokenImpersonationLevel.Anonymous); comboBoxImpLevel.Items.Add(TokenLibrary.TokenImpersonationLevel.Identification); comboBoxImpLevel.Items.Add(TokenLibrary.TokenImpersonationLevel.Impersonation); comboBoxImpLevel.Items.Add(TokenLibrary.TokenImpersonationLevel.Delegation); comboBoxImpLevel.SelectedItem = TokenLibrary.TokenImpersonationLevel.Impersonation; comboBoxTokenType.Items.Add(TokenLibrary.TokenType.Primary); comboBoxTokenType.Items.Add(TokenLibrary.TokenType.Impersonation); comboBoxTokenType.SelectedItem = TokenLibrary.TokenType.Impersonation; foreach (object v in Enum.GetValues(typeof(TokenLibrary.SaferLevel))) { comboBoxSaferLevel.Items.Add(v); } comboBoxSaferLevel.SelectedItem = SaferLevel.NormalUser; }
public void EndCurrentSession() { currentUser = null; LoginStatusChangedEvent loginEvent = eventAggregator.GetEvent<LoginStatusChangedEvent>(); loginEvent.Publish(currentUser); }
public TenroxIdentity(string token, int userId, UserToken userToken) { if (userToken == null) throw new ArgumentNullException("userToken"); if (string.IsNullOrEmpty(token)) throw new ArgumentNullException("token"); _token = token; _userId = userId; _userToken = userToken; }
/// <summary> /// Gets current user context /// </summary> /// <param name="currentUserToken">current user token</param> /// <returns>current user context</returns> public UserContext GetCurrentUserContext(UserToken currentUserToken) { var userContextInitData = new UserContextInitData(this.contextInitData) { CurrentUserToken = currentUserToken, UserDataProviderResolver = this.userDataProviderResolver, }; return new UserContext(userContextInitData); }
public void ProcessReceive(string argument, UserToken token) { try { token.Send(argument); } catch { } //Console.WriteLine("UserToken{1}:ProcessReceive:{0}", argument, token.Identity); }
public void Release(UserToken userToken) { if (userToken == null) { throw new ArgumentNullException("UserToken cannot be null"); } userToken.Reset(); mPool.Push(userToken); }
public static void Save(UserToken token) { string saveFile = SaveLocation("MP"); saveFile += FileName(); IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, token); stream.Close(); }
protected void CreateSPTokenRequest() { SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string ScoreSystemSecret = spInfo.GetPropertyBySPID(SPID, "SecretKey", SPData); String TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ; UserToken UT = new UserToken(); newSPTokenRequest = UT.GenerateBestAccountMainUserTokenM(CustID, ReturnUrl, TimeStamp, ScoreSystemSecret, out ErrMsg); newSPTokenRequest = HttpUtility.UrlEncode(SPID + "$" + newSPTokenRequest); }
/// <summary> /// Gets meeting context /// </summary> /// <param name="currentUserToken">current user token</param> /// <param name="meetingId">meeting identifier</param> /// <returns>meeting context</returns> public MeetingContext GetMeetingContext(UserToken currentUserToken, int meetingId) { var meetingContextInitData = new MeetingContextInitData(this.contextInitData) { CurrentUserToken = currentUserToken, UserDataProviderResolver = this.userDataProviderResolver, CurrentMeetingId = meetingId, MeetingProviderResolver = this.meetingProviderResolver, }; return new MeetingContext(meetingContextInitData); }
public static void OpenForm(IWin32Window parent, UserToken token, bool copy) { if (token != null) { TokenForm form = new TokenForm(copy ? token.DuplicateHandle() : token); _forms.Add(form); form.FormClosed += form_FormClosed; form.Show(parent); } }
public void LoginStatusChanged(UserToken token ) { if (token == null) return; Username = token.Name; LogoutUserCommand.RaiseCanExecuteChanged(); ContinueCommand.RaiseCanExecuteChanged(); // TODO: Move this somewhere cool (i.e. figure out the proper architectural pattern) regionManager.ActivateViewInRegion<UserSessionView>("login_status_space"); }
/// <summary> /// Gets user data by user token /// </summary> /// <param name="context">context</param> /// <param name="userToken">user token</param> /// <returns>user data</returns> public UserData GetUserData(Context context, UserToken userToken) { int userId = 0; if (!(userToken is AnonymousUserToken)) { var token = userToken as SampleUserToken; Debug.Assert(token != null, "token != null"); userId = token.UserId; } return this.userData[userId]; }
protected void CreateNewSPTokenRequest() { SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string ScoreSystemSecret = spInfo.GetPropertyBySPID(SPID, "SecretKey", SPData); //string RequestStr = CryptographyUtil.Decrypt(EncryptSourceStr.ToString(), ScoreSystemSecret); String _HeadFooter = "yes"; String TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ; UserToken UT = new UserToken(); newSPTokenRequest = UT.GenerateBestAccountMainUserToken(CustID, ReturnUrl, _HeadFooter, TimeStamp, ScoreSystemSecret, out ErrMsg); newSPTokenRequest = HttpUtility.UrlEncode(SPID + "$" + newSPTokenRequest); }
public CreateRestrictedTokenForm(UserToken token) { InitializeComponent(); _token = token; PopulateGroupList(listViewDisableSids, new UserGroup[] { token.GetUser() }); PopulateGroupList(listViewDisableSids, token.GetGroups().Where(g => !g.IsDenyOnly())); foreach (TokenPrivilege priv in token.GetPrivileges()) { ListViewItem item = new ListViewItem(priv.Name); item.SubItems.Add(priv.DisplayName); item.Tag = priv; listViewDeletePrivs.Items.Add(item); } }
// This happens upon a successful login public void GetCoursesForUser(UserToken currentUser) { if (currentUser == null) // no login return; if (availableCourses != null ) { eventAggregator.GetEvent<CourseListReadyEvent>().Publish( availableCourses); return; } LoadCoursesForUserCommand command = new LoadCoursesForUserCommand(currentUser); command.SuccessActions.Add(CourseListReady); command.Execute(); }
public void LoginSucceeded(UserToken token) { IsLoginInProgress = false; LoginCommand.RaiseCanExecuteChanged(); if (token == null) { // handle failed login messaging HasLoginFailed = true; } if (token != null ) { // TODO: Move this somewhere cool (i.e. figure out the proper architectural pattern) regionManager.ActivateViewInRegion<LoginView>("login_status_space"); } }
protected void Page_Load(object sender, EventArgs e) { top_welcome.InnerHtml = welcome; string CookieName = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; if (PageUtility.IsCookieExist(CookieName, this.Context)) { SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); UserToken UT = new UserToken(); string strCIPToken = Request.Cookies.Get(CookieName).Value; string custID; string realName; string userName; string nickName; string outerID; string custType; string loginAuthenName; string loginAuthenType; string errMsg; int result = UT.ParseUserToken(strCIPToken, key, out custID, out realName, out userName, out nickName, out outerID, out custType, out loginAuthenName, out loginAuthenType, out errMsg); if (result==0){ if (realName!=null&&! "".Equals(realName)) { top_name.InnerHtml = "您好," + realName; } else if (nickName != null && !"".Equals(nickName)) { top_name.InnerHtml = "您好," + nickName; } else if (userName != null && !"".Equals(userName)) { top_name.InnerHtml = "您好," + userName; } } } }
public void offline(UserToken token) { throw new NotImplementedException(); }
public User online(UserToken token) { throw new NotImplementedException(); }
User IUserBiz.get(UserToken token) { throw new NotImplementedException(); }
private void ProxyCmdletExecution(CmdletProxyInfo cmdletProxyInfo) { ExAssert.RetailAssert(this.context.ExchangeRunspaceConfig != null, "this.context.ExchangeRunspaceConfig should not be null."); string remoteServerFqdn = cmdletProxyInfo.RemoteServerFqdn; int remoteServerVersion = cmdletProxyInfo.RemoteServerVersion; string friendlyVersionInformation = ProxyHelper.GetFriendlyVersionInformation(remoteServerVersion); CmdletProxyInfo.ChangeCmdletProxyParametersDelegate changeCmdletProxyParameters = cmdletProxyInfo.ChangeCmdletProxyParameters; if (Microsoft.Exchange.Diagnostics.Components.Tasks.ExTraceGlobals.FaultInjectionTracer.IsTraceEnabled(TraceType.FaultInjection)) { Microsoft.Exchange.Diagnostics.Components.Tasks.ExTraceGlobals.FaultInjectionTracer.TraceTest <string>(3720752445U, ref remoteServerFqdn); UserToken userToken = this.context.ExchangeRunspaceConfig.ConfigurationSettings.UserToken; ProxyHelper.FaultInjection_UserSid(ref userToken); Microsoft.Exchange.Diagnostics.Components.Tasks.ExTraceGlobals.FaultInjectionTracer.TraceTest <int>(3452316989U, ref remoteServerVersion); } string text = this.GeneratePswsProxyCmdlet(changeCmdletProxyParameters); ExchangeRunspaceConfigurationSettings.ProxyMethod proxyMethod = this.DetermineProxyMethod(remoteServerVersion); if (this.context.CommandShell != null) { this.context.CommandShell.WriteVerbose(Strings.VerboseCmdletProxiedToAnotherServer(text, remoteServerFqdn, friendlyVersionInformation, proxyMethod.ToString())); } Guid uniqueId = this.context.UniqueId; CmdletLogger.SafeAppendColumn(uniqueId, RpsCmdletMetadata.CmdletProxyRemoteServer, this.proxiedObjectCount.ToString(), remoteServerFqdn); CmdletLogger.SafeAppendColumn(uniqueId, RpsCmdletMetadata.CmdletProxyRemoteServerVersion, this.proxiedObjectCount.ToString(), friendlyVersionInformation.ToString()); CmdletLogger.SafeAppendColumn(uniqueId, RpsCmdletMetadata.CmdletProxyMethod, this.proxiedObjectCount.ToString(), proxyMethod.ToString()); try { IEnumerable <PSObject> enumerable; if (proxyMethod == ExchangeRunspaceConfigurationSettings.ProxyMethod.RPS) { PSCommand command = this.GenerateProxyCmdlet(changeCmdletProxyParameters); Task.TaskWarningLoggingDelegate writeWarning = null; if (this.context.CommandShell != null) { writeWarning = new Task.TaskWarningLoggingDelegate(this.context.CommandShell.WriteWarning); } enumerable = ProxyHelper.RPSProxyExecution(this.context.UniqueId, command, remoteServerFqdn, this.context.ExchangeRunspaceConfig, remoteServerVersion, cmdletProxyInfo.ShouldAsyncProxy, writeWarning); } else { enumerable = CommandInvocation.Invoke(this.context.UniqueId, ProxyHelper.GetPSWSProxySiteUri(remoteServerFqdn), text, CredentialCache.DefaultNetworkCredentials, ProxyHelper.GetPSWSProxyRequestHeaders(this.context.ExchangeRunspaceConfig), this.context.ExchangeRunspaceConfig.TypeTable); } foreach (PSObject psobject in enumerable) { object sendToPipeline = psobject; if (psobject.BaseObject != null && !(psobject.BaseObject is PSCustomObject)) { sendToPipeline = psobject.BaseObject; } else if (this.context.ExchangeRunspaceConfig != null) { if (this.context.ExchangeRunspaceConfig.ConfigurationSettings.ClientApplication != ExchangeRunspaceConfigurationSettings.ExchangeApplication.ECP) { if (this.context.ExchangeRunspaceConfig.ConfigurationSettings.ClientApplication != ExchangeRunspaceConfigurationSettings.ExchangeApplication.OSP) { goto IL_2CB; } } try { Task.TaskVerboseLoggingDelegate writeVerbose = null; if (this.context.CommandShell != null) { writeVerbose = new Task.TaskVerboseLoggingDelegate(this.context.CommandShell.WriteWarning); } sendToPipeline = ProxyHelper.ConvertPSObjectToOriginalType(psobject, remoteServerVersion, writeVerbose); } catch (Exception ex) { CmdletLogger.SafeAppendGenericError(uniqueId, "ConvertPSObjectToOriginalTyp", ex, new Func <Exception, bool>(TaskHelper.IsTaskUnhandledException)); Diagnostics.ReportException(ex, Constants.CoreEventLogger, TaskEventLogConstants.Tuple_UnhandledException, null, null, Microsoft.Exchange.Diagnostics.Components.Configuration.Core.ExTraceGlobals.InstrumentationTracer, "Exception from ProxyHelper.ConvertPSObjectToOriginalType : {0}"); } } IL_2CB: if (this.context.CommandShell != null) { this.context.CommandShell.WriteObject(sendToPipeline); } } } catch (Exception ex2) { CmdletLogger.SafeAppendGenericError(this.context.UniqueId, "ProxyCmdletExecution", ex2, new Func <Exception, bool>(TaskHelper.IsTaskUnhandledException)); if (this.context.CommandShell != null) { this.context.CommandShell.WriteError(new CmdletProxyException(text, remoteServerFqdn, friendlyVersionInformation, proxyMethod.ToString(), ex2.Message), ExchangeErrorCategory.ServerOperation, null); } } }
public void close(UserToken token) { }
public int get(UserToken token) { return(accountCache.getId(token)); }
/// <summary> /// 下线 /// </summary> /// <param name="token"></param> public void OffLine(UserToken token) { cacheFight.OffLine(token); }
/// <exclude /> public SecurityToken(EntityToken entityToken, ActionToken actionToken, UserToken userToken) { _entityToken = entityToken; _actionToken = actionToken; _userToken = userToken; }
private void Enter(UserToken token) { int userId = GetUserId(token); //判断是否正在匹配的房间中 if (!userRoom.ContainsKey(userId)) { MatchRoom room = null; bool isEnter = false; //当前是否有在等待中的房间 if (roomMap.Count > 0) { //遍历所有等待中的房间 foreach (MatchRoom item in roomMap.Values) { //如果没满员 if (item.TeamMax * 2 > item.TeamOne.Count + item.TeamTwo.Count) { room = item; //如果队伍一没满员则进入队伍1 if (room.TeamOne.Count < room.TeamMax) { room.TeamOne.Add(userId); } else { room.TeamTwo.Add(userId); } //添加玩家与房间的映射关系 isEnter = true; userRoom.TryAdd(userId, room.Id); break; } } //当所有房间全部满员 判断缓存中是否有房间 if (!isEnter) { CreateRoomFromCache(userId, out room); } } else { //没有等待中的房间 CreateRoomFromCache(userId, out room); } //不管什么方式进入房间,判断房间是否满员,满了就开始选人,将房间丢进缓存队列 if (room.TeamOne.Count == room.TeamTwo.Count && room.TeamOne.Count == room.TeamMax) { //通知选人模块开始选人 EventUtil.createSelect(room.TeamOne, room.TeamTwo); WriteToUsers(room.TeamOne.ToArray(), GetType(), 0, MatchProtocol.ENTER_DELECT_BRO, null); WriteToUsers(room.TeamTwo.ToArray(), GetType(), 0, MatchProtocol.ENTER_DELECT_BRO, null); //移除玩家映射 foreach (int item in room.TeamOne) { int i; userRoom.TryRemove(item, out i); } foreach (int item in room.TeamTwo) { int i; userRoom.TryRemove(item, out i); } //重置房间数据 room.TeamOne.Clear(); room.TeamTwo.Clear(); //将房间从等待房间中移除 roomMap.TryRemove(room.Id, out room); //加入缓存 cacheRooms.Push(room); } } }
public void ClientClose(UserToken token, string error) { Leave(token); }
public abstract BusinessLayerResult <UserToken> RemoveToken(UserToken token);
private bool IsAuthenticationTokenValid(UserToken userToken) { return(!(userToken.RefreshTokenExpiration <= DateTime.Now)); }
public void brocast(int area, int command, object message, UserToken exToken = null) { brocast(GetType(), area, command, message, exToken); }
public void brocast(int command, object message, UserToken exToken = null) { brocast(GetArea(), command, message, exToken); }
public GameService(UserToken userToken) : base(userToken) { }
/// <summary> /// 获取对应的ID /// </summary> /// <param name="token"></param> /// <returns></returns> public int GetID(UserToken token) { return(cacheFight.GetID(token)); }
public void write(UserToken token, int area, int command, object message) { write(token, GetType(), GetArea(), command, message); }
public BusinessLayerResult <UserToken> UserTokenUpdate(UserToken token) { return(_userTokenManager.UpdateToken(token)); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl = null) { List <MessageClassUtil> _message = new List <MessageClassUtil>(); try { string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); var resultLogin = await _client.PostAsJsonAsync(baseadress + "api/cuenta/login", new UserInfo { Email = model.Email, Password = model.Password }); if (resultLogin.IsSuccessStatusCode) { string webtoken = await(resultLogin.Content.ReadAsStringAsync()); UserToken _userToken = JsonConvert.DeserializeObject <UserToken>(webtoken); //Validacion para el vencimiento de la contraseña //if (_userToken.LastPasswordChangedDate != null) //{ // if (_userToken != null // && _userToken.LastPasswordChangedDate.Date.AddDays(_userToken.Passworddias) < DateTime.Now.Date // && !Request.Path.ToString().EndsWith("/Account/ChangePassword.aspx")) // { // HttpContext.Session.SetString("token", _userToken.Token); // HttpContext.Session.SetString("user", model.Email); // HttpContext.Session.SetString("Expiration", _userToken.Expiration.ToString()); // return RedirectToAction("ChangePassword", "Account"); // } //} if (_userToken.IsEnabled.Value) { HttpContext.Session.SetString("token", _userToken.Token); HttpContext.Session.SetString("Expiration", _userToken.Expiration.ToString()); HttpContext.Session.SetString("user", model.Email); HttpContext.Session.SetString("BranchId", _userToken.BranchId.ToString()); HttpContext.Session.SetString("BranchName", _userToken.BranchName); //HttpContext.Session.SetString("BranchId", "1"); // se coloco la sucursal en duro hasta que se defina como se va utilizar las sucursale de los usuarios var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken secToken = handler.ReadJwtToken(_userToken.Token); var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaims(secToken.Claims); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); HttpClient cliente = new HttpClient(); cliente.DefaultRequestHeaders.Add("Authorization", "Bearer " + _userToken.Token); var resultado = await cliente.GetAsync(baseadress + "api/Reportes/CadenaConexionBD"); if (resultado.IsSuccessStatusCode) { var cadena = await resultado.Content.ReadAsStringAsync(); Utils.ConexionReportes = cadena; } var resultadoCierre = await cliente.GetAsync(baseadress + "api/CierreContable/UltimoCierre"); string ultimoCierre = await resultadoCierre.Content.ReadAsStringAsync(); return(RedirectToAction("Index", "Home")); } else { _message.Add(new MessageClassUtil { key = "Login", name = "error", mensaje = "Error en login" }); model.Failed = true; model.LoginError = "Error en login: "******"Login", name = "error", mensaje = "Error en login" }); model.Failed = true; model.LoginError = "Error en login: "******"Ocurrio un error: { ex.ToString() }"); model.LoginError = "Ocurrio un error: " + ex.Message.ToString(); model.Failed = true; return(View(model)); // throw ex; } }
/// <summary> /// 用户是否在此子模块 /// </summary> /// <param name="token"></param> /// <returns></returns> public bool isEntered(UserToken token) { return(list.Contains(token)); }
public BusinessLayerResult <UserToken> UserTokenAdd(UserToken token) { return(_userTokenManager.AddToken(token)); }
public BusinessLayerResult <UserToken> UserTokenDelete(UserToken model) { return(_userTokenManager.RemoveToken(model)); }
/// <summary> /// Create a new UserToken object. /// </summary> /// <param name="userId">Initial value of UserId.</param> public static UserToken CreateUserToken(int userId) { UserToken userToken = new UserToken(); userToken.UserId = userId; return userToken; }
public abstract BusinessLayerResult <UserToken> AddToken(UserToken token);
public void write(UserToken token, int command) { write(token, command, null); }
public static void SetUserGroupPermissionTypes(UserToken userToken, EntityToken entityToken, IReadOnlyCollection<PermissionType> permissionTypes) { SetToCache(userToken, entityToken, permissionTypes, UserGroupPermissionTypeCachingKey); }
public abstract BusinessLayerResult <UserToken> UpdateToken(UserToken token);
protected void Page_Load(object sender, EventArgs e) { string SPID = "35000000"; string AuthenType = ""; string AuthenName = ""; string Password = ""; string CustID = ""; string RealName = ""; string NickName = ""; string UserName = ""; string OutID = ""; string UserAccount = ""; string CustType = ""; string ProvinceID = ""; string Ticket = ""; string ReturnUrl = ""; int Result = ErrorDefinition.BT_IError_Result_UnknowError_Code; string ErrMsg = ErrorDefinition.BT_IError_Result_UnknowError_Msg; try { if (CommonUtility.IsParameterExist("LoginTicket", this.Page)) { Ticket = Request["LoginTicket"]; Result = CIPTicketManager.checkCIPTicket(SPID, Ticket, "", out CustID, out RealName, out UserName, out NickName, out OutID, "", out AuthenName, out AuthenType, out ErrMsg); Log(String.Format("SPID:{0},Ticket:{1},CustID:{2},RealName:{3},UserName:{4},NickName:{5},OutID:{6},AuthenName:{7},AuthenType:{8},Result:{9},ErrMsg:{10}——【DateTime:{11}】", SPID, Ticket, CustID, RealName, UserName, NickName, OutID, AuthenName, AuthenType, Result, ErrMsg, DateTime.Now.ToString("yyyy-MM-dd HH:mm"))); if (Result == 0) { SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); UserToken UT = new UserToken(); string UserTokenValue = UT.GenerateUserToken(CustID, RealName, UserName, NickName, OutID, CustType, AuthenName, AuthenType, key, out ErrMsg); string CookieName = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; PageUtility.SetCookie(UserTokenValue, CookieName, this.Page); if (CommonUtility.IsParameterExist("ReturnUrl", this.Page)) { ReturnUrl = Request["ReturnUrl"]; Response.Redirect(ReturnUrl); } Response.Redirect("http://www.118114.cn"); } else { Response.Redirect("../ErrorInfo.aspx?ErrorInfo=" + ErrMsg); } } else { Response.Redirect("http://www.118114.cn"); } } catch (Exception ex) { ErrMsg += ex.Message; } finally { Log(String.Format("LoginTicket:{0},ErrMsg:{1}——【DateTime:{2}】", Ticket, ErrMsg, DateTime.Now.ToString("yyyy-MM-dd HH:mm"))); } }
protected void Button1_Click(object sender, EventArgs e) { Response.AddHeader("P3P", "CP=CAO PSA OUR"); StringBuilder strLog = new StringBuilder(); string AuthenType = HttpUtility.HtmlDecode(Request.Form["AuthenType"].ToString().Trim().ToUpper()); //获取认证类型 PageUtility.SetCookie("AuthenType", AuthenType, 168); //168个小时,即一个礼拜 string AuthenName = username.Text; string Password = password.Text; string CustID = ""; string RealName = ""; string NickName = ""; string UserName = ""; string OutID = ""; string UserAccount = ""; string ErrMsg = ""; string CustType = ""; string ProvinceID = ""; int Result = 1; try { strLog.AppendFormat("checkCode={0}", Request.Form["checkCode"]); if (!CommonUtility.ValidateValidateCode(HttpUtility.HtmlDecode(Request.Form["checkCode"].ToString().Trim()), this.Context)) { errorHint.InnerHtml = "验证码错误,请重新输入"; return; } //日志 strLog.AppendFormat("【开始验证】:SPID:{0},ProvinceID:{1},AuthenName:{2},AuthenType:{3}", SPID, ProvinceID, AuthenName, AuthenType); Result = BTForBusinessSystemInterfaceRules.UserAuthV2(SPID, AuthenName, AuthenType, Password, Context, ProvinceID, "", "", out ErrMsg, out CustID, out UserAccount, out CustType, out OutID, out ProvinceID, out RealName, out UserName, out NickName); //验证结果日志 strLog.AppendFormat("【验证结果】:CustID:{0},UserAcount:{1},CustType:{2},OutID:{3},ProvinceID:{4},RealName:{5},UserName:{6},NickName:{7}", CustID, UserAccount, CustType, OutID, ProvinceID, RealName, UserName, NickName); CommonBizRules.WriteDataCustAuthenLog(SPID, CustID, ProvinceID, AuthenType, AuthenName, "2", Result, ErrMsg); if (Result != 0) { if (Result == 1001 || Result == -20504 || Result == -21553) { errorHint.InnerHtml = ErrMsg; //hint_Username.InnerHtml = ""; return; } if (Result == -21501) { errorHint.InnerHtml = ErrMsg; return; } Response.Write(ErrMsg); return; } SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); //生成token并保存 UserToken UT = new UserToken(); string UserTokenValue = UT.GenerateUserToken(CustID, RealName, UserName, NickName, OutID, CustType, AuthenName, AuthenType, key, out ErrMsg); string CookieName = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; //PageUtility.SetCookie(UserTokenValue, CookieName, this.Page); PageUtility.SetCookie(CookieName, UserTokenValue); TokenValidate.IsRedircet = false; TokenValidate.Validate(); this.ssoFunc(); } catch (System.Exception ex) { log(ex.ToString()); } finally { log(strLog.ToString()); } }
protected void Page_Load(object sender, EventArgs e) { StringBuilder strLog = new StringBuilder(); string CookieName = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; string isLogin = "******"; string welcomeName = "0"; string encryptCustIDValue = "0"; if (PageUtility.IsCookieExist(CookieName, this.Context)) { SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); UserToken UT = new UserToken(); string strCIPToken = Request.Cookies.Get(CookieName).Value; string custID; string realName; string userName; string nickName; string outerID; string custType; string loginAuthenName; string loginAuthenType; string TimeStamp = ""; string SPID = ""; string errMsg = ""; int result = UT.ParseUserToken(strCIPToken, key, out custID, out realName, out userName, out nickName, out outerID, out custType, out loginAuthenName, out loginAuthenType, out errMsg); log("result="+result+";custID="+custID+";outerID="+outerID+"\r\n"); string json_custinfo = ""; json_custinfo = json_custinfo + "{"; if (result == 0) { isLogin = "******"; if (realName != null && !"".Equals(realName)) { welcomeName = realName; } else if (nickName != null && !"".Equals(nickName)) { welcomeName = nickName; } else if (userName != null && !"".Equals(userName)) { welcomeName = userName; } json_custinfo = json_custinfo + "isLogin" + ":" + "'" + isLogin + "',"; json_custinfo = json_custinfo + "welcomeName" + ":" + "'" + realName + "',"; json_custinfo = json_custinfo + "outerID" + ":" + "'" + outerID + "',"; //json_custinfo = json_custinfo + "encryptCustIDValue"+":"+"'"+ } if (CommonUtility.IsParameterExist("SPID", this.Page)) { TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); SPID = Request["SPID"]; spInfo = new SPInfoManager(); SPData = spInfo.GetSPData(this.Context, "SPData"); key = spInfo.GetPropertyBySPID(SPID, "SecretKey", SPData); string Digest = CryptographyUtil.GenerateAuthenticator(TimeStamp + "$" + custID + "$" + result + "$" + errMsg, key); encryptCustIDValue = SPID + "$" + CryptographyUtil.Encrypt(TimeStamp + "$" + custID + "$" + result + "$" + errMsg + "$" + Digest, key); //string RegistryResponseValue = HttpUtility.UrlEncode(temp); json_custinfo = json_custinfo + "encryptCustIDValue" + ":" + "'" + encryptCustIDValue + "'"; } json_custinfo = json_custinfo + "}"; Response.Write("var o ="+json_custinfo); } else { //综合平台渠道udb渠道控制 String UDBorUnifyPlatform = String.Empty; try { SqlConnection conn = new SqlConnection(DBUtility.BestToneCenterConStr); StringBuilder sql = new StringBuilder(); sql.Append("select platform_name from udb_authen_platform where flag=1 "); // 1生效 0 失效 SqlCommand cmd = new SqlCommand(sql.ToString(), conn); using (conn) { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { UDBorUnifyPlatform = (String)reader["platform_name"]; } } } catch (Exception ex) { UDBorUnifyPlatform = System.Configuration.ConfigurationManager.AppSettings["UDBorUnifyPlatform"]; strLog.AppendFormat("UDBorUnifyPlatform异常:{0}\r\n", ex.ToString()); } strLog.AppendFormat("UDBorUnifyPlatform:{0}\r\n", UDBorUnifyPlatform); //单双向sso控制 String ssoway = String.Empty; try { SqlConnection conn = new SqlConnection(DBUtility.BestToneCenterConStr); StringBuilder sql = new StringBuilder(); sql.Append("select ssoway from unifyAuthen "); // 1生效 0 失效 SqlCommand cmd = new SqlCommand(sql.ToString(), conn); using (conn) { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { ssoway = (String)reader["ssoway"]; } } } catch (Exception ex) { strLog.AppendFormat("ssoway异常:{0}\r\n", ex.ToString()); ssoway = "1"; } strLog.AppendFormat("ssoway:{0}\r\n", ssoway); log(strLog.ToString()); if (!String.IsNullOrEmpty(UDBorUnifyPlatform)) { if (UDBorUnifyPlatform.ToLower().Equals("unifyplatform") && ssoway.Equals("2")) //双向sso { //String UnifyAccountCheckResult = String.Empty; //if (CommonUtility.IsParameterExist("UnifyAccountCheckResult", this.Page)) //{ // UnifyAccountCheckResult = Request["UnifyAccountCheckResult"]; //} //strLog.AppendFormat("UnifyAccountCheckResult:{0}\r\n", UnifyAccountCheckResult); //if ("1".Equals(UnifyAccountCheckResult) || String.IsNullOrEmpty(UnifyAccountCheckResult)) //{ //检查登录状态 if (!CommonUtility.IsParameterExist("UnifyAccountCheckResult", this.Page)) { string TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string appId = UDBConstDefinition.DefaultInstance.UnifyPlatformAppId; //System.Configuration.ConfigurationManager.AppSettings["unifyPlatform_appId"]; string appSecret = UDBConstDefinition.DefaultInstance.UnifyPlatformAppSecret; //System.Configuration.ConfigurationManager.AppSettings["unifyPlatform_appSecretKey"]; string version = UDBConstDefinition.DefaultInstance.UnifyPlatformVersion; //System.Configuration.ConfigurationManager.AppSettings["unifyPlatform_version"]; string clientType = UDBConstDefinition.DefaultInstance.UnifyPlatformClientType; //System.Configuration.ConfigurationManager.AppSettings["unifyPlatform_clientType"]; string accountType = UDBConstDefinition.DefaultInstance.UnifyPlatformAccountType; string format = "redirect"; String returnURL = HttpUtility.UrlEncode(UDBConstDefinition.DefaultInstance.UnifyAccountCheckCallBackUrlYY + "?SPID=35000000"); string parameters = "&timeStamp=" + TimeStamp + "&accoutType=" + accountType + "&returnURL=" + returnURL; strLog.AppendFormat("参数:{0}\r\n", parameters); string paras = CryptographyUtil.XXTeaEncrypt(parameters, appSecret); strLog.AppendFormat("参数:{0},paras:{1}\r\n", parameters, paras); string sign = CryptographyUtil.HMAC_SHA1(appId + clientType + format + version + paras, appSecret); strLog.AppendFormat("sign:{0}\r\n", sign); String UnifyAccountCheckUrl = UDBConstDefinition.DefaultInstance.UnifyAccountCheckUrl; UnifyAccountCheckUrl = UnifyAccountCheckUrl + "?appId=" + appId + "&version=" + version + "&clientType=" + clientType + "¶s=" + paras + "&sign=" + sign + "&format=redirect"; strLog.AppendFormat(" Redirect to UnifyAccountCheckUrl:{0}\r\n", UnifyAccountCheckUrl); log(strLog.ToString()); Response.Redirect(UnifyAccountCheckUrl, false); } //} } } else { } } }
/// <summary> /// 用户断开连接 /// </summary> /// <param name="token"></param> /// <param name="error"></param> public void ClientClose(UserToken token, string error) { BizFactory.login.offLine(token); }
private UserToken CreateUserToken() { SocketAsyncEventArgs sendEventArg; sendEventArg = new SocketAsyncEventArgs(); sendEventArg.Completed += OnComplete; SocketAsyncEventArgs recvEventArg; recvEventArg = new SocketAsyncEventArgs(); recvEventArg.Completed += OnComplete; // 처음 생성할 때 버퍼를 할당해 놓는다. 풀에 반납하더라도 버퍼는 유지된다. mSendBufferManager.SetBuffer(sendEventArg); mRecvBufferManager.SetBuffer(recvEventArg); UserToken userToken = new UserToken(mServer, sendEventArg, recvEventArg); sendEventArg.UserToken = userToken; recvEventArg.UserToken = userToken; return userToken; }
public int create(UserToken token, string account, string password) { return(0); }
void DoCallback() { StringBuilder strLog = new StringBuilder(); if (CommonUtility.IsParameterExist("ReturnUrl", this.Page)) { ReturnUrl = Request["ReturnUrl"]; } else { //Logs.logSave("没有ReturnUrl返回"); strLog.AppendFormat("没有ReturnUrl返回\r\n"); } if(CommonUtility.IsParameterExist("code", this.Page)) { code = Request["code"]; }else { //Logs.logSave("没有code返回"); strLog.AppendFormat("没有code返回\r\n"); } if (CommonUtility.IsParameterExist("openid", this.Page)) { openid = Request["openid"]; }else { //Logs.logSave("没有openid返回"); strLog.AppendFormat("没有openid返回\r\n"); } if (CommonUtility.IsParameterExist("openkey", this.Page)) { openkey = Request["openkey"]; }else { //Logs.logSave("没有openkey返回"); strLog.AppendFormat("没有openkey返回\r\n"); } //写日志 //Logs.logSave("返回CODE结果:" + code+",返回的openid:"+openid+",返回的openkey:"+openkey); strLog.AppendFormat("返回CODE结果:" + code + ",返回的openid:" + openid + ",返回的openkey:" + openkey+"\r\n"); //==============通过Authorization Code和基本资料获取Access Token================= send_url = "https://open.t.qq.com/cgi-bin/oauth2/access_token?grant_type=authorization_code&client_id=" + client_id + "&client_secret=" + client_secret + "&code=" + code + "&state=" + state + "&redirect_uri=" + Utils.UrlEncode(redirect_uri); //https://open.t.qq.com/cgi-bin/oauth2/access_token?client_id=APP_KEY&client_secret=APP_SECRET&redirect_uri=http://www.myurl.com/example&grant_type=authorization_code&code=CODE send_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + client_id + "&client_secret=" + client_secret + "&code=" + code + "&state=" + state + "&redirect_uri=" + Utils.UrlEncode(redirect_uri); //写日志 //Logs.logSave("第二步,通过Authorization Code获取Access Token,发送URL:" + send_url); strLog.AppendFormat("第二步,通过Authorization Code获取Access Token,发送URL:" + send_url+"\r\n"); //发送并接受返回值 rezult = HttpMethods.HttpGet(send_url); // 返回内容:access_token=7a0fae7d2183c0c54ef18589fffe6475&expires_in=604800&refresh_token=15a0d166120bda818cd0782c0b7a8c1a&name=huoxintang //写日志 //Logs.logSave("取得返回结果:" + rezult); strLog.AppendFormat("取得返回结果:" + rezult+"\r\n"); //如果失败 if (rezult.Contains("error")) { //出错了 //写日志 //Logs.logSave("出错了:" + rezult); strLog.AppendFormat("出错了:" + rezult+"\r\n"); HttpContext.Current.Response.End(); } else { //======================通过Access Token来获取用户的OpenID 这一步不需要 =======graph需要======= string[] parm = rezult.Split('&'); //取得 access_token access_token = parm[0].Split('=')[1]; //取得 过期时间 expires_in = parm[1].Split('=')[1]; //refresh_token = parm[2].Split('=')[1]; 用graph 可能没有refresh_token //拼接url send_url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token; //发送并接受返回值 rezult = HttpMethods.HttpGet(send_url); //写日志 //Logs.logSave("第三步,发送 access_token:" + send_url); strLog.AppendFormat("第三步,发送 access_token:" + send_url+"\r\n"); //如果失败 if (rezult.Contains("error")) { //出错了 //写日志 //Logs.logSave("出错了:" + rezult); strLog.AppendFormat("出错了:" + rezult+"\r\n"); HttpContext.Current.Response.End(); } //写日志 //Logs.logSave("得到返回结果:" + rezult); strLog.AppendFormat("得到返回结果:" + rezult+"\r\n"); //取得文字出现 int str_start = rezult.IndexOf('(') + 1; int str_last = rezult.LastIndexOf(')') - 1; //取得JSON字符串 rezult = rezult.Substring(str_start, (str_last - str_start)); //反序列化JSON Dictionary<string, string> _dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(rezult); //取值 _dic.TryGetValue("client_id", out new_client_id); _dic.TryGetValue("openid", out openid); //储存获取数据用到的信息 HttpContext.Current.Session["access_token"] = access_token; HttpContext.Current.Session["client_id"] = client_id; HttpContext.Current.Session["openid"] = openid; HttpContext.Current.Session["openkey"] = openkey; // 这里张剑锋还拿到了 Level,NickName,Gender //========继续您的业务逻辑编程========================================== //取到 openId //openId与您系统的user数据进行关联 //一个openid对应一个QQ,一个openid也要对应到您系统的一个账号:QQ--OpenId--User; //这个时候有两种情况: //【1】您让用户绑定系统已有的用户,那么让用户输入用户名密码,找到该用户,然后绑定OpenId //【2】为用户生成一个系统用户,直接绑定OpenId //上面完成之后,设置用户的登录状态,完整绑定和登录 //=============通过Access Token和OpenID来获取用户资料 ==== send_url = "https://open.t.qq.com/api/user/info?access_token=" + access_token + "&oauth_consumer_key=" + client_id + "&openid=" + openid + "&openkey=" + openkey + "&oauth_version=2.a"; //https://open.t.qq.com/api/user/info?access_token=7a0fae7d2183c0c54ef18589fffe6475&oauth_consumer_key=801210600&openid=65FCC7BC2B69619BC13BCF6C16FB06C3&oauth_version=2.a&openkey=05FB5E1C75119B141BAD0444C6EA41CE send_url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token + "&oauth_consumer_key=" + client_id + "&openid=" + openid + "&openkey=" + openkey + "&oauth_version=2.a"; //发送并接受返回值 //Logs.logSave("发送send_url:" + send_url); strLog.AppendFormat("发送send_url:" + send_url+"\r\n"); rezult = HttpMethods.HttpGet(send_url); //写日志 //Logs.logSave("第四步,通过get_user_info方法获取数据:" + send_url); //Logs.logSave("rezult:" + rezult); strLog.AppendFormat("第四步,通过get_user_info方法获取数据:" + send_url+"\r\n"); strLog.AppendFormat("rezult:" + rezult+"\r\n"); //反序列化JSON /** Dictionary<string, object> _data = JsonConvert.DeserializeObject<Dictionary<string, object>>(rezult); object jsondata = null; _data.TryGetValue("data", out jsondata); string js_data = jsondata.ToString(); Dictionary<string, object> useinfo_data = JsonConvert.DeserializeObject<Dictionary<string, object>>(js_data); object nick = null; object j_openid = null; object sex = null; object province_code = null; object head = null; object j_name = null; useinfo_data.TryGetValue("nick", out nick); useinfo_data.TryGetValue("openid", out j_openid); useinfo_data.TryGetValue("sex", out sex); useinfo_data.TryGetValue("province_code", out province_code); useinfo_data.TryGetValue("head", out head); useinfo_data.TryGetValue("name", out j_name); Logs.logSave("====================="); Logs.logSave("nickname:" + nick.ToString()); Logs.logSave("openid:"+j_openid.ToString()); Logs.logSave("sex:"+sex.ToString()); Logs.logSave("Province_code:" + province_code.ToString()); Logs.logSave("head:" + head.ToString()); Logs.logSave("name:" + j_name.ToString()); //Logs.logSave("jsondata:" + jsondata); **/ Dictionary<string, string> _dic2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(rezult); string ret = "", msg = "", nickname = "", face = "", sex = "",ret_openid="",ret_name=""; //取值 _dic2.TryGetValue("ret", out ret); _dic2.TryGetValue("msg", out msg); //如果失败 if (ret != "0") { //出错了 //写日志 //Logs.logSave("出错了:" + rezult); strLog.AppendFormat("出错了:" + rezult+"\r\n"); //HttpContext.Current.Response.Write(rezult); HttpContext.Current.Response.End(); } _dic2.TryGetValue("nickname", out nickname); _dic2.TryGetValue("head", out face); _dic2.TryGetValue("gender", out sex); _dic2.TryGetValue("openid", out ret_openid); _dic2.TryGetValue("name", out ret_name); //写日志 ///Logs.logSave("得到返回结果:" + rezult); strLog.AppendFormat("得到返回结果:" + rezult+"\r\n"); //string newline = "<br>"; //string str = ""; //str += "openid:" + openid + newline; //str += "昵称:" + nickname + newline; //str += "名称:" + ret_name + newline; //str += "性别:" + sex + newline; //str += "默认头像:" + face + newline; //页面输出结果: //HttpContext.Current.Response.Write("返回结果如下:" + rezult + newline + newline); //HttpContext.Current.Response.Write("经过处理后:" + newline + str); /** string newline = "<br>"; string str = ""; str += "openid:" + j_openid.ToString() + newline; str += "昵称:" + nick.ToString() + newline; str += "名称:" + j_name.ToString() + newline; str += "性别:" + sex.ToString() + newline; str += "默认头像:" + head.ToString() + newline; str += "省份:" + province_code.ToString() + newline; **/ //页面输出结果: //HttpContext.Current.Response.Write("返回结果如下:" + rezult + newline + newline); //HttpContext.Current.Response.Write("经过处理后:" + newline + str); string CustID = QueryByOpenID(openid); if (String.IsNullOrEmpty(CustID)) // 已有绑定关系 { //直接单点登录 string AuthenName = ""; string AuthenType = ""; string RealName = ""; string NickName = ""; string UserName = ""; string OutID = ""; string UserAccount = ""; string CustType = ""; string ProvinceID = ""; string _connectionString = WebConfigurationManager.ConnectionStrings["BestToneCenterConStr"].ConnectionString; SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("select RealName,UserName,NickName,OuterID,CustType,SourceSPID from custinfo where custid=@CustID", con); cmd.Parameters.Add("@CustID", SqlDbType.NVarChar, 16).Value = CustID; using (con) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { RealName = (string)reader["RealName"]; UserName = (string)reader["UserName"]; NickName = (string)reader["NickName"]; OutID = (string)reader["OuterID"]; CustType = (string)reader["CustType"]; SPID = (string)reader["SourceSPID"]; } } SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); string key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); string ErrMsg = ""; //生成token并保存 UserToken UT = new UserToken(); string UserTokenValue = UT.GenerateUserToken(CustID, RealName, UserName, NickName, OutID, CustType, AuthenName, AuthenType, key, out ErrMsg); string CookieName = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; PageUtility.SetCookie(CookieName, UserTokenValue); TokenValidate.IsRedircet = false; TokenValidate.Validate(); //begin this.ssoFunc(); //Response.Redirect(ReturnUrl, true); //end } else { // 未有绑定关系 (可能有号百账号-则去绑定,可能没有号百账号,则注册) string SelectOauthAssertion = System.Configuration.ConfigurationManager.AppSettings["SelectOauthAssertion"]; SelectOauthAssertion = SelectOauthAssertion + "?code=" + openid + "&returnUrl=" + ReturnUrl+"&oauthtype=0"; // 0 代表qq 1代表sina Response.Redirect(SelectOauthAssertion, true); //SelectOauthAssertion 指向地址: http://sso.besttone.cn/SSO/boundingV2.action?code=***&returnUrl=*** //boundingV2.action 会forward到 他自己的一个auth.jsp ,这个jsp会嵌入两个iframe,其中一个iframe的src,指向客户信息平台的AuthBindLogin.aspx,另个iframe指向 客户信息平台的AuthRegister.aspx //同时分别带上SPTokenRequest和code参数,这个SPTokenRequest参数中的ReturnUrl } } log(strLog.ToString()); }
public int login(UserToken token, string account, string password) { return(0); }
protected void BtnSubmit_Click(object sender, EventArgs e) { UserName = Request.Form["UserName"].ToString().Trim(); Password = Request.Form["Password"].ToString().Trim(); Password2 = Request.Form["Password2"].ToString().Trim(); try { Result = CustBasicInfo.IsExistUser(UserName); if (Result != 0) { errorHint.InnerHtml = "<script type='text/javascript'>showError('用户名已存在!')</script>"; return; } Result = UserRegistry.UserRegisterWebLowStint(SPID, UserName, Password, out CustID, out ErrMsg); if (Result == 0) { // 重定向到欢迎页面 String IPAddress = Request.UserHostAddress.ToString(); CommonBizRules.WriteTraceIpLog(CustID, UserName, SPID, IPAddress, "client_wap"); String youhuiquan_url = "http://www.114yg.cn/facadeHome.do?actions=facadeHome&method=sendCouponToRegist&wt=json&from=" + Device + "&custId=" + CustID; String jsonmsg = HttpMethods.HttpGet(youhuiquan_url); System.Collections.Generic.Dictionary<string, string> resuzt = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string, string>>(jsonmsg); //{"returnCode":"00000"} string youhuiquan = ""; resuzt.TryGetValue("returnCode", out youhuiquan); String TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); SPInfoManager spInfo = new SPInfoManager(); Object SPData = spInfo.GetSPData(this.Context, "SPData"); String key = spInfo.GetPropertyBySPID("35000000", "SecretKey", SPData); String Digest = CryptographyUtil.GenerateAuthenticator(TimeStamp + "$" + CustID + "$" + Result + "$" + ErrMsg, key); String temp = SPID + "$" + CryptographyUtil.Encrypt(TimeStamp + "$" + CustID + "$" + Result + "$" + ErrMsg + "$" + Digest, key); String RegistryResponseValue = HttpUtility.UrlEncode(temp); //给用户写cookie UserToken UT = new UserToken(); String RealName = UserName; String NickName = UserName; string UserTokenValue = UT.GenerateUserToken(CustID, RealName, UserName, NickName, "", "42", UserName, "1", key, out ErrMsg); string CookieName = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; PageUtility.SetCookie(UserTokenValue, CookieName, this.Page); CreateSPTokenRequest(); StringBuilder URL = new StringBuilder(); URL.Append("LowSintRegisterMSuccess.aspx?SPID="); Response.Redirect(URL.ToString() + SPID + "&SPTokenRequest=" + newSPTokenRequest, true); } else { errorHint.InnerHtml = "<script type='text/javascript'>showError('注册失败:"+ErrMsg+"')</script>"; return; } } catch (Exception exp) { errorHint.InnerHtml = "<script type='text/javascript'>showError('"+exp.ToString()+"!')</script>"; return; } }
public int get(UserToken token) { return(0); }
/// <summary> /// There are no comments for UserToken in the schema. /// </summary> public void AddToUserToken(UserToken userToken) { base.AddObject("UserToken", userToken); }
public bool create(UserToken token, string name) { throw new NotImplementedException(); }