Problems with authentication on Huawei b525s-23a - c#

I have a Huawei b525-23a router. Using it's web interface you can send/check SMS but I want to do it automatically from an C# app. I didn't found any API documentation for it so any link will be very good.
I managed to find some HTTPRequests using Chrome but when I use it from C# I get the 125003 error that is according to some google search an authentication problem.
Here are some parts of my code :
private void button4_Click(object sender, EventArgs e)
{
// getting SenInfo and TokInfo
string urlTokenInfo = "http://192.168.8.1/api/webserver/SesTokInfo";
HttpWebRequest requestTokenInfo = (HttpWebRequest)WebRequest.Create(urlTokenInfo);
requestTokenInfo.Method = "GET";
WebResponse responseTokenInfo = requestTokenInfo.GetResponse();
Stream responseTokenInfoStream = responseTokenInfo.GetResponseStream();
string responseTokenInfoString = new StreamReader(responseTokenInfoStream).ReadToEnd();
var rootElement = XElement.Parse(responseTokenInfoString);
string sessionId = rootElement.Element("SesInfo").Value;
string tokenInfo = rootElement.Element("TokInfo").Value;
//_________________________________________________________________________________
// trying to log
String urlLogin = "http://192.168.8.1/api/user/login";
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create(urlLogin);
requestLogin.Method = "POST";
String XMLLogin;
String base64Passwd = Base64Encode(passwd); //function for base64 encode
XMLLogin = " <request ><Username> " + userName + " </Username><Password> " + base64Passwd + " </Password></request> ";
byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(XMLLogin);
requestLogin.ContentType = "text/xml;charset=utf-8";
requestLogin.ContentLength = requestInFormOfBytes.Length;
Stream requestStream = requestLogin.GetRequestStream();
requestStream.Write(requestInFormOfBytes, 0, requestInFormOfBytes.Length);
requestLogin.Headers.Add("__RequestVerificationToken", tokenInfo);
requestLogin.Headers.Add("Cookie", sessionId);
WebResponse raspuns = (HttpWebResponse)requestLogin.GetResponse();
Stream responseStreamLogin = raspuns.GetResponseStream();
string responseStrlogin = new StreamReader(responseStreamLogin).ReadToEnd();
}
}
The response that I get is
<?xml version="1.0" encoding="UTF-8"?><error><message></message><code>125003</code></error>
Thank you for your time reading this and any response will be apreciated.
Mihai Stanciu

125003 error means token verification failed.
Check the session and token values in the first html resource request file

Related

Calling PHP Web -Service from C# Windows Form

I am trying to verify username, password, and software token number of a C# Windows Form to values in MySQL database.
My C# Code:
private void btnlogin_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtusername.Text))
{
MessageBox.Show("Please insert username");
}
if (String.IsNullOrEmpty(txtpassword.Text))
{
MessageBox.Show("Please insert password");
}
var username = txtusername.Text;
var password = txtpassword.Text;
string Token = "28956";
var SoftwareToken = token;
WebRequest request = WebRequest.Create("https://mydomain.com.au/Verification.php?username=username&password=password&Token=SoftwareToken");
request.Method = "GET";
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
responseFromServer.ToArray();
/*I have tried:
responseFromServer.ToArray();(because result on php page is an array.
I have tried responseFromServer.ToString();*/
MessageBox.Show(responseFromServer);
}
My PHP code (Web service):
<?php
// Database Structure
require_once('connect.php');
//Get password from the database for the user
$stmtus = $conn->prepare("SELECT password from `Users` where `email` = :Username");
$stmtus->bindParam(':Username', $username);
$username= $_GET['username'];;
$stmtus -> execute();
$password = $stmtus->fetch();
$un = $_GET['username'];
$pw = $_GET['password'];
$ust = $_GET['Token'];
if(password_verify($pw, $password[0])){
$stmt = $conn->prepare("SELECT
COUNT(Token) AS cnt FROM `SoftwareToken`
LEFT JOIN User ON iduser = SoftwareToken.Consultant
WHERE Token = '$ust'
AND username = '$un'");
$stmt->bindValue(':Username', $un);
$stmt->bindValue(':Token', $ust);
$stmt->execute();
$result= array();
while($SToken= $stmt->fetch(PDO::FETCH_OBJ)){
array_push($result, $SToken->cnt);
}
echo json_encode($result);
}
$conn = null;
?>
I am battling to understand how I call the web service from the C# application, how do I pass the variables from the C# application to the web service and how do I return the json_encode to the C# application from the web service.
I am not a full-time programmer and this is my first encounter with web services. If there are any suggestions on how to improve either of the codes, I would much appreciate.
UPDATE
I have updated my code as assisted. When I run the php code with variables it runs and gives me a $result (array). A numeral answer 1.
When I test my code to display the result in a MessageBox, the MessageBox is empty. Why ?
Of course you can call WebService from C#.
There is a built in calss in System.
One Way:
WebRequest request = WebRequest.Create("http://localhost:8080/?username=john");
request.Method="GET";
WebResponse response = request.GetResponse();
Other Way:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
HttpResponseMessage response = await client.PostAsJsonAsync( "api/user", userName);
response.EnsureSuccessStatusCode();
Code which I used:
var username = txtusername.Text;
var password = txtpassword.Text;
string Token = "28956";
var url = "https://mydomain.com.au/LoginVerification.php?";
var var = "username=" + username + "&password=" + password + "&Token=" + Token ;
var URL = url + var;
//MessageBox.Show(URL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
//MessageBox.Show(responseFromServer);
// Display the content.
if (responseFromServer == "\n Allow")
{
MessageBox.Show("Success");
}

Retrieve/fetch data to display to my ASP.Net web application from PHP service thats connected to remote MySQL database

So I have a remote(hosted) MySQL database which I connect to with a PHP service. I need both my ASP.Net c# web application and my android to communicate with it. However, I'm struggling with populating my web application template with all the information I retrieve from the service. For instance, I would like to populate a profile page of the user.
Below would be my PHP connection and communication to the database:
`// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Vendor Where VendorId = 2"; //this is just a test
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo . $row["id"]. . $row["BusinessName"]. . $row["Location"]. . $row["Email"]. .$row["Website"]. .$row["ProductType"]. .$row["Contact"]. .$row["PaymentOption"]. .$row["ProfileImg"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
`
and then (without sharing all my setups) this would be the code sample for asp.net c# to communicate with my PHP file/service.
public void getUserInfo(int id)
{
string BusinessName = lblBusiness.Text.Trim();
string email = lblEmail.Text.Trim();
string Contact = lblPhone.Text.Trim();
string location = lblLocation.Text.Trim();
string Website = lblWebsite.Text.Trim();
string payment = lblPayment.Text.Trim();
//Variables to get information from the service
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
//Stores the result from the server
string responseFromServer = null;
try
{
string requestMethod = "GET";
//Sending this data across the stream
string postData = "&Email=" + email + "&BusinessName=" + BusinessName + "&Website=" + Website + "&PaymentOption=" + payment + "&Location=" + location + "&ProductType=" + ProductType + "&Contact=" + Contact + "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
string URL = "";// url of php service location
string contenttype = "application/x-www-form-urlencoded";
//Create link to web service
WebRequest request = WebRequest.Create(URL);
//Pass the request method
request.Method = requestMethod;
request.ContentType = contenttype;
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
//Get response from the server
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (dataStream != null && reader != null && response != null)
{
dataStream.Close();
reader.Close();
response.Close();
}
//Getting the response from the service
//string result = responseFromServer.ToString();
}
}
also, Im not sure what to return from that function.
Please help.
Your php file is the "API" i pressume.
You basically need to return this from your php file.
$vendorArray = [
"Id" => $row["id"],
"BusinessName" => $row["BusinessName"],
// ... this is just pseudo code, convert the array or take the array or something like that
];
header('Content-type: application/json');
echo json_encode($vendorArray);
then in asp.net you do:
var deserializedVendor = JsonConvert.DeserializeObject<Vendor>(responseFromServer);
Your vendor class has to match your jsonObject to be Deserializable
public class Vendor {
public string Id {get;set;}
public string BusinessName {get;set;}
...
}
it depends on your jsonResponse...
you can also deserialize directly into a complex item with a list of vendors like this:
var allTheVendorsDeserialized = JsonConvert.DeserializeObject<AllTheVendors>(responseFromServer);
public class AllTheVendors {
public bool Success {get;set}
public List<Vendor> {get;set}
}
where php:
$arr = ["Success" => true, $myArrayOfVendors];
header('Content-type: application/json');
echo json_encode($arr);
I believe, your PHP web application is hosted and you can use the PHP service in ASP.NET with the following steps:
WebClient client = new WebClient(); //Create WebClient object
string url = "http://test.com/test.php"; //Get the URL of the PHP service
byte[] html = client.DownloadData(url); //Byte array to hold returned data from the service
Finally use the UTF8Encoding object to convert the byte array into sring:
UTF8Encoding utf = new UTF8Encoding(); //Create an object of the UTF8Encoding class
string str = utf.GetString(html); //Convert data into string

Can't create workitem via webrequest in RTC

I'm trying to create a .NET web application integration with RTC, where I would insert new workitems using RTC change management services, as defined in this article (specifically in "Create a Change Request"). I was able to get the URL-to-be-used inside services.xml file (/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/) and my goal is to insert data using JSON.
My code is basically the following:
CookieContainer cookies = new CookieContainer();
HttpWebRequest documentPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/order");//"Order" is the workitem name
documentPost.Method = "POST";
documentPost.CookieContainer = cookies;
documentPost.Accept = "application/json";
documentPost.ContentType = "application/x-oslc-cm-change-request+json";
documentPost.Timeout = TIMEOUT_SERVICO;
string json = "{ \"dc:title\":\"" + title + "\", \"rtc_cm:filedAgainst\": [ { \"rdf:resource\" : \"" + rtcServerUrl + "/resource/itemOid/com.ibm.team.workitem.Category/" + idCategory + "\"} ] }"; //dc:title and rtc_cm:filedAgainst are the only two mandatory data from the workitem I'm trying to create
using (var writer = new StreamWriter(documentPost.GetRequestStream()))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Encoding encode = System.Text.Encoding.UTF8;
string retorno = null;
//Login
HttpWebRequest formPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/j_security_check");
formPost.Method = "POST";
formPost.Timeout = TIMEOUT_REQUEST;
formPost.CookieContainer = request.CookieContainer;
formPost.Accept = "text/xml";
formPost.ContentType = "application/x-www-form-urlencoded";
String authString = "j_username=" + userName + "&j_password=" + password; //create authentication string
Byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes(authString); //store in byte buffer
formPost.ContentLength = outBuffer.Length;
System.IO.Stream str = formPost.GetRequestStream();
str.Write(outBuffer, 0, outBuffer.Length); //update form
str.Close();
//FormBasedAuth Step2:submit the login form and get the response from the server
HttpWebResponse formResponse = (HttpWebResponse)formPost.GetResponse();
var rtcAuthHeader = formResponse.Headers["X-com-ibm-team-repository-web- auth-msg"];
//check if authentication has failed
if ((rtcAuthHeader != null) && rtcAuthHeader.Equals("authfailed"))
{
//authentication failed. You can write code to handle the authentication failure.
//if (DEBUG) Console.WriteLine("Authentication Failure");
}
else
{
//login successful
HttpWebResponse responseRetorno = (HttpWebResponse)request.GetResponse();
if (responseRetorno.StatusCode != HttpStatusCode.OK)
retorno = responseRetorno.StatusDescription;
else
{
StreamReader reader = new StreamReader(responseRetorno.GetResponseStream());
retorno = "[Response] " + reader.ReadToEnd();
}
responseRetorno.Close();
formResponse.GetResponseStream().Flush();
formResponse.Close();
}
As I was managed to search for in other forums, this should be enough in order to create the workitem (I have a very similar code working to update workitems using "" URL and PUT method). However, instead of create the workitem in RTC and give me some response with item's identifier, the request's response returns a huge JSON file that ends with "oslc_cm:next":"https:///oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/%7B0%7D?oslc_cm.pageSize=50&_resultToken=_AAY50FEkEee1V4u7RUQSjA&_startIndex=50. It's a JSON representation of the XML I receive when I access /oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/ directly from browser, like I was trying to do a simple query inside the workitem's collection (even though I'm using POST, not GET).
I also tried to use PUT method, but then I receive a 405 status code.
Does anyone have an idea of what am I missing here? My approach is wrong, even though with the same approach I'm able to update existing workitem data in RTC?
Thanks in advance.

HP ALM 12.21 REST API - 401 Unauthorized - C#

I am trying to use the API against our ALM 12.21 server, but always ends up with "401 Unauthorized". It seems that I get the auth cookie back correctly, but when I try to do something after that I am unauthorized.
I use this the get this to get auth cookie (seems to work):
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create("https://server/qcbin/authentication-point/alm-authenticate");
string AuthenticationXML = #"<alm-authentication>
<user>username</user>
<password>password</password>
</alm-authentication>";
byte[] Requestbytes = Encoding.UTF8.GetBytes(AuthenticationXML);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
var AuthenticationCookie = myauthres.Headers.Get("Set-Cookie");
AuthenticationCookie = AuthenticationCookie.Replace(";Path=/;HTTPOnly", "");
I am not sure if the .Replace is needed. Just read it somewhere. I get 401 both with or without it though, when trying to do subsequent requests.
Trying e.g. this after getting auth cookie:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://server/qcbin/rest/domains/FS/projects/P3602_SLS_Project/defects/1");
req.Method = "GET";
req.ContentType = "application/xml";
req.Accept = "application/octet-stream";
req.Headers.Set(HttpRequestHeader.Cookie, AuthenticationCookie);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream RStream2 = res.GetResponseStream();
XDocument doc = XDocument.Load(RStream2);
Which fails with 401.
Anyone have complete working code for the ALM 12.21 REST API?
You need two main cookies to get the ALM REST API works perfectly.
LWSSO_COOKIE_KEY
QCSession
almURL = "https://..com/qcbin/"
authEndPoint = almURL + "authentication-point/authenticate"
qcSessionEndPoint = almURL + "rest/site-session"
After you get successful response for authEndPoint you will get the LWSSO_COOKIE_KEY
Use that cookie in your next request to qcSessionEndPoint, it should give you QCSession cookie.
Use both LWSSO_COOKIE_KEY and QCSession cookies in your subsequent requests to get data from ALM.
I see that you are using octet-stream to get the defect response. When I checked the documentation, it can return one of the following types.
"application/xml"
"application/atom+xml"
"application/json"
Just in case, if you need to see some working implementation in python, here it is https://github.com/macroking/ALM-Integration/blob/master/ALM_Integration_Util.py
It may give you some idea.
Thank you #Barney. You sent me in the correct direction :-) For anyone interested, I managed it like this, e.g. for getting defect ID 473:
Logging on to create a CookieContainer and then use that to do the actual ALM data fetch:
private void button1_Click(object sender, EventArgs e)
{
string almURL = #"https://url/qcbin/";
string domain = "domain";
string project = "project";
CookieContainer cookieContainer = LoginAlm2(almURL, "username", "password", domain, project);
HttpWebRequest myWebRequest1 = (HttpWebRequest)WebRequest.Create(almURL + "/rest/domains/" + domain + "/projects/" + project + "/defects/473");
myWebRequest1.CookieContainer = cookieContainer;
myWebRequest1.Accept = "application/json";
WebResponse webResponse1 = myWebRequest1.GetResponse();
StreamReader reader = new StreamReader(webResponse1.GetResponseStream());
string res = reader.ReadToEnd();
}
public CookieContainer LoginAlm2(string server, string user, string password, string domain, string project)
{
//Creating the WebRequest with the URL and encoded authentication
string StrServerLogin = server + "/api/authentication/sign-in";
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(StrServerLogin);
myWebRequest.Headers[HttpRequestHeader.Authorization] = "Basic " + Base64Encode(user + ":" + password);
WebResponse webResponse = myWebRequest.GetResponse();
CookieContainer c = new CookieContainer();
Uri uri = new Uri(server);
string StrCookie = webResponse.Headers.ToString();
string StrCookie1 = StrCookie.Substring(StrCookie.IndexOf("LWSSO_COOKIE_KEY=") + 17);
StrCookie1 = StrCookie1.Substring(0, StrCookie1.IndexOf(";"));
c.Add(new Cookie("LWSSO_COOKIE_KEY", StrCookie1) { Domain = uri.Host });
//Then the QCSession cookie
string StrCookie2 = StrCookie.Substring(StrCookie.IndexOf("QCSession=") + 10);
StrCookie2 = StrCookie2.Substring(0, StrCookie2.IndexOf(";"));
c.Add(new Cookie("QCSession", StrCookie2) { Domain = uri.Host });
//Then the ALM_USER cookie
string StrCookie3 = StrCookie.Substring(StrCookie.IndexOf("ALM_USER=") + 9);
StrCookie3 = StrCookie3.Substring(0, StrCookie3.IndexOf(";"));
c.Add(new Cookie("ALM_USER", StrCookie3) { Domain = uri.Host });
//And finally the XSRF-TOKEN cookie
string StrCookie4 = StrCookie.Substring(StrCookie.IndexOf("XSRF-TOKEN=") + 12);
StrCookie4 = StrCookie4.Substring(0, StrCookie4.IndexOf(";"));
c.Add(new Cookie("XSRF-TOKEN", StrCookie4) { Domain = uri.Host });
return c;
}
Works like a charm :-)

c# login Google App Engine (GAE) returns http 500

c# login Google App Engine (GAE) returns http 500
c# google-app-engine http-status-code-500
I want to retrive user specific data form the app engine with a c# client. The Client uses the following code to authenticate:
private const string GoogleLoginUri = "https://www.google.com/accounts/ClientLogin";
private const string AppBaseUri = "http://sphinx-online.appspot.com/";
private const string AppLoginUri = AppBaseUri + "_ah/login";
private const string AppMyStarredQuestionnaireUri = AppBaseUri + "res/MyStarredQuestionnaires";
[...]
private static void RetrieveAuthToken(SyncStorage syncStorage)
{
// Request
HttpWebRequest authRequest = (HttpWebRequest)HttpWebRequest.Create(GoogleLoginUri);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.AllowAutoRedirect = false;
String postData = string.Format("Email={0}&Passwd={1}&service={2}&source={3}&accountType={4}",
Uri.EscapeUriString(syncStorage.Username),
Uri.EscapeUriString(syncStorage.Password),
Uri.EscapeUriString("apps"),
Uri.EscapeUriString("lippodesign-sphinx-1.0"),
Uri.EscapeUriString("GOOGLE"));
byte[] buffer = Encoding.ASCII.GetBytes(postData);
authRequest.ContentLength = buffer.Length;
using (Stream postDataStr = authRequest.GetRequestStream())
{
postDataStr.Write(buffer, 0, buffer.Length);
postDataStr.Flush();
}
// Response
HttpWebResponse authResponse = (HttpWebResponse)authRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(authResponse.GetResponseStream()))
{
while (true)
{
String line = responseReader.ReadLine();
if (line == null)
{
break;
}
else if (line.StartsWith("Auth="))
{
syncStorage.AuthToken = line.Substring(5);
break;
}
}
}
}
private static void RetrieveCookie(SyncStorage syncStorage)
{
Uri cookieRequestUrl = new Uri(string.Format("{0}?auth={1}", AppLoginUri, syncStorage.AuthToken));
HttpWebRequest cookieRequest = (HttpWebRequest)WebRequest.Create(cookieRequestUrl);
cookieRequest.Method = "GET";
cookieRequest.ContentType = "application/x-www-form-urlencoded";
cookieRequest.AllowAutoRedirect = false;
using (HttpWebResponse cookieResponse = (HttpWebResponse)cookieRequest.GetResponse())
{
syncStorage.Cookie = cookieResponse.Headers["Set-Cookie"];
}
}
private static void RetrieveData(SyncStorage syncStorage)
{
Uri dataRequestUrl = new Uri(AppMyStarredQuestionnaireUri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(dataRequestUrl);
request.Headers["Cookie"] = syncStorage.Cookie;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
syncStorage.JsonData = streamReader.ReadToEnd();
}
}
}
All works fine for a while, but since I try it before two days I always get an http-error-code 500 (Internal Error) when I want to get the cookie (RetrieveCookie-Method). I think it does not work since I activate 2-Step-Authentication. The Google ClientLogin for Installed Applications says:
Important: If any of your customers are having trouble with ClientLogin, their account may not be compatible with it for a variety of possible reasons. For example, accounts that use 2-step verification, SAML, or Open ID are not compatible with ClientLogin. One workaround is to tell users to generate a single-use password, provided by access codes, which allows them to log in to their account in a web browser and generate a long password that they can type into the password field of any application using ClientLogin. A better solution is to convert your app to use OAuth 2.0, which is compatible with all existing Google accounts.
I use an Application-specific password for login. Before I get a http-error 403 "Authentication failed" while getting the auth-token.
I have no idea why I can't retrieve the cookie. Getting the auth-token works fine.
And the Webservice has no problem, I can call it over a browser without having trouble if I am loggend in.

Categories

Resources