ASP.Net MVC Cookies in Console App - asp.net-mvc

I'm trying to create an ASP.Net MVC endpoint to authenticate externally. The idea is so that I can call the endpoint from a console app, WPF app or whatever, and use the MVC pattern for my service, returning JSON to authenticated users, checking authentication via the attribute etc. I'm using a console app for now just because it's quick and simple.
I have this so far:
In my console app:
Public Sub MakeLoginRequest()
Dim address As Uri = New Uri("http://localhost:50536/Account/LogIn")
Dim request As HttpWebRequest = HttpWebRequest.Create(address)
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim loginModel As New LogOnModel With {.UserName = "Richard",
.Password = "Password1",
.RememberMe = False}
Dim jsonData As String = JsonConvert.SerializeObject(loginModel)
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(jsonData)
request.GetRequestStream.Write(bytes, 0, bytes.Count)
Dim response As HttpWebResponse = request.GetResponse()
End Sub
In my controller:
<HttpPost()>
Public Function LogIn(model As LogOnModel) As ActionResult
If ModelState.IsValid Then
If Membership.ValidateUser(model.UserName, model.Password) Then
Dim cookie As HttpCookie = FormsAuthentication.GetAuthCookie(model.UserName, False)
cookie.Expires = DateTime.Now.AddMinutes(20)
Request.Cookies.Add(cookie)
Request.Cookies.Add(New HttpCookie("Barney", "Rubble"))
Return Content("Logged In Ok")
Else
Return New HttpUnauthorizedResult
End If
Else
Return New HttpUnauthorizedResult
End If
End Function
Now when I inspect the response in the console app, there are never any cookies - neither the real Auth cookie, nor my bogus Barney Rubble cookie actually appear!
However... I make the same call in Chrome and inspect the response... and both cookies are there!
Anyone any ideas as to what's going wrong?

You need to set a CookieContainer on your request as described here:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx

Related

Session value is not getting after payment completion

I am using paytabs(a payment gateway like paypal) in my mvc project.In that
when when I call create-paypage-api-call it will go to paytab website and complete
the payment section and will return back to my page.
return back url is an action method in same controller and that url i have to pass as a parameter when calling create-paypage-api-call.
before calling it I am saving customerID in session. But I am not able to get the session
value in the retrurnpage.
Here is my code
This is my payment gateway calling actionresult
public ActionResult paymentcall()
{
//my logic part here let it be int customerid = 123
session[id] = customerid;
//create-paypage-api-call starts here
request = (HttpWebRequest)WebRequest.Create("https://www.paytabs.com/apiv2/create_pay_page");
request.Method = "POST";
formContent = "merchant_email=bb#gmail.com&amount=333"// formcontent will contain some more parameters that i wont mention here
formContent += "&return_url=" + "http://example.com/mycontroller/TheReturnPage"; // this is the returnpage after payment
byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = HttpUtility.UrlDecode(reader.ReadToEnd());
PTResp = new PromoPayTabsMakePaymentResponse();
PTResp = JsonConvert.DeserializeObject<PromoPayTabsMakePaymentResponse>(responseFromServer);
System.Web.HttpContext.Current.Response.Redirect(PTResp.payment_url);
}
when call this it will go to the paytabs website and complete the payment there like entering
card details cvv . after payment it is successfully returning back to TheReturnPage actionmethod
public ActionResult TheReturnPage()
{
int aa = Convert.ToInt32(Session["id"]);
}
but in returnpage i am getting session value zero.
I tride redirecting from paymentcall action just after creating session. At that time it is getting.Session value is is not getting when it goes to paytabs page and returning back from there.
(paytabs page is https and my website is http. I dont know whether this info is needed. Just mentioning)
I am guessing because you redirect to paytabs and when it return page back to you, it is not the same session as the one you had with your customer (because it is from paytabs to you now)
The only thing I can think of is put a transaction id or something which you can identify on the return url, such that:
formContent += "&return_url=" + "http://example.com/mycontroller/TheReturnPage?id=" + someId
then use that someId to retrieve customer info from a database or some external storage.

Forms Authentication Cookie Missing in HttpWebResponse

I am sending a post request from an ASP.NET MVC 2.0 Controller to another site on the same domain using HttpWebRequest. I am sending username and password to logon to the site. That site uses forms authentication. So it sets authentication cookie. But when I get response in HttpWebResponse object, I find cookie neither in cookie container nor inside header (no Cookie or Set-Cookie header found). Let me add some code snippet here used in the MVC controller:
HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = postData.Length;
if (httpRequest.CookieContainer == null)
{
//httpRequest.CookieContainer = new CookieContainer();
}
httpRequest.Headers.Add(HttpRequestHeader.Cookie, "a=b");
var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(postData);
streamWriter.Close();
HttpWebResponse httpResponse = (HttpWebResponse) httpRequest.GetResponse();
string postBody = "";
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream()))
{
postBody = reader.ReadToEnd();
}
return this.Content(postBody);
Please note that I am not using cookie container and cookie header at the same time in HttpWebRequest.
I don't understand what I am missing here to get authentication cookie in web response.
Try to use
request.CookieContainer.Add(new Cookie("a", "b"));
instead of adding cookie as a header.

Storing Value in HttpCookie

Using MVC.
Function Login(ByVal token As String) As ActionResult
Using client As New WebClient
Try
Dim jsonResponse As String = client.DownloadString(URL & "/Getuser&token=" & token)
Dim obj As UserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(Of UserInfo)(jsonResponse)
Response.Cookies.Add(New HttpCookie("token", token))
Response.Cookies.Add(New HttpCookie("user_id", obj.id))
Return Json(obj)
Catch ex As WebException
Return Content("ERROR")
Catch ex As Exception
Return Content("ERROR")
End Try
End Using
End Function
I am sending a token to this function.
Then Using this token to get the User Info from a certain API
Then Storing this token in a HttpCookie
All this has been working fine for almost a month,
Until it stopped working.
When I debugged, token had a value, and it stored it in the HttpCookie, but when I called Request.Cookies("token").Value it returned ''
Any help would be appreciated.
I did a trace on the Token..
I am writing the parameter "token" in a file before storing it in the cookie.
then I am writing the cookie Request.Cookies("token").Value in a file,
Function Login(ByVal token As String) As ActionResult
WriteToFile("TOKEN RECEIVED = ", token)
Using client As New WebClient
Try
Dim jsonResponse As String = client.DownloadString(URL & "/Getuser&token=" & token)
Dim obj As UserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(Of UserInfo)(jsonResponse)
Response.Cookies.Add(New HttpCookie("token", token))
Response.Cookies.Add(New HttpCookie("user_id", obj.id))
WriteToFile("TOKEN COOKIE = ", Request.Cookies("token").Value)
Return Json(obj)
Catch ex As WebException
Return Content("ERROR")
Catch ex As Exception
Return Content("ERROR")
End Try
End Using
End Function
it returns the following:
TOKEN RECEIVED = X132WEeRT3AASDV
TOKEN COOKIE =
When I try to write both Request and Response Cookies:
WriteToFile("TOKEN COOKIE = ", Request.Cookies("token").Value)
WriteToFile("TOKEN COOKIE = ", Response.Cookies("token").Value)
Request.Cookies("token").Value Returns Empty String
Response.Cookies("token").Value Returns Actual Value
Maybe your cookie just expire after one month? When using cookies don't forget to set expiration date, and check web browser settings (example: if you are using "tor browser bundle" this can be an issue).
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
https://msdn.microsoft.com/en-us/library/78c837bd%28v=vs.140%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Make sure you access the cookies only during the actual Http request. Maybe you have changed the way (or place where) you call this function.
This is an old question on SO but for those interested, .NET team has created a new method to properly handle cookies.
This is available in .NET 4.7.1 and not earlier versions:
See under the section ASP.NET HttpCookie parsing here
https://blogs.msdn.microsoft.com/dotnet/2017/09/13/net-framework-4-7-1-asp-net-and-configuration-features/

MVC 4 Forms authentication strange behavior

I am using Asp.Net with MVC 4 to build a web application. For authentication, I am using forms authentication. The login page is set correctly and login behaves properly. However, instead of using the default partial login view I am using my own and I use AJAX to log in.
The login controller works fine and here is the code for login.
Here is my code in login action. Here resp is my custom response object
resp.Status = true;
// sometimes used to persist user roles
string userData = "some user data";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
login.username, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
false, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
//Response.Cookies.Add(cookie);
Response.SetCookie(cookie);
return Json(resp);
Here is the code of cshtml page to handle this script response
function (respData) {
if (respData.Status) {
window.location.href = "/";
}
if (!respData.Status) {
if (respData.Errors[0].ErrorCode == 1) {
$('#invalid').show();
$('#username').val('');
$('#password').val('');
}
else if (respData.Errors[0].ErrorCode == -1) {
var msg = respData.Errors[0].ErrorDescription;
$('#error_email').text(msg);
}
else {
var msg = respData.Errors[0].ErrorDescription;
$('#error_pwd').text(msg);
}
}
$("#dialog").dialog("close");
},
Everything works fine and the user is successfully redirected to home page on successful login. Also gets a proper message on failure.
The problem is, when I browse any other page after this successful redirection, the subsequent requests are not authenticated.
I did a little bit research and found that the browser is not sending the forms authentication cookie in the subsequent requests and hence those requests are not authenticated.
Any idea on this behavior ? , Am I missing something ?
Try explicitly setting the expiry time on your cookie with:
Cookie.Expires(DateTime.Now.AddMinutes(30));

Why GetResponseStream does not execute Cookies on server response on data GET from MVC Razor View?

I have a .net website on IIS that has an virtual directory pointing to MVC application. I am trying to reuse a sitemaster.master on the RAzor view header.
I have this code below on a Razor view _hearder_it.cshtml.
I am doing a StreamReader on test.aspx page which has a sitemaster.master only. The req.GetResponse does return the stream from the sitemaster(menu bar etc.). However the sitemaster.master has Request.Cookies and the cookies never have a value. I know they should have a value because I already test outside of the mvc application. The cookie changes the view of the sitemaster and that is the reason I need it.
//This code does returns the stream .
WebRequest req = HttpWebRequest.Create(url );
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
source = reader.ReadToEnd();
Response.Write(source); // I get HTML result back from my sitemaster.master.
Cookies are sent in request headers, while you don't add any cookies to your webrequest here. Here is a post that might help you
I added the cookie in the CookieContainer. This code is working successfully.
This code is in Razor view _header_it.cshtml:
#{
string userTyp3 = Request.Cookies["MY_USERTYPE"] != null ? Server.UrlDecode(Request.Cookies["MY_USERTYPE"].Value) : "";
CookieCollection _CookieCollection2 = new CookieCollection();
HttpWebRequest _request2 = (HttpWebRequest)WebRequest.Create("http://MySite_TEST/it/test.aspx");
_request2.Method = "GET";
_request2.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_request2.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)";
_request2.Referer = "http://MySite_TEST/it";
_request2.KeepAlive = true;
//Here is auth cookie, works fine
_request2.CookieContainer = _cookieContainer;
_request2.CookieContainer.Add(( new Cookie ( "MY_USERTYPE", userTyp3 , "/", "MySite_TEST") )) ;
_request2.Headers.Add(HttpRequestHeader.CacheControl, "no-cache=set-cookie");
HttpWebResponse _response2 = (HttpWebResponse)_request2.GetResponse();
StreamReader _reader2 = new StreamReader(_response2.GetResponseStream());
Response.Write(_reader2.ReadToEnd()); //
_response2.Close();
_reader2.Close();
}
I used the example on this URL:
http://stackoverflow.com/questions/2476092/login-website-curious-cookie-problem?rq=1]
Thank you

Resources