cockies is null when HttpWebResponse in formauthentication - c#

I have an application where I used signalr. and formAuthentication. I am trying to connect hub class from WCF service. IN WCF service code is as bellow:
Public Class Demo
{
public Demo()
{
var connection = new HubConnection("http://localhost:47315/")
{
CookieContainer = new CookieContainer()
};
connection.CookieContainer.Add(GetAuthCookie("user1", "pass"));
chatHubProxy = connection.CreateHubProxy("servicesSatatuseHub");
connection.Start().Wait();
}
private static System.Net.Cookie GetAuthCookie(string user, string pass)
{
//var http = WebRequest.Create("http://localhost:47315/module/account/login.aspx") as HttpWebRequest;
var http = WebRequest.Create("http://localhost:47315//module/account/login.aspx") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
//var postData = "UserName=" + user + "&Password=" + pass + "";
var postData = "UserName=" + user + "&Password=" + pass + "";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
System.Net.Cookie authCookie;
using (var response = http.GetResponse() as HttpWebResponse)
{
authCookie = response.Cookies[FormsAuthentication.FormsCookieName];//authCookie = null
}
httpResponse.Close();
return cookie;
}
}
Every thing is fine but Cookie is null on this code
authCookie = <p>response.Cookies[FormsAuthentication.FormsCookieName];//authCookie = null
Due to cookie null hubconnection is fail.
Thanks in advance

Related

Not receiving cookie suddenly for HttpWebRequest POST placed through Visual Studio C# code

There is a common framework in our company where we pass username, password, url and get the cookie back. It was working for me for a long time and suddenly it stopped working. My team mates are able to get the cookie successfully with no issues. Here is the common function that we use to get the cookie back. Please help me to complete the troubleshooting
public static CookieContainer GetAvidAuthCookies(string url, string userName, string password, bool allowAutoRedirect = false)
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
CookieContainer cookieContainer = new CookieContainer();
req = (HttpWebRequest) WebRequest.Create(url);
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.ContentType = "text/xml;charset=UTF-8"; //for SOAP
req.Timeout = 30000;
req.AllowAutoRedirect = allowAutoRedirect;
req.AllowWriteStreamBuffering = true;
req.Referer = url;
//req.Host = "api.avidxchange.net";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(userName + ":" + password));
var request = Common.GetMemoryStream("username=" + userName + "&password=" + password + "&submit=");
if (request != null)
{
req.ContentLength = request.Length;
Stream sw = req.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
request.Position = 0;
while ((bytesRead = request.Read(buffer, 0, buffer.Length)) != 0)
{
sw.Write(buffer, 0, bytesRead);
}
request.Flush();
request.Close();
sw.Flush();
sw.Close();
}
try
{
resp = (HttpWebResponse) req.GetResponse();
}
catch (WebException we)
{
resp = (HttpWebResponse) we.Response;
Debug.WriteLine("Response:" + we.InnerException + "\r\n" + resp.StatusCode + ":" +
new StreamReader(we.Response.GetResponseStream()).ReadToEnd());
var responseStream = we.Response.GetResponseStream();
if (responseStream != null) responseStream.Position = 0;
}
var rStream = resp.GetResponseStream();
var responseText = new StreamReader(rStream).ReadToEnd();
var t = resp.Cookies;
return cookieContainer;
}

Connect application to Jira rest api using Windows credentials

My application connects to Jira for data extraction. To do that, I used the following code:
public string RunQuery(JiraRessource resource, string project_id, int startAt, int maxResults, string method = "GET")
{
string url = string.Format(m_BaseUrl);
if (project_id != null)
{
string jql = "search?jql=project=" + project_id;
url = string.Format("{0}{1}", url, jql);
}
string jqr = "&startAt=" + startAt + "&maxResults=" + maxResults;
url = string.Format("{0}{1}", url, jqr);
Console.WriteLine(url);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
string base64Credentials = GetEncodedCredentials();
//string base64Credentials = WindowsIdentity.GetCurrent().Token.ToString();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
string result = string.Empty;
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
private string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", m_username, m_password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}
The user has to enter the username and the password to connect. I want to change that in order to connect directly using windows credentials. I have no idea on how to do that. Is it possible? If it is, how can I do that?
WebRequest class has a Credentials property. You can set it with a new NetworkCredential object. You can also set it to logged in windows user. Sample code;
request.Credentials = new NetworkCredential(user, pwd, domain);
or
request.Credentials = CredentialCache.DefaultNetworkCredentials;

Linked In API (auth token (oauth2)) c#.net

I wonder if someone can give me some pointers on using the linked in API. I thought I had it sussed but for some reason when trying to get the auth_token I just get http 400 Bad Request.
My code, simply is:
public string redirectUrl = URLTOREDIRECT;
public String apiKey = APIKEY;
public String apiSecret = APISECRET;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=apiKey&scope=rw_company_admin&state=DCEEFWF45453sdffef424&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl));
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code" + "&code=" + code + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + _consumerkey + "&client_secret=" + _consumerSecret;
// var postData = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}", code, HttpUtility.HtmlEncode(redirectUrl), apiKey, apiSecret);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
//This "application/x-www-form-urlencoded"; line is important
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = sign.Length;
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(sign);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
return responseReader.ReadToEnd().ToString() ;
}
The code is all in the same page for testing purposes and is the same page as the redirectUrl.
Really stumped, tried all variations.
First bit clearly works as I get directed to linked in to allow app. The second part getting the auth token fails.
After much head scratching, eureka moment - did not need to send the info in the request.
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
//byte[] byteArray = Encoding.UTF8.GetBytes(sign);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
return returnVal;
I'm Using this code and it's working fine..... C# code ASP.NET :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LI
{
public partial class WebForm3 : System.Web.UI.Page
{
public string redirectUrl = "http://localhost:64576/WebForm3";
public string TokenGlobe = "";
public String apiKey = "API_KEY";
public string retval = "";
public String apiSecret = "API_Secret";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void btnTwit_Click(object sender, EventArgs e)
{
var Address = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=" + apiKey + "&redirect_uri=http://localhost:64576/WebForm3&state=987654321&scope=w_share";
using (var webClient = new WebClient())
{
webClient.Headers.Add("x-li-format", "json");
}
Response.Redirect(Address);
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/oauth/v2/accessToken";
var sign1 = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUrl + "&client_id=" + apiKey + "&client_secret=" + apiSecret + "";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
HttpWebRequest webRequest = System.Net.WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Host = "www.linkedin.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
var stri = redirectUrl;
retval = returnVal.ToString();
var objects = JsonConvert.DeserializeObject<Accountdsdsd>(retval);//JArray.Parse(retval);
TokenGlobe = objects.access_token;
var SentStatus = PostLinkedInNetworkUpdate(TokenGlobe, "Hello API"); //Share
return TokenGlobe;
// return responseReader.ReadToEnd().ToString();
}
private string linkedinSharesEndPoint = "https://api.linkedin.com//v1/people/~/shares?oauth2_access_token={0}&format=json";
private const string defaultUrl = "http://localhost:64576/WebForm3";
private const string defaultImageUrl = "http://opusleads.com/opusing/technology/technology%20(1).jpg"; //Image To Post
public bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = defaultUrl, string submittedImageUrl = defaultImageUrl)
{
var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
var message = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new Dictionary<string, string>
{ { "title", title },
{ "submitted-url", submittedUrl },
{"submitted-image-url" , submittedImageUrl}
},
visibility = new
{
code = "anyone"
}
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response.ContainsKey("updateKey");
}
}
//Json Parsing
public class Accountdsdsd
{
public string access_token { get; set; }
public string expires_in { get; set; }
}
}

Pulling categories from store via BigCommerce restful API

I am tring to pull categories from my store on BigCommerce via API.
When I try my credentials at API Console;
https://developer.bigcommerce.com/console
it is working fine, but I when send credentials via C# post request it does not work.
I am receiving [{"status":401,"message":"No credentials were supplied in the request."}]
My code is like;
List<PostCredential> postCredentials = new List<PostCredential>();
postCredentials.Add(new PostCredential { name = "store_url", value = ApiPath });
postCredentials.Add(new PostCredential { name = "username", value = Username });
postCredentials.Add(new PostCredential { name = "api_key", value = ApiToken });
JavaScriptSerializer serializer = new JavaScriptSerializer();
string serialize = serializer.Serialize(postCredentials);
const string requestUrl = "https://myteststore1234.mybigcommerce.com/api/v2/categories.json";
StringBuilder postData = new StringBuilder();
postData.Append(serialize);
string postRequest = PostRequest(requestUrl, postData.ToString());
public static string PostRequest(string url, string postData)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
string responseString = new StreamReader(responseStream).ReadToEnd();
return responseString;
}
return null;
}
is there any workaround for this?
WebHeaderCollection wHeader = new WebHeaderCollection();
wHeader.Clear();
//wHeader.Add("username:test");
//wHeader.Add("password:4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b");
//wHeader.Add("u","test:4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b");
string Username = "test";
string ApiToken = "4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b";
string sUrl = "https://store-bwvr466.mybigcommerce.com/api/v2/brands.json"; //txtstoreurl.Text.ToString() + "/api/v2/products.json";
HttpWebRequest wRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(sUrl);
wRequest.Credentials = new NetworkCredential(Username, ApiToken);
wRequest.ContentType = "application/json"; //' I don't know what your content type is
//wRequest.Headers = wHeader;
wRequest.Method = "GET";
HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();
string sResponse = "";
using (StreamReader srRead = new StreamReader(wResponse.GetResponseStream()))
{
sResponse = srRead.ReadToEnd();
MessageBox.Show(sResponse);
}
After some research I found out I need to pass parameters like this;
httpWReq.Method = "GET";
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
httpWReq.Credentials = new NetworkCredential(Username, ApiToken);

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Categories