public string SetSession(string userName, Session session) { session.UserName = userName; var sessions = _cacheManager.Get<List<Session>>(userName) ?? new List<Session>(); sessions.Add(session); var sessionId = Guid.NewGuid().ToString(); session.SessionId = sessionId; _cacheManager.Set(userName, sessions, _expiredTime); SessionToken sid = new SessionToken { SessionId = sessionId, UserName = userName, }; var cookie = FormsAuthentication.GetAuthCookie(userName, false); cookie.Value = FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddHours(1000), false, sid.ToString())); HttpContext.Current.Response.Cookies.Add(cookie); return sessionId; }
static void AuthorizeRequest(object sender, EventArgs e) { SessionInfo session=null; try { if (HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity) { // Note: If user signed out in another window, the ticket would have been // removed from the browser and this code shoudn't be executed. // resemble the SessionInfo from the ticket. FormsIdentity loginId = (FormsIdentity) HttpContext.Current.User.Identity ; FormsAuthenticationTicket ticket = loginId.Ticket; String[] fields = ticket.UserData.Split('|'); String tokenId = fields[0]; String userDisplayName = fields[1]; SessionToken token = new SessionToken(tokenId, ticket.Expiration); session = new SessionInfo(loginId.Name, userDisplayName, token); // Initialize the session. This will throw exception if the session is no longer // valid. For eg, time-out. SessionManager.InitializeSession(session); } if (String.IsNullOrEmpty(Thread.CurrentThread.Name)) { String user = SessionManager.Current != null ? SessionManager.Current.User.Identity.Name : "Unknown"; Thread.CurrentThread.Name = String.Format(SR.WebGUILogHeader, HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.Browser.Browser, HttpContext.Current.Request.Browser.Version, user); } } catch (SessionValidationException) { // SessionValidationException is thrown when the session id is invalid or the session already expired. // If session already expired, if (session != null && session.Credentials.SessionToken.ExpiryTime < Platform.Time) { SessionManager.SignOut(session); } else { // redirect to login screen SessionManager.TerminateSession("The current session is no longer valid.", SR.MessageCurrentSessionNoLongerValid); } } catch(Exception ex) { // log the exception ExceptionHandler.ThrowException(ex); } }
public InitiateSessionResponse InitiateSession(InitiateSessionRequest request) { bool ok = Membership.ValidateUser(request.UserName, request.Password); if (ok) { Guid tokenId = Guid.NewGuid(); var token = new SessionToken(tokenId.ToString(), Platform.Time + ServerPlatform.WebSessionTimeout); string[] authority = Roles.GetRolesForUser(request.UserName); string displayName = request.UserName; #if STANDALONE var list = new List<string>(); list.AddRange(authority); list.Add(Enterprise.Authentication.AuthorityTokens.Study.ViewImages); list.Add("Viewer/Visible"); list.Add("Viewer/Clinical"); authority = list.ToArray(); #endif var rsp = new InitiateSessionResponse(token, authority, new Guid[0], displayName,string.Empty); SessionTokenManager.Instance.AddSession(token); return rsp; } throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException()); }
public InitiateSessionResponse(SessionToken sessionToken, string[] authorityTokens, Guid[] authorityGroups, string displayName, string emailAddress) { this.SessionToken = sessionToken; this.AuthorityTokens = authorityTokens; this.DisplayName = displayName; this.DataGroupOids = authorityGroups; this.EmailAddress = emailAddress; this.WarningMessages = new List<string>(); }
private static LoginCredentials CreateLoginCredentials(string loginId, string name, SessionToken token) { var credentials = new LoginCredentials { UserName = loginId, DisplayName = name, SessionToken = token }; return credentials; }
/// <summary> /// Initializes a new instance of the <see cref="AdministrationApi" /> class. /// </summary> /// <param name="currentToken"> /// The current token. /// </param> public AdministrationApi(SessionToken currentToken) { if (currentToken.IsValid() && currentToken.TokenType == TokenType.Config) { this.CurrentToken = currentToken; // Once all of the BaseApi settings have been created, pass the AdministrationApi into the constructor of all of the sub API managers this.REST = new RestManager(this); this.Licenses = new LicenseManager(this); this.Customers = new CustomerManager(this); } }
public void RemoveSession(SessionToken session) { if (session == null) throw new Exception("Token cannot be null"); lock (_sync) { _cache.Remove(session.Id); if (Platform.IsLogLevelEnabled(LogLevel.Debug)) Platform.Log(LogLevel.Debug, "Session {0} is removed", session.Id); } }
public void AddSession(SessionToken session) { if (session == null) throw new Exception("Token cannot be null"); if (session.ExpiryTime < Platform.Time) { throw new Exception(String.Format("Token {0} already expired. Cannot be updated.", session.Id)); } lock (_sync) { _cache.Insert(session.Id, session, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration); if (Platform.IsLogLevelEnabled(LogLevel.Debug)) Platform.Log(LogLevel.Debug, "Session {0} is added", session.Id); } }
public InitiateSessionResponse InitiateSession(InitiateSessionRequest request) { bool ok = Membership.ValidateUser(request.UserName, request.Password); if (ok) { Guid tokenId = Guid.NewGuid(); var token = new SessionToken(tokenId.ToString(), Platform.Time + ServerPlatform.WebSessionTimeout); string[] authority = Roles.GetRolesForUser(request.UserName); string displayName = request.UserName; var rsp = new InitiateSessionResponse(token, authority, new Guid[0], displayName,string.Empty); SessionTokenManager.Instance.AddSession(token); return rsp; } throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException()); }
public SessionToken UpdateSession(SessionToken token) { if (token == null) throw new Exception("Token cannot be null"); if (token.ExpiryTime < Platform.Time) { throw new Exception(String.Format("Token {0} already expired. Cannot be updated.", token.Id)); } lock (_sync) { RemoveSession(token); var newSession = new SessionToken(token.Id, Platform.Time + ServerPlatform.WebSessionTimeout); AddSession(newSession); return newSession; } }
public static List <T> PutListResult <T>(string virtualPath, string queryString, SessionToken token, object postData, params object[] virtualPathArgs) where T : RestObject, new() { JObject resultData = Put(virtualPath, queryString, token, postData, virtualPathArgs); return(ConvertToRestTokenObjectList <T>(token, resultData)); }
/// <summary> /// Creates an object that implements <see cref="IPrincipal"/> based on the specified /// identity and session token. The authorizations will be automatically obtained /// via the <see cref="IAuthenticationService"/>. /// </summary> /// <param name="identity"></param> /// <param name="sessionToken"></param> /// <returns></returns> public static IPrincipal CreatePrincipal(IIdentity identity, SessionToken sessionToken) { return new DefaultPrincipal(identity, sessionToken, null); }
private void LogOut(SessionToken token) { _proxy.logout(new logoutRequest{ logout = new logout {sessionToken = token}}); }
public ValidateSessionResponse(SessionToken sessionToken, string[] authorityTokens, Guid[] dataGroupOids) { this.SessionToken = sessionToken; this.AuthorityTokens = authorityTokens; DataGroupOids = dataGroupOids; }
private SfRserver GetServer(string serverName, string farm, SessionToken token, IEnumerable<DeviceID> deviceIds, out DeviceID deviceId) { deviceId = null; foreach (var currentDeviceId in deviceIds) { try { var rServerRequest = new listServerfarmRservers { deviceID = currentDeviceId, serverfarmname = farm, sessionToken = token }; var rServers = _proxy.listServerfarmRservers(new listServerfarmRserversRequest { listServerfarmRservers = rServerRequest }); var sfRServer = rServers.listServerfarmRserversResponse.SfRservers.Single(x => x.realserverName.ToLower() == serverName.ToLower()); deviceId = currentDeviceId; return sfRServer; } catch(FaultException<WSException> aceEx) { Logger.Verbose("Web Service Fault: {0}", aceEx.Message); Logger.Verbose("Since this device [{0}] faulted, ConDep will try next device.", currentDeviceId.name); } } throw new ConDepLoadBalancerException("Unable to get real server from load balancer. Use verbose logging for more details."); }
private string NewSession(string ipAddress, string userName) { var token = new SessionToken { Expiry = DateTime.UtcNow + _sessionTimeout, IpAddress = ipAddress, Token = Guid.NewGuid().ToString("n"), Username = userName }; lock (_sessionTokens) { _sessionTokens.Add(token.Token, token); } return token.Token; }
public ValidateSessionRequest(string userName, SessionToken sessionToken) { this.UserName = userName; this.SessionToken = sessionToken; }
/// <summary> /// GET a List of T back. Use when you are expecting and array of results. /// </summary> /// <param name="virtualPath">Path you want to access based on the base url of the token. Start it with '~/'</param> /// <param name="queryString">The query string, already URL encoded</param> /// <param name="expand">If set to true, the request will return all available fields.</param> /// <param name="fields">A comma-delimited list of fields to return. If none are supplied, the server will return the default fields.</param> /// <param name="token">The current token.</param> /// <param name="virtualPathArgs">The arguments to replace the tokens ({0},{1}, etc.) in the virtual path</param> /// <returns></returns> public static Page <T> GetPagedResult <T>(string virtualPath, string queryString, RequestOptions options, SessionToken token, params object[] virtualPathArgs) where T : RestObject, new() { JToken resultData = Get(virtualPath, queryString, options, token, virtualPathArgs); Page <T> result = ConvertToRestTokenObjectPage <T>(token, resultData); return(result); }
public static T Delete <T>(string virtualPath, string queryString, SessionToken token, params object[] virtualPathArgs) where T : RestObject, new() { JObject resultData = Delete(virtualPath, queryString, token, virtualPathArgs); return(ConvertToRestTokenObject <T>(token, resultData)); }
public static ApiMetaData PutReturnMeta(string virtualPath, string queryString, SessionToken token, object postData, params object[] virtualPathArgs) { JObject resultData = Put(virtualPath, queryString, token, postData, virtualPathArgs); return(ConvertToRestTokenToApiMetaData(token, resultData)); }
public GetAuthorizationsRequest(string user, SessionToken sessionToken) { this.UserName = user; this.SessionToken = sessionToken; }
public Session(SessionToken sessionToken, UserId userId) { SessionToken = sessionToken; UserId = userId; }
public DefaultAuthorizationPolicy(string userName, SessionToken sessionToken) { _userName = userName; _sessionToken = sessionToken; }
/// <summary> /// Gets the session identified by the specified session token, or null if no session exists. /// </summary> /// <param name="sessionToken"></param> /// <returns></returns> private UserSession GetSession(SessionToken sessionToken) { if (String.IsNullOrEmpty(sessionToken.Id)) return null; //we know this isn't valid, so don't go to the database. var where = new UserSessionSearchCriteria(); where.SessionId.EqualTo(sessionToken.Id); // use query caching here to hopefully speed this up a bit var sessions = PersistenceContext.GetBroker<IUserSessionBroker>().Find( where, new SearchResultPage(0, 1), new EntityFindOptions { Cache = true }); // ensure case-sensitive match, returns null if no match return CollectionUtils.SelectFirst(sessions, s => s.SessionId == sessionToken.Id); }
public ValidateSessionResponse(SessionToken sessionToken, string[] authorityTokens) { this.SessionToken = sessionToken; this.AuthorityTokens = authorityTokens; }
public SessionToken Renew(string tokenId, DateTime time) { lock (_sync) { var sessionInfo = _cacheSessionInfo[tokenId]; var newToken = new SessionToken(sessionInfo.Credentials.SessionToken.Id, time); sessionInfo.Credentials.SessionToken = newToken; if (Platform.IsLogLevelEnabled(LogLevel.Debug)) Platform.Log(LogLevel.Debug, "Session {0} renewed. Will expire on {1}", sessionInfo.Credentials.SessionToken.Id, sessionInfo.Credentials.SessionToken.ExpiryTime); return newToken; } }
private DefaultPrincipal(IIdentity identity, SessionToken sessionToken, string[] authorityTokens) { _identity = identity; _sessionToken = sessionToken; _authorityTokens = authorityTokens; }
private IEnumerable<DeviceID> GetDeviceIds(SessionToken token) { var deviceIdsRequest = new listDeviceIds { sessionToken = token, deviceType = DeviceType.VIRTUAL_CONTEXT }; var deviceIds = _proxy.listDeviceIds(new listDeviceIdsRequest { listDeviceIds = deviceIdsRequest}); return deviceIds.listDeviceIdsResponse.DeviceIDs; }
public static ApiMetaData GetReturnMeta(string virtualPath, string queryString, RequestOptions options, SessionToken token, params object[] virtualPathArgs) { JObject resultData = Get(virtualPath, queryString, options, token, virtualPathArgs); return(ConvertToRestTokenToApiMetaData(token, resultData)); }
public SessionInfo(string loginId, string name, SessionToken token) : this(new CustomPrincipal(new CustomIdentity(loginId, name), CreateLoginCredentials(loginId, name, token))) { }
private SfRserver GetServer(string serverName, string farm, SessionToken token, DeviceID deviceId) { var rServerRequest = new listServerfarmRservers {deviceID = deviceId, serverfarmname = farm, sessionToken = token}; var rServers = _proxy.listServerfarmRservers(new listServerfarmRserversRequest { listServerfarmRservers = rServerRequest}); var sfRServer = rServers.listServerfarmRserversResponse.SfRservers.Single(x => x.realserverName.ToLower() == serverName.ToLower()); return sfRServer; }
/// <summary> /// GET the virtual path with the querystring and field options /// </summary> /// <param name="virtualPath">Path you want to access based on the base url of the token. Start it with '~/'</param> /// <param name="queryString">The query string, already URL encoded</param> /// <param name="expand">If set to true, the request will return all available fields.</param> /// <param name="fields">A comma-delimited list of fields to return. If none are supplied, the server will return the default fields.</param> /// <param name="token">The current token.</param> /// <param name="virtualPathArgs">The arguments to replace the tokens ({0},{1}, etc.) in the virtual path</param> /// <returns></returns> public static JObject Get(string virtualPath, string queryString, RequestOptions options, SessionToken token, params object[] virtualPathArgs) { if (options == null) { options = new RequestOptions(); } options.PrepForRequest(); var client = new HttpClient(); JObject resultData = null; CleanupVirtualPathArgs(virtualPathArgs); string url = token.CreateUrl(string.Format(virtualPath, virtualPathArgs), options.GetQueryString(queryString), HttpMethod.Get, options.Fields, options.Expand); string signature = CreateAuthorization(client.DefaultRequestHeaders, new Uri(url), "GET", string.Empty, token.DeveloperKey, token.DeveloperSecret); client.DefaultRequestHeaders.Add("X-Authorization", signature); OutputCurlCommand(client, HttpMethod.Get, url, null); Task task = client.GetAsync(url).ContinueWith(async taskwithresponse => { try { JObject result = await taskwithresponse.Result.Content.ReadAsAsync <JObject>(); resultData = ProcessResultData(result, url, HttpMethod.Get); } catch (Exception ex) { HandleTaskException(taskwithresponse, ex, HttpMethod.Get); } }); task.Wait(); return(resultData); }
private DeviceID GetDeviceId(SessionToken token) { var deviceIdsRequest = new listDeviceIds { sessionToken = token, deviceType = DeviceType.VIRTUAL_CONTEXT }; var deviceIds = _proxy.listDeviceIds(new listDeviceIdsRequest { listDeviceIds = deviceIdsRequest}); return string.IsNullOrWhiteSpace(_chassisIp) ? deviceIds.listDeviceIdsResponse.DeviceIDs[0] : deviceIds.listDeviceIdsResponse.DeviceIDs.Single(x => x.chassisIPAddr == _chassisIp); }
static void AuthorizeRequest(object sender, EventArgs e) { SessionInfo session=null; try { if (HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity) { // Note: If user signed out in another window, the ticket would have been // removed from the browser and this code shoudn't be executed. // resemble the SessionInfo from the ticket. var loginId = (FormsIdentity) HttpContext.Current.User.Identity ; FormsAuthenticationTicket ticket = loginId.Ticket; String[] fields = ticket.UserData.Split('|'); String tokenId = fields[0]; String userDisplayName = fields[1]; SessionToken token = new SessionToken(tokenId, ticket.Expiration); session = new SessionInfo(loginId.Name, userDisplayName, token); if (ticket.Version > 1) { if (!string.IsNullOrEmpty(fields[2])) { var warningMessages = fields[2].Split('@'); session.User.WarningMessages = warningMessages.Length > 0 ? new List<string>(warningMessages) : new List<string>(); } if (!string.IsNullOrEmpty(fields[3])) { session.User.WarningsDisplayed = bool.Parse(fields[3]); } } // Initialize the session. This will throw exception if the session is no longer // valid. For eg, time-out. SessionManager.InitializeSession(session); } // TODO (CR Jan 2014): This is a worker thread, and thread names can only be // set once. This will forever give false information after the first use. if (String.IsNullOrEmpty(Thread.CurrentThread.Name)) { String user = SessionManager.Current != null ? SessionManager.Current.User.Identity.Name : "Unknown"; Thread.CurrentThread.Name = String.Format(SR.WebGUILogHeader, HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.Browser.Browser, HttpContext.Current.Request.Browser.Version, user); } } catch (SessionValidationException) { // SessionValidationException is thrown when the session id is invalid or the session already expired. // If session already expired, if (session != null && session.Credentials.SessionToken.ExpiryTime < Platform.Time) { SessionManager.SignOut(session); } else { // redirect to login screen SessionManager.TerminateSession("The current session is no longer valid.", SR.MessageCurrentSessionNoLongerValid); } } catch(Exception ex) { // log the exception ExceptionHandler.ThrowException(ex); } }
/// <summary> /// Creates an object that implements <see cref="IPrincipal"/> based on the specified /// identity, session token, and authorizations. /// </summary> /// <param name="identity"></param> /// <param name="sessionToken"></param> /// <param name="authorityTokens"></param> /// <returns></returns> public static IPrincipal CreatePrincipal(IIdentity identity, SessionToken sessionToken, string[] authorityTokens) { return new DefaultPrincipal(identity, sessionToken, authorityTokens); }
/// <summary>申请会话</summary> /// <exception cref="ArgumentNullException"/> /// <exception cref="YggdrasilService"/> public static bool Join(SessionToken token, string serverHash) => Join(token.AccessToken, token.PlayerUUID, serverHash);
public TerminateSessionRequest(string userName, SessionToken token) { this.UserName = userName; this.SessionToken = token; }
/// <summary> /// Start a new Client /// </summary> private static void InitializeClient() { SessionToken session = new SessionToken(); ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired; if (Settings.Password == "-") { ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode."); result = ProtocolHandler.LoginResult.Success; session.PlayerID = "0"; session.PlayerName = Settings.Login; } else { // Validate cached session or login new session. if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower())) { session = SessionCache.Get(Settings.Login.ToLower()); result = ProtocolHandler.GetTokenValidation(session); if (result != ProtocolHandler.LoginResult.Success) { ConsoleIO.WriteLineFormatted("§8Cached session is invalid or expired."); if (Settings.Password == "") { RequestPassword(); } } else { ConsoleIO.WriteLineFormatted("§8Cached session is still valid for " + session.PlayerName + '.'); } } if (result != ProtocolHandler.LoginResult.Success) { Console.WriteLine("Connecting to Minecraft.net..."); result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session); if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None) { SessionCache.Store(Settings.Login.ToLower(), session); } } } if (result == ProtocolHandler.LoginResult.Success) { Settings.Username = session.PlayerName; if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } if (Settings.playerHeadAsIcon) { ConsoleIcon.setPlayerIconAsync(Settings.Username); } if (Settings.DebugMessages) { Console.WriteLine("Success. (session ID: " + session.ID + ')'); } //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE if (Settings.ServerIP == "") { Console.Write("Server IP : "); Settings.SetServerIP(Console.ReadLine()); } //Get server version int protocolversion = 0; ForgeInfo forgeInfo = null; if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto") { protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion); if (protocolversion != 0) { ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')'); } else { ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode."); } if (useMcVersionOnce) { useMcVersionOnce = false; Settings.ServerVersion = ""; } } if (protocolversion == 0 || Settings.ServerMayHaveForge) { if (protocolversion != 0) { Console.WriteLine("Checking if server is running Forge..."); } else { Console.WriteLine("Retrieving Server Info..."); } if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo)) { HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost); return; } } if (protocolversion != 0) { try { //Start the main TCP client if (Settings.SingleCommand != "") { client = new McClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand); } else { client = new McClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort); } //Update console title if (Settings.ConsoleTitle != "") { Console.Title = Settings.ExpandVars(Settings.ConsoleTitle); } } catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); } } else { HandleFailure("Failed to determine server version.", true); } } else { string failureMessage = "Minecraft Login failed : "; switch (result) { case ProtocolHandler.LoginResult.AccountMigrated: failureMessage += "Account migrated, use e-mail as username."; break; case ProtocolHandler.LoginResult.ServiceUnavailable: failureMessage += "Login servers are unavailable. Please try again later."; break; case ProtocolHandler.LoginResult.WrongPassword: failureMessage += "Incorrect password, blacklisted IP or too many logins."; break; case ProtocolHandler.LoginResult.InvalidResponse: failureMessage += "Invalid server response."; break; case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break; case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break; case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break; default: failureMessage += "Unknown Error."; break; } if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono) { ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program." + '\n' + "The first time, you have to import HTTPS certificates using:" + '\n' + "mozroots --import --ask-remove"); return; } HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected); } }