/// <summary> /// Attempts to get the OAuth Ticket ID from the login attempt. /// </summary> /// <param name="client">Restclient to use.</param> /// <returns>The OAuth ticket if available or null.</returns> private string TryGetTicketId(RestClient client) { PTCLoginSessionCookie cookie = TryGetLoginSessionCookie(client); //Build the login request //lt=LTVALUE&_eventId=submit&username=USERNAMEy&password=PASSWORD&Login=Sign+In RestRequest request = new RestRequest(); request.AddParameter("application/x-www-form-urlencoded", $"lt={cookie.LT}&execution={cookie.ExecutionID}&_eventId={"submit"}&username={this.userLoginName}&password={this.userPassword}", ParameterType.RequestBody); //Wrap this block in a continue expected. Only way to do it with rest sharp IRestResponse loginResponse = client.Post(request); Parameter locationHeader = loginResponse.Headers.FirstOrDefault(h => h.Name == "Location"); if (locationHeader == null) { HandleNullLocationHeader(loginResponse); } string ticketId = null; try { //Like Rocket-API we must get the ticket id //WARNING: You must conver to Uri so we can generate the query ticketId = HttpUtility.ParseQueryString(new Uri(locationHeader.Value.ToString()).Query).Get("ticket"); } catch (Exception e) { throw new InvalidOperationException("Unable to get Ticket ID. Could be failed login or login to offline servers.", e); } if (ticketId == null) { throw new InvalidOperationException($"Unable to get Ticket ID. Could be failed login or login to offline servers. Location Value: {locationHeader.Value.ToString()} Content: {loginResponse.Content.ToString()}"); } return(ticketId); }
/// <summary> /// Handles cases when the location header in the login response is null. /// </summary> /// <param name="loginResponse">Login response with the null location header.</param> private void HandleNullLocationHeader(IRestResponse loginResponse) { if (loginResponse.Content != null && loginResponse.Content.Length != 0) { //try to get the cookie PTCLoginSessionCookie errorCookie = null; try { errorCookie = JsonConvert.DeserializeObject <PTCLoginSessionCookie>(loginResponse.Content.ToString()); } catch (Exception e) { } //If there is no location header it's likely that there is an error message in the form of a JSON object, the cookie, sent back to us. if (errorCookie != null && !errorCookie.isValid) { throw new ServerLoginException($"PTC Error: {errorCookie.ErrorStrings.Aggregate("", (e1, e2) => $"{e1} {e2}")}."); } } throw new InvalidOperationException("Error: Failed to parse Location Header from login response."); }