I have the following attribute to make sure that the remote site page opens in https mode.
public class RemoteRequireHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentException("Filter Context");
}
if (filterContext != null && filterContext.HttpContext != null)
{
if (filterContext.HttpContext.Request.IsLocal)
{
return;
}
else
{
string val = ConfigurationManager.AppSettings["RequireSSL"].Trim();
bool requireSsl = bool.Parse(val);
if (!requireSsl)
{
return;
}
}
}
base.OnAuthorization(filterContext);
}
}
Local development now work normal since i don't want it to open in https mode.
Dev site opens the page in https mode - no issues here (single node).
Where as the production (load balanced - 2 nodes) site that i am currently setting up is giving me following error. Please note that dev and prod sites have the same setings and web.config
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
Dev site url is like
http://dev.datalab.something.org
Prod site url is like
http://datalab.something.org
And here is the call
[RemoteRequireHttps]
public ActionResult Index(string returnUrl, string error)
What am i missing here?
Update 1: My admin has confirmed that the SSL termination has been setup at the lad balancer evel. I have looked at the iis site setup and i don't see https bindings. I only see http binding. Does he need to setup https bindings as well?
Update 2: #AlexeiLevenkov pointed me to the right direction and this post had the code that I utilized and it is working. MOVED the code into a separate answer.
Your site is behind load balancer that does SSL termination - so as result all incoming traffic to your site is HTTP irrespective what user sees. This causes your code to always try to redirect to HTTPS version and hence infinite loop.
Options to fix:
Usually load balancer that does SSL termination will forward original IP/protocol via custom headers. x-forwarded-proto and x-forwarded-for are common ones to be used for this purpose. You may need to check with network admins if these headers used or some additional configuration is needed
Alternatively you can turn off SSL termination, but it will put additional load on your server.
One can also configure load balancer to talk to server with the same protocol as incoming request.
How to investigate such issue:
Look at http debugger (like Fiddler) to see if you are getting 30x redirects requests in a loop. If no redirects - likely code is wrong.
If you see repeated redirects it likely means site does not see actual request information - could be protocol, path cookies missing.
To continue investigation see what devices are between user and server (CDN, proxies, load balancer,...) - each have good chance to loose some date or transform protocols.
Not that I am against writing nice custom attributes, would it not make sense to perhaps perform the redirect in the web.config and use transformations available for the web.config to change the enabled value below from false to true for production deploys?
<rewrite>
<rules>
<rule name="SSL_ENABLED" enabled="false" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
Moving the fix into a separate answer as noted by #AlexeiLevenkov.
public class RemoteRequireHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentException("Filter Context");
}
if(filterContext.HttpContext != null)
{
if (filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
var currentUrl = filterContext.HttpContext.Request.Url;
if (currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
return;
}
if (string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if (filterContext.HttpContext.Request.IsLocal)
{
return;
}
var val = ConfigurationManager.AppSettings["RequireSSL"].Trim();
var requireSsl = bool.Parse(val);
if (!requireSsl)
{
return;
}
}
base.OnAuthorization(filterContext);
}
}
and i have updated the ExitHttps attribute as well. This was having the similar issues...
public class ExitHttpsAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentException("Filter Context");
}
if (filterContext.HttpContext == null)
{
return;
}
var isSecure = filterContext.HttpContext.Request.IsSecureConnection;
var currentUrl = filterContext.HttpContext.Request.Url;
if (!isSecure && currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
isSecure = true;
}
if (!isSecure && string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase))
{
isSecure = true;
}
if (isSecure)
{
//in these cases keep https
// abort if a [RequireHttps] attribute is applied to controller or action
if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof (RequireHttpsAttribute), true).Length > 0)
{
isSecure = false;
}
if (isSecure && filterContext.ActionDescriptor.GetCustomAttributes(typeof (RequireHttpsAttribute), true).Length > 0)
{
isSecure = false;
}
// abort if a [RetainHttps] attribute is applied to controller or action
if (isSecure && filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof (RetainHttpsAttribute), true).Length > 0)
{
isSecure = false;
}
if (isSecure && filterContext.ActionDescriptor.GetCustomAttributes(typeof (RetainHttpsAttribute), true).Length > 0)
{
isSecure = false;
}
// abort if it's not a GET request - we don't want to be redirecting on a form post
if (isSecure && !String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
isSecure = false;
}
}
if (!isSecure)
{
return;
}
// redirect to HTTP
var url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult(url);
}
}
Related
I wanted to implement this solution to handle antiforgery in ajax requests. I know there are other solutions but this is the one I like most.
The problem is I have to deal with System.Web.Webpages 1.0 so I cannot make use of AntiForgeryConfig.CookieName in my code.
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes
// to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
string cookieName = AntiForgeryData.GetAntiForgeryTokenName(context.Request.ApplicationPath);
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
else
{
new ValidateAntiForgeryTokenAttribute()
.OnAuthorization(filterContext);
}
}
}
How can I retrieve (programmatically) the cookie name set by the antiforgery system in Mvc3? I suspect the AntiForgery.Validate part will also be a problem but I'll handle that before. Any thoughts?
The actual cookie name always starts from "__RequestVerificationToken" with some suffix. So you can find the cookie like this:
private static string FindCookieValueByName(HttpRequestBase request)
{
return request.Cookies
.Cast<string>()
.Where(cn => cn.StartsWith("__RequestVerificationToken", StringComparison.OrdinalIgnoreCase))
.Select(cn => request.Cookies[cn].Value)
.FirstOrDefault();
}
As a continuation of this question, there's an issue I'm having with dotnetopenauth.
Basically, I'm wondering if the realm specified in the RP has to be the actual base URL of the application? That is, (http://localhost:1903)? Given the existing architecture in place it is difficult to remove the redirect - I tried setting the realm to the base OpenId controller (http://localhost:1903/OpenId) and testing manually did generate the XRDS document. However, the application seems to freeze, and the EP log reveals the following error:
2012-10-10 15:17:46,000 (GMT-4) [24] ERROR DotNetOpenAuth.OpenId - Attribute Exchange extension did not provide any aliases in the if_available or required lists.
Code:
Relying Party:
public ActionResult Authenticate(string RuserName = "")
{
UriBuilder returnToBuilder = new UriBuilder(Request.Url);
returnToBuilder.Path = "/OpenId/Authenticate";
returnToBuilder.Query = null;
returnToBuilder.Fragment = null;
Uri returnTo = returnToBuilder.Uri;
returnToBuilder.Path = "/";
Realm realm = returnToBuilder.Uri;
var response = openid.GetResponse();
if (response == null) {
if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) {
} else {
string strIdentifier = "http://localhost:3314/User/Identity/" + RuserName;
var request = openid.CreateRequest(
strIdentifier,
realm,
returnTo);
var fetchRequest = new FetchRequest();
request.AddExtension(fetchRequest);
request.RedirectToProvider();
}
} else {
switch (response.Status) {
case AuthenticationStatus.Canceled:
break;
case AuthenticationStatus.Failed:
break;
case AuthenticationStatus.Authenticated:
//log the user in
break;
}
}
return new EmptyResult();
}
Provider:
public ActionResult Index()
{
IRequest request = OpenIdProvider.GetRequest();
if (request != null) {
if (request.IsResponseReady) {
return OpenIdProvider.PrepareResponse(request).AsActionResult();
}
ProviderEndpoint.PendingRequest = (IHostProcessedRequest)request;
return this.ProcessAuthRequest();
} else {
//user stumbled on openid endpoint - 404 maybe?
return new EmptyResult();
}
}
public ActionResult ProcessAuthRequest()
{
if (ProviderEndpoint.PendingRequest == null) {
//there is no pending request
return new EmptyResult();
}
ActionResult response;
if (this.AutoRespondIfPossible(out response)) {
return response;
}
if (ProviderEndpoint.PendingRequest.Immediate) {
return this.SendAssertion();
}
return new EmptyResult();
}
The answer to your question is "no". The realm can be any URL between the base URL of your site and your return_to URL. So for example, if your return_to URL is http://localhost:1903/OpenId/Authenticate, the following are all valid realms:
http://localhost:1903/OpenId/Authenticate
http://localhost:1903/OpenId/
http://localhost:1903/
The following are not valid realms, given the return_to above:
http://localhost:1903/OpenId/Authenticate/ (extra trailing slash)
http://localhost:1903/openid/ (case sensitive!)
https://localhost:1903/ (scheme change)
Because some OpenID Providers such as Google issue pairwise unique identifiers for their users based on the exact realm URL, it's advisable for your realm to be the base URL to your web site so that it's most stable (redesigning your site won't change it). It's also strongly recommended that if it can be HTTPS that you make it HTTPS as that allows your return_to to be HTTPS and is slightly more secure that way (it mitigates DNS poisoning attacks).
The reason for the error in the log is because your RP creates and adds a FetchRequest extension to the OpenID authentication request, but you haven't initialized the FetchRequest with any actual attributes that you're requesting.
I couldn't tell you why your app freezes though, with the information you've provided.
I'm using the following sample code from the DotnetOpenAuth Samples (OpenId Controller in OpenIdProviderMvc)
public ActionResult ProcessAuthRequest() {
if (ProviderEndpoint.PendingRequest == null) {
return this.RedirectToAction("Index", "Home");
}
// Try responding immediately if possible.
ActionResult response;
if (this.AutoRespondIfPossible(out response)) {
return response;
}
// We can't respond immediately with a positive result. But if we still have to respond immediately...
if (ProviderEndpoint.PendingRequest.Immediate) {
// We can't stop to prompt the user -- we must just return a negative response.
return this.SendAssertion();
}
return this.RedirectToAction("AskUser");
}
private bool AutoRespondIfPossible(out ActionResult response)
{
if (ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverable(OpenIdProvider.Channel.WebRequestHandler) == RelyingPartyDiscoveryResult.Success
&& User.Identity.IsAuthenticated) {
if (ProviderEndpoint.PendingAuthenticationRequest != null) {
if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity
|| this.UserControlsIdentifier(ProviderEndpoint.PendingAuthenticationRequest)) {
ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
response = this.SendAssertion();
return true;
}
}
if (ProviderEndpoint.PendingAnonymousRequest != null) {
ProviderEndpoint.PendingAnonymousRequest.IsApproved = true;
response = this.SendAssertion();
return true;
}
}
response = null;
return false;
}
However, I don't want to ask the user anything. I'm trying to set up a web application portal that should automatically respond positively to the RP if the user is logged in (which he is). Yet AutoRespondIfPossible returns false, because ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverable returns false and I'm not sure why. What action should I be taking here?
Logs:
RP: http://pastebin.com/0EX2ZE1C
EP: http://pastebin.com/q5CPrWp6
Previous related questions:
SSO - No OpenID endpoint found
OpenIdProvider.GetRequest() returns null
Does an OpenID realm have to be the base URL of the web site?
IsReturnUrlDiscoverable performs what OpenID calls "RP Discovery". And it's important anyway, but particularly if you will be auto-logging users in, it's critical for security. The fact that it's returning false tells you the RP needs some work to do this correctly.
This blog post explains what the RP must do to pass "RP Discovery" tests.
Need some help with a Session timeout problem in an ASP.Net web app. Essentially the session expires about 10-15 seconds after login.
Side Note: I use a custom combo of FormsAuthentication and basic security
My Session.IsNewSession gets set to true after 3-4 good postbacks after login.
My Web.Config has the following...
<sessionState mode="InProc" timeout="130" regenerateExpiredSessionId="true" stateNetworkTimeout="120" compressionEnabled="true" cookieless="UseCookies" />
<authentication mode="Forms">
<forms timeout="120" ticketCompatibilityMode="Framework40" enableCrossAppRedirects="true" />
</authentication>
Where I believe the timeout refers to minutes....
I have an MVC 3 application with an ActionFilter registered
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyActionFilterAttribute());
}
Inside the OnActionExecuting I check for a Current Session to prevent access to controller actions which an unauthorized user shouldn't be able to access.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
Player player = SessionHelper.GetCurrentPlayer(filterContext.HttpContext.Session);
if (player == null && ctx != null)
{
player = SessionHelper.GetCurrentPlayer(ctx.Session);
}
if (player == null ||
(player.IsAdministrator == false && player.IsCoach == false && player.IsCommittee == false))
{
if (filterContext.Controller is HomeController || filterContext.Controller is AccountController)
{
base.OnActionExecuting(filterContext);
return;
}
string ctxError = ctx != null ? "Context Exists" : "Context Doesnt Exist";
string sessionError = filterContext.HttpContext.Session != null ? "filterContext.HttpContext.Session Exists" : "filterContext.HttpContext.Session Doesnt Exist";
string requestSessionError = filterContext.RequestContext.HttpContext.Session != null ? "filterContext.RequestContext.HttpContext.Session Exists" : "filterContext.RequestContext.HttpContext.Session Doesnt Exist";
throw new SecurityException(string.Format("Attempt to access {0} by user at {1} - {2} ({3}, {4}, {5})",
filterContext.HttpContext.Request.RawUrl,
filterContext.HttpContext.Request.UserHostAddress,
filterContext.HttpContext.Session,
ctxError,
sessionError,
requestSessionError));
}
base.OnActionExecuting(filterContext);
}
So I've determined that the Web Server was refreshing its AppPool faster than my session lifespan. This would result in the same SessionId to be used, but the IsNewSession flag to be set also.
As I have no control over the AppPool lifespan I was able to keep the session in the InProc mode in IIS.
I resolved the issue by moving Session State persistance to a hosted SqlServer database, thereby allowing the session to persist despite the AppPool being recycled.
I'd recommend the solution for any other person seeing their otherwise stable website losing their session state when hosted on a server which they do not have administrative access to.
Oh, and I found that IIS logs were pretty useless here. The best diagnosis logging here, I found, was my own manual logging to determine that this was the scenario.
I have a file upload in my site which is done using uploadify it uses a ashx page to upload file to database.It works fine in IE but in Mozilla the context.Session is getting null.I have also used IReadOnlySessionState to read session.
how can i get session in Mozilla like IE.
here is the ashx code i have done
public class Upload : IHttpHandler, IReadOnlySessionState
{
HttpContext context;
public void ProcessRequest(HttpContext context)
{
string UserID = context.Request["UserID"];
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
XmlDocument xDoc = new XmlDocument();
HttpPostedFile postedFile = context.Request.Files["Filedata"];
try
{
if (context.Session["User"] == null || context.Session["User"].ToString() == "")
{
context.Response.Write("SessionExpired");
context.Response.StatusCode = 200;
}
else
{
// does the uploading to database
}
}
}
}
In IE Context.Session["User"] always have the value but in Mozilla it is always null
You need to add sessionId to uploadify post params and restore ASP.NET_SessionId cookie on the server side on global.asax at OnBeginRequest. It is actually bug with flash and cookies.
I have created module for session and auth cookie restore, to get work flash and asp.net session, so i think it will be useful for your:
public class SwfUploadSupportModule : IHttpModule
{
public void Dispose()
{
// clean-up code here.
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(OnBeginRequest);
}
private void OnBeginRequest(object sender, EventArgs e)
{
var httpApplication = (HttpApplication)sender;
/* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SessionId";
if (httpApplication.Request.Form[session_param_name] != null)
{
UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.Form[session_param_name]);
}
else if (httpApplication.Request.QueryString[session_param_name] != null)
{
UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.QueryString[session_param_name]);
}
}
catch
{
}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (httpApplication.Request.Form[auth_param_name] != null)
{
UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.Form[auth_param_name]);
}
else if (httpApplication.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.QueryString[auth_param_name]);
}
}
catch
{
}
}
private void UpdateCookie(HttpApplication application, string cookie_name, string cookie_value)
{
var httpApplication = (HttpApplication)application;
HttpCookie cookie = httpApplication.Request.Cookies.Get(cookie_name);
if (null == cookie)
{
cookie = new HttpCookie(cookie_name);
}
cookie.Value = cookie_value;
httpApplication.Request.Cookies.Set(cookie);
}
}
Also than you need register above module at web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="SwfUploadSupportModule" type="namespace.SwfUploadSupportModule, application name" />
</modules>
</system.webServer>
Context.Session is null.. because connection to HttpHandler has another Context.Session
(debug and try: Context.Session.SessionId in where is the fileInput is different from Context.Session.SessionId in Upload.ashx)!
I suggest a workaround: pass a reference to the elements you need in the second session ( in my sample i pass the original SessionId using sessionId variable)
....
var sessionId = "<%=Context.Session.SessionID%>";
var theString = "other param,if needed";
$(document).ready(function () {
$('#fileInput').uploadify({
'uploader': '<%=ResolveUrl("~/uploadify/uploadify.swf")%>',
'script': '<%=ResolveUrl("~/Upload.ashx")%>',
'scriptData': { 'sessionId': sessionId, 'foo': theString },
'cancelImg': '<%=ResolveUrl("~/uploadify/cancel.png")%>',
....
and use this items in .ashx file.
public void ProcessRequest(HttpContext context)
{
try
{
HttpPostedFile file = context.Request.Files["Filedata"];
string sessionId = context.Request["sessionId"].ToString();
....
If you need to share complex elements use Context.Application instead of Context.Session, using original SessionID: Context.Application["SharedElement"+SessionID]
It's likely to be something failing to be set by the server or sent back on the client.
Step back to a lower level - use a network diagnostic tool such as Fiddler or Wireshark to examine the traffic being sent to/from your server and compare the differences between IE and Firefox.
Look at the headers to ensure that cookies and form values are being sent back to the server as expected.
I have created a function to check session have expired and then pass that as a parameter in script-data of uploadify and in ashx file i check that parameter to see whether session exists or not.if it returns session have expired then upload will not take place.It worked for me. Did not find any issues using that. hope that solve my issue
I had a similar problem with an .ashx file. The solution was that the handler has to implement IReadOnlySessionState (for read-only access) or IRequiresSessionState (for read-write access). eg:
public class SwfUploadSupportModule : IHttpHandler, IRequiresSessionState { ... }
These Interfaces do not need any additional code but act as markers for the framework.
Hope that this helps.
Jonathan