I want to pass data user Id and user code to another server and get the response using network.
So, I created this code
var webRequest = WebRequest.Create(#"http://10.2.1.85/");
It is working fine but I don't know how to pass the user Id and user code.
Do I have to create object or something?
How can I do it?
This is how to Post Data on Web Service:
WebService Post Function
public static string JsonPost(string url, string method, string postData)
{
Uri address = new Uri(url + method);
//Get User current network credential
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(address, "Basic");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
//Network Credential should be included on the request to avoid network issues when requesting to the web service
request.Proxy = WebRequest.DefaultWebProxy;
request.Credentials = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);
request.Proxy.Credentials = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string JsonResponse = reader.ReadToEnd();
return JsonResponse;
}
}
Login Function
public static string Login(string Email, string Password)
{
try
{
string postData = "{" + "\"Email\":\"" + Email + "\"," +
"\"Password\":\"" + Password + "\"" +
"}";
string JsonResult = JsonPost("Your Web Service URL", "Login", postData);
return JsonResult;
}
catch (Exception ex)
{
return "";
}
}
Example How To Use:
public void LoginUser()
{
string Email = "me#example.com";
string Password = "password";
string JsonUserAccount = Login(Email, Password);
if(!string.IsNullOrEmpty(JsonUserAccount))
{
Debug.Print("User logged in");
}
else
{
Debug.Print("Failed to logged in");
}
}
Related
I have 2 programs on my localhost, one with REST API and another program that calls the api.
I'm trying to authenticate user(https://localhost:44301/token) with below function and getting badRequest.
the same is working when testing with postman.
baseUrl is "https://localhost:44301/";
static async Task<Uri> AddCartRecordAsync(CartsTable cartsTable)
{
string ResponseString = "";
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(Utility.baseUrl + "token");
request.Accept = "application/json";
request.Method = "POST";
//Get credentials from config.
var username = "kkk#gmail.com";
var password = "Test123!";
Credentials cred = new Credentials()
{
username = username,
password = password,
grant_type = "password"
};
var myContent = JsonConvert.SerializeObject(cred);
var data = Encoding.ASCII.GetBytes(myContent);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
using (response = (HttpWebResponse)request.GetResponse())//BadRequest Here
{
ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
catch (Exception e)
{
string i = "df";
}
The common issues are :
1-Params Body Type
2-Authentication Type : if u have bearer type you should include bearer keyword before your token in the header before sending request like "token":"bearer AuthToken"
3-method type : get put post delete
I have created one .net Web application to fetch some data and metadata from Salesforce. So, this application first ask for the salesforce username and password to login and once log-in is successful, it will fetch some data from salesforce.
i am trying below code it is right way or wrong, please suggest proper way
string response_type = "code";
string client_id = "...";
string redirect_url = #"...";
string client_secret = "....";
// GET: LoginApp
public void Login()
{
authorize();
}
public void authorize()
{
Redirect("");
string URI = "";
StringBuilder body = new StringBuilder();
body.Append(URI);
body.Append("?response_type=" + response_type + "&");
body.Append("client_id=" + client_id + "&");
body.Append("client_secret=" + client_secret + "&");
body.Append("redirect_uri=" + redirect_url);
//string red_url = body.ToString();
string red_url = HttpPost(body.ToString());
Response.Redirect(URI);
}
public string HttpPost(string URI)
{
WebRequest request = WebRequest.Create(URI);
request.Method = "POST";
string postData = "This is a test data.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
string res = request.RequestUri.ToString();
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
return res;
}
I'm working on a C# Windows Form application and I would like to have the ability to test a users' credentials against Jira. Basically the user would input their username and password, click OK and the program will tell them if their credentials are accepted or not.
I already have working code (see below) that uses basic authentication via HttpWebRequest to create new tickets (aka issues), close tickets, add watchers, etc - so I figured this would be easy but I'm struggling with it.
As an analog, you can do a credentials check against Active Directory very easily using the System.DirectoryServices.AccountManagement namespace. Basically the method authenticateAD() will simply return true or false:
private bool authenticateAD(string username, string password)
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "example.com");
bool isValid = pc.ValidateCredentials(username,password);
return isValid;
}
This is exactly the kind of thing I want to do with Jira.
For reference, here's the code I'm using to add/close/update tickets in jira - maybe it can be modified to do what I want?
private Dictionary<string, string> sendHTTPtoREST(string json, string restURL)
{
HttpWebRequest request = WebRequest.Create(restURL) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
string mergedCreds = string.Format("{0}:{1}", username, password);
byte[] byteCreds = UTF8Encoding.UTF8.GetBytes(mergedCreds);
request.Headers.Add("Authorization", "Basic " + byteCreds);
byte[] data = Encoding.UTF8.GetBytes(json);
try
{
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
}
catch(Exception ex)
{
displayMessages(string.Format("Error creating Jira: {0}",ex.Message.ToString()), "red", "white");
Dictionary<string, string> excepHTTP = new Dictionary<string, string>();
excepHTTP.Add("error", ex.Message.ToString());
return excepHTTP;
}
response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var sData = jss.Deserialize<Dictionary<string, string>>(str);
if(response.StatusCode.ToString()=="NoContent")
{
sData.Add("code", "NoContent");
request.Abort();
return sData;
}
else
{
sData.Add("code", response.StatusCode.ToString());
request.Abort();
return sData;
}
}
Thanks!
How about attempting to access the root page of JIRA and see if you get an HTTP 403 error?
try
{
// access JIRA using (parts of) your existing code
}
catch (WebException we)
{
var response = we.Response as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.Forbidden)
{
// JIRA doesn't like your credentials
}
}
The HttpClient would be simple and best to use check credentials with GetAsync.
The sample code is below
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(JiraPath);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string mergedCreds = string.Format("{0}:{1}", username, password);
byte[] byteCreds = UTF8Encoding.UTF8.GetBytes(mergedCreds);
var authHeader = new AuthenticationHeaderValue("Basic", byteCreds);
client.DefaultRequestHeaders.Authorization = authHeader;
HttpResponseMessage response = client.GetAsync(restURL).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
strJSON = response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(strJSON))
return strJSON;
}
else
{
exceptionOccured = true;
// Use "response.ReasonPhrase" to return error message
}
}
So I'm making a small application for a vbulleting site but need to authenticate the user when he opens my application, I have code to send login request, but I am unsure how to actually check if the login was successful.
This is what I have so far:
public string Login(string username, string password)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MPGHLogin);
string cookie = "";
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false;
using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
writer.Write(values);
}
HttpWebResponse c = (HttpWebResponse)req.GetResponse();
foreach (Cookie cook in c.Cookies)
{
cookie = cookie + cook.ToString() + ";";
}
if (c.StatusCode != HttpStatusCode.OK)
return "FAILED_CONNECTION";
return cookie;
}
But how can I check if the authentication was successful?
For other people that may have the same problem, I completely forgot about checking the respone stream for a login successful message, so below is the full code.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MPGHLogin);
req.AllowAutoRedirect = true;
string cookie = "";
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false;
StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
writer.Write(values);
writer.Close();
req.Timeout = 5000;
HttpWebResponse c;
try {
c = (HttpWebResponse)req.GetResponse(); // da response
} catch(Exception e)
{
MessageBox.Show(e.Message, "Web Exception");
return "WebException";
}
foreach (Cookie cook in c.Cookies)
{
cookie = cookie + cook.ToString() + ";";
}
Stream resp = c.GetResponseStream();
StreamReader reader = new StreamReader(resp, Encoding.GetEncoding(c.CharacterSet));
string response = reader.ReadToEnd();
reader.Close();
reader.Dispose();
if (response.Contains("Thank you for logging in, " + username))
{
c.Dispose();
return cookie;
}
else
return "FAILED_AUTH";
I need to implement last.fm authentication in my Windows Phone 8 application. Last.fm requires a POST request with https for successful login. Here is what I'm doing.
public async void GetMobileSession(string userName, string password, Action<LastFmAuthResponse> onCompletion)
{
string CORE_URL = "https://ws.audioscrobbler.com/2.0/";
var parameters = new Dictionary<string, string>();
parameters.Add("username", userName);
parameters.Add("password", password);
parameters.Add("method", "auth.getMobileSession");
parameters.Add("api_key", api_key);
string signature = GetSignature(parameters);
string comboUrl = string.Concat("method=auth.getMobileSession", "&api_key=", api_key,
"&username=", userName, "&password=", password, "&api_sig=", signature);
LastFmAuthResponse response = null;
byte[] pendingPostContent = Encoding.UTF8.GetBytes(comboUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(CORE_URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(pendingPostContent, 0, pendingPostContent.Length);
}
request.BeginGetResponse(new AsyncCallback(n =>
{
HttpWebResponse rawResponse = (HttpWebResponse)request.EndGetResponse(n);
string rawData = string.Empty;
using (StreamReader reader = new StreamReader(rawResponse.GetResponseStream()))
{
rawData = reader.ReadToEnd();
}
try
{
if (!string.IsNullOrEmpty(rawData))
{
response = CommonFunctions.GetObjectFromString<LastFmAuthResponse>(rawData);
}
}
catch
{
}
onCompletion(response);
}), null);
}
However the code is failing at request.BeginGetResponse It returns an error saying remote server could not be found. Can someone please point out what I'm doing wrong here?