session, httphandler, java applet work together - asp.net

i have a aspx page see:
<%# Page Language="C#" %>
<%
HttpContext.Current.Session["UserID"] = "ABC1";
Response.Write(HttpContext.Current.Session["UserID"].ToString());
%>
<script>
var parameters = { OpenURL: "test.pdf", java_arguments: "-Xmx256m" };
var attributes = {archive:"webviewerS.jar,jPDFViewerS.jar", code:"qoppa.webViewer.PDFWebViewer", width:"100%", Height:"95%"};
var version = "1.6.0";
deployJava.runApplet(attributes, parameters, version);
</script>
The page load and created a session variable, and i also added a custom httphandler to handle the http request of pdf, every user type the path with .pdf will run the class
response.Cookies["UserID"].HttpOnly = false;
if (HttpContext.Current.Session["UserID"] != null)
{
response.ContentType = "application/pdf";
response.WriteFile(request.PhysicalPath);
}
else
{
response.Write("access denied");
}
The main objective of this script to test is it possible to view the pdf only by using the java applet within that aspx page. But finally,
var parameters = { OpenURL: "test.pdf", java_arguments: "-Xmx256m" };
the java applet request to load the pdf, but it seems the session could not be detected at httphandler, but the above code is successful if i directly type the .pdf path after i loaded the .aspx page.
If the applet request the pdf file, the result of the seesion["UserID"] will be null, why it can't detect the session value?

Have you tried using something like Fiddler or Charles to see the applet request going back from the browser to the server?
There will normally be a cookie called ASP.NET_SessionId or possibly a querystring parameter called sessionId to maintain the session depending on the server configuration.
From ASP.NET Session State Overview
By default, SessionID values are stored in a cookie. However, you can
also configure the application to store SessionID values in the URL
for a "cookieless" session.
The Java applet probably doesn't include this in the request and so the server thinks it's a different session.

Related

How to trigger HttpApplication.ReleaseRequestState Event

I'm working with cookies.
I want to delete my asp .net session cookies which are not pointing to the root directory as shown below.
I have updated the path of the cookie using the below piece of code:
public class CookieManager : SessionIDManager, ISessionIDManager
{
void ISessionIDManager.SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
{
base.SaveSessionID(context, id, out redirected, out cookieAdded);
if (cookieAdded)
{
SessionStateSection sessionStateSection = (System.Web.Configuration.SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
var cookie = context.Response.Cookies[sessionStateSection.CookieName];
cookie.Path = context.Request.ApplicationPath;
}
}
}
Web.config code :
<sessionState sessionIDManagerType="ANJU.Reports.WebUI.Library.CookieManager" timeout="30" cookieName="DVCookie"/>
I tried deleting this cookie, like how we delete the cookies which are pointing to the root directory but failed to do so.
Similar to ISessionIDManager.SaveSessionID, we also have ISessionIDManager.RemoveSessionID to remove the session cookies.
As per the microsoft document, mentioned in the below link:
https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.sessionidmanager.removesessionid?view=netframework-4.8
We can't directly call this method from our application code.
The SessionStateModule calls the RemoveSessionID method during the ReleaseRequestState event to remove the session identifier from the Cookies collection of the HttpResponse if a new session was created but was not used.
Can you please help me how to trigger this ReleaseRequestState event from my asp.net application?
Every piece of help is much appreciated.
Thank you all in advance.

Load a webpage that requires basic authentication in a Windows 8 App

How would you load an external site that requires basic authentication inside an iframe in a Windows 8 HTML/JavaScript app?
I've found that you can't use URLs of the form http://username:password#host/.
In order to load the URL I was trying to load, I had to use a webview or x-ms-webview and invoke it's navigateWithHttpRequestMessage function in order to pass the basic authentication header.
This resulted in the following code structure:
function ready(element, options) {
var webview = document.querySelector('[data-hook~="camera"]');
webview.navigateWithHttpRequestMessage(buildRequest());
}
function buildRequest() {
var username = 'username',
password = 'password',
Crypto = Windows.Security.Cryptography,
Http = Windows.Web.Http,
request,
buffer,
token;
request = new Http.HttpRequestMessage(
Http.HttpMethod.get,
new Windows.Foundation.Uri('http://ipcamera/'));
buffer = Crypto.CryptographicBuffer.convertStringToBinary(
[username, password].join(':'),
Crypto.BinaryStringEncoding.utf8);
token = Crypto.CryptographicBuffer.encodeToBase64String(buffer);
request.headers.authorization = new Http.Headers.HttpCredentialsHeaderValue('basic', token);
return request;
}
The caveat to this is that none of the DOM ready events seem to fire, so if you need to interact with the external site, you'll have to play with timers.

ASP.NET MVC5 - Server cannot modify cookies after HTTP headers have been sent

I've got an MVC Site that is giving an "Server cannot modify cookies after HTTP headers have been sent." error. It's happening in the _Layout.cshtml. At that line, there is a #Html.Action("_LightBoxes"), which calls a _LightBoxes partial view. The code for the _LightBoxes Partial View is simply:-
[ChildActionOnly]
public PartialViewResult _LightBoxes()
{
return PartialView();
}
I've read other threads with this error, but these all seem to be performing re-directs or similar, where as in this controller it simply returns an empty Partial View.
Does anyone have any suggestions for what is causing this? Could it be a reference inside that PartialView to another controller which is actually causing this error?
EDIT - 26 JANUARY 2015
I think this might be the issue. This is in a Partial View called from within the PartialView at that line. Code below, for a Facebook login button, which has cookies set to true.
<script type="text/javascript">
//Facebook Login Button
window.fbAsyncInit = function () {
FB.init({
appId: "#(System.Configuration.ConfigurationManager.AppSettings["facebook_appid"].ToString())", // App ID
//channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status: true, // check login status
cookie: false, // enable cookies to allow the server to access the session
oauth: true, // enable OAuth 2.0
xfbml: true // parse XFBML
});
$("fblogin").show();
};
(function (d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
//End Facebook
</script>
Thanks,
Mike.
This is often caused in MVC applications by inappropriate use of Response.Write() somewhere in your application (it doesn't need to even be in the code that is causing the problem). MVC is designed to render pages AFTER the controllers have finished processing, and it renders these to an output buffer and finally writes this to the response at the very end of the output.
If you have code somewhere in your pipeline that executes a Response.Write() and then after that you attempt to write a cookie, but before the view has actually been rendered you get this problem.
So search you code for Response.Write() that is not in a view.

Executing a webrequest without redirecting a page

I ran into a weird problem while using openid in asp.net. I wanted a server side logout for gmail account but without redirecting to another page.
I thought executing a web request would do that. This is my code
HttpWebRequest loHttp =
(HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/Logout");
// *** Set properties
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Sample Web Client";
// *** Retrieve request info headers
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(), enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
But it doesn't seem to work. The gmail account is still signed in.
Is it possible to execute a webrequest with such URL?
Thanks
I think that's because HttpWebRequest is made at the server level and you are logged in in the client.
You should use an iframe to load the URL

Why my httpwebrequest post to myhandler.ashx is rejected with status code 401

I've already written an HTTPHandler that gets POSTed from a ColdFusion page and it works successfully; now, I am trying to write a web application in ASP.NET so I can post a form to the .ashx handler from an .aspx page.
Application Trace (trace.axd) shows the following as my last 3 entries:
2 8/14/2009 1:53:56 PM /Default.aspx 200 GET View Details
3 8/14/2009 1:54:04 PM /Default.aspx 200 POST View Details
4 8/14/2009 1:54:13 PM /UploadHandler.ashx 401 POST View Details
I have a breakpoint in my .ashx file but it is never reached (I guess because of the 401 status code). Here is the snippet of code from the default.aspx trying to POST to the handler:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(BuildFormData());
string baseAddress = "http://" + Environment.MachineName;
string pathInfo = Page.ResolveUrl("UploadHandler.ashx");
string URI = baseAddress + pathInfo;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
Here is a snippet of code from the UploadHandler.ashx file (but this doesn't appear to be reached):
public void ProcessRequest(HttpContext context)
{
string returnURL = context.Request.ServerVariables["HTTP_REFERER"];
string message;
message = UploadFile(context);
StringBuilder msgReturn = new StringBuilder(returnURL);
msgReturn.Append("?n=");
msgReturn.Append(HttpUtility.UrlEncode(TRIMrecNumAssigned));
msgReturn.Append("&m=");
msgReturn.Append(HttpUtility.UrlEncode(message));
context.Response.Redirect(msgReturn.ToString());
}
Both default.aspx and UploadHandler.ashx are in the root of a virtual directory on my localhost; the directory security is currently set to "Anonymous access" CHECKED and "Integrated Windows authentication" CHECKED.
When I click the "View Details" link on the trace.axd display, I see all the data in the Forms collection that I expect to see and hope to process but this 401 seems to be stopping everything. I could post the code for my little function called BuildFormData() if useful.
EDIT: Revised handler as follows (has had no effect; same error occurs):
public void ProcessRequest(HttpContext context)
{
//-----------------------------------------------------------------------------------------
// the remainder of this block is alternative to the .Redirect and is useful for debugging.
context.Response.ContentType = "text/html";
//context.Response.Write(TRIMrecNumAssigned);
//context.Response.Write("<p>");
//context.Response.Write(msgReturn);
context.Response.Write("<H1>Trim - Kerberos Prototype for ColdFusion consuming pages</h1>");
HttpContext.Current.Trace.IsEnabled = true;
HttpContext.Current.Trace.Write(null);
HttpContext.Current.Trace.Write("-------");
HttpContext.Current.Trace.Write(context.Request.Form["txtTrimRecordType"]);
HttpContext.Current.Trace.Write(GetUserInfo());
HttpContext.Current.Trace.Write("-------");
HttpContext.Current.Trace.Write(null);
using (Html32TextWriter htw = new Html32TextWriter(context.Response.Output))
{
typeof(TraceContext)
.GetMethod("Render", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(HttpContext.Current.Trace, new object[] { htw });
}
}
Have you tried turning off Integrated Windows Auth and just leaving anonymous checked? Does it make a difference?
Your answer: "I think it made things worse because now I cannot even browse to default.aspx. I get this: HTTP 401.3 - Access denied by ACL on resource Internet Information Services"
My response: This is actually a good thing. This means we're getting closer to what is going on. If you're getting that error message and the only thing you have enabled is anonymous authentication via IIS, that means that the ASP.NET impersonation user doesn't have NTFS permissions on the files in question.
I'm not sure if you are on XP or Win 2k3, but now you want to check and make sure that either the ASPNET (XP) or Network Service (Win 2k3) users have at least read access on the files in question. Make sure that user has at least that level of access and then let me know how it goes.
Update: I don't know why I didn't think of this before. You may need to set credentials on your HttpWebRequest. To use the credentials of the current user, try adding this to your request.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
myRequest.Credentials = CredentialCache.DefaultCredentials;
If you need to add different credentials you can try Network Credentials
There's a good explanation of credentials here.
Hope this helps.
Looking at your ProcessRequest(), you do the following:
string returnURL = context.Request.ServerVariables["HTTP_REFERER"];
Based on how you are calling it with HttpWebRequest, this variable will be null. Then when you create your msgReturn, it will look something like this:
?n=XXX%m=YYY
When you redirect to this URL, it will probably not be found which is what is returning the 401.

Resources