I have the SSL certificate for my example.com domain. I want to make a redirection if user wants to enter the site with www.example.com. The code below works fine, but I can't enter the site if I want to use https://www.example.com in the URL bar. Why ?
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.Host.StartsWith("www", StringComparison.InvariantCultureIgnoreCase))
{
Response.Clear();
Response.AddHeader("Location",
string.Format("{0}://{1}{2}", Request.Url.Scheme,
Request.Url.Host.Substring(4),
Request.Url.PathAndQuery)
);
Response.StatusCode = 301;
Response.End();
}
}
I guess that there is no binding on your web server that is listening for https://www.example.com. You only have a valid certificate for https://example.com. So when you attempt to request https://www.example.com IIS simply drops the connection.
Related
How can we achieve single signOn for windows authentication where my two applications which are available on internet are configured in iis for windows authentication. On requesting the url there is a popup of windows authentication, so I want there should not be popup for 2nd application if 1st is authenticated.
I have created two application SSO1 and SSO2 on SSO1 Login page I am writing code
protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "test" && txtPassword.Text == "test")
{
string guid = Guid.NewGuid().ToString();
Response.Cookies.Add(new HttpCookie("eNPSAuthToken", guid));
Response.Redirect("Default.aspx");
}
else
Response.Write("Invalid User");
}
On SSO2 application default page I am writing code to check the cookie if available redirect it to default page or else login page of SSO2 application.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["eNPSAuthToken"] == null)
{
Response.Redirect("Login.aspx");
}
}
I need to host both the application on IIS and enable windows authentication, So I will get login popup of windows authentication, I want to get popup only once, if user is authenticated then for 2nd application popup should not come.
I have a requirement to ensure all traffic on my website is redirected to HTTPS if it is requested over HTTP. When we deploy the site to appharbor, we use the custom RequireHttpsAttribute which works well for our MVC controllers.
However we also want to force any request for static files (images, stylesheets, javascript) via HTTP to be sent to HTTPS. Trying it using the web.config rewrite rules ends up in a redirect loop due to the load balancer sending https request to the web server as http.
Does anyone have any ideas on how to achieve this?
After receiving a reply from appharbor support, one of their suggestions was to implement code similar to the custom RequireHttpsAttribute for static files as well.
So I created a class called HttpRequestModule, and set it up to run for all requests (runAllManagedModulesForAllRequests set to true) I was able to force any direct requests to HTTP urls to redirect to HTTPS.
class HttpRequestModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(CheckHttpRequest);
}
private void CheckHttpRequest(object sender, EventArgs a)
{
if (app.Context.Request.IsSecureConnection) return;
if (app.Contact.Request.IsLocal) return;
if (string.Equals(app.Context.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var secureUrl = "https://" + app.Context.Request["HTTP_HOST"] + HttpContext.Current.Request.RawUrl;
app.Context.Response.Redirect(secureUrl);
}
}
i want to redirect my old address www.informarea.it/BlogEngine to new address www.informarea.it...
*my global.asax of blogengine.net is *
void Application_BeginRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
// Attempt to perform first request initialization
FirstRequestInitialization.Initialize(context);
}
*can i make to apply the code of redirect permanently? *
if (app.url.ToString().ToLower().Contains("http://www.informarea.it/BlogEngine"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location",url.Replace("http://www.informarea.it/blogengine", "http://www.informarea.it"));
}
Can Someone help me?
thank you very much
Fabry
This should redirect any query where the path starts with /BlogEngine to the same url with the /BlogEngine removed.
if(Request.Url.PathAndQuery.StartsWith("/BlogEngine", StringComparison.OrdinalIgnoreCase)) {
Response.RedirectPermanent(Request.Url.PathAndQuery.Substring(11), true);
}
Pros:
Gives a 301 Redirect like you requested
Keeps the rest of the path and query string intact for the following request
Cons:
Requires .net 4.0 (Version 2.7 of BlogEngine is targeted at 4.0 so I don't think this will be an issue.)
We have a WebBrowser embedded in our Windows Phone 7x application. This WebBrowser is pointed at our web servers. We need to be able to differentiate between a request coming from the app and a request coming from the native browser (or a WebBrowser embedded in another app, for instance). To do this we'd like to modify the User-Agent of all HTTP requests coming from said WebBrowser.
However, I can't find a way to do this. My initial thought was simply to override the Navigate functions adding "additionalHeaders." Unfortunately the WebBrowser class is sealed, so that option wasn't an option at all. I've searched high and low for a property or handler that's exposed that I might be able to take advantage of to no avail.
So, in short, is there a way to modify the User-Agent for a WebBrowser for all outbound HTTP requests?
I know this question is old, but in case this is of use to anyone, you could always use this for the WebBrowser's navigating event:
void wb_Navigating(object sender, NavigatingEventArgs e)
{
if (!e.Uri.ToString().Contains("!!!"))
{
e.Cancel = true;
string url = e.Uri.ToString();
if (url.Contains("?"))
url = url + "&!!!";
else
url = url + "?!!!";
wb.Navigate(new Uri(url), null, "User-Agent: " + "Your User Agent");
}
}
You just add "!!!" to all the urls for navigations that have your custom user agent. If the URL doesn't contain "!!!", it is a request from a clicked link and the WebBrowser cancels the navigation, and re-navigates with your custom user agent and "!!!" in the query string.
I tried a similar approach to msbg, where you store the URL in memory to avoid double checking it, and avoid modifying it with !!!. However, that approach doesn't preserve POST data, so it won't help me.
List<string> recentlyRequestedUrls = new List<string>();
void wb_Navigating(object sender, NavigatingEventArgs e)
{
if(!recentlyRequestedUrls.Contains(e.Uri.ToString()))
{
//new request, reinitiate it ourselves and save that we did to avoid infinite loop.
e.Cancel = true;
string url = e.Uri.ToString();
recentlyRequestedUrls.Add(url);
webBrowser1.Navigate(new Uri(url), null, "User-Agent: Your_User_Agent");
}
}
Set the user agent through additional headers, when invoking the Navigate method. Details here.
I have a scenario where I have to handle authentication of ajax requests using "Forms Authentication". Based on some search and help from my earlier stackoverflow post, I had decided to use the method described at here.
The idea is to send back a 401 response for unauthenticated requests, and then handle that in the AJAX error handler. So I have an AJAX error handler in my ASP.net MVC3 Layout page that redirects the browser to the login page when it receives 401 response on unauthenticated ajax requests. Here is the ajax error handler.
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == "401") {
window.location.replace(loginUrl);
}
....
});
This all works well on my local IIS 7.5 Server. But on the server where my site is hosted, unfortunately, I get a basic authentication popup on unauthenticated ajax requests (for example session timed out), before the AJAX error handler runs and redirects the browser to the login page. When I cancel the "Authentication Required" popup by pressing the Cancel button, the AJAX error handler then runs and I am redirected to the login page.
So, why does the browser show the authentication popup before running the AJAX error handler?
Edit: The Hosting Server is running IIS 6.
as Softlion said
This is a common question with an easy answer. the 401 is transformed into a 302 to the login >page by the .net authorization module. The browser never see the 401 only the 302.
if you are using .net 4 and later, you use code below
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
it work's fine for me.
This is a common question with an easy answer.
the 401 is transformed into a 302 to the login page by the .net authorization module. The browser never see the 401 only the 302.
Of course this is not playing nicely with ajax calls.
The best solution i tryed and i'm currently using involve writing a new attribute which is catching 401 and tranform it into ... 409 which is catched by the jquery ajax handler.
It is part of a paid product so i can not give any code.
Try to remove WWW-Authenticate header from response.
IIS 6 in integrated mode? I don't believe there is any such thing, unless you're talking about integrated authentication.
My guess is that you're using a non-aspx extension, so on IIS6 this means that it's not even hitting the .net process. So, IIS is using it's own 401 error response page.
Likely, the solution is to force all requests to be handled by the .net process.
Your host will have to go into IIS properties > configuration > wildcard mappings - and map everything to the .net process.
.net won't catch the 401 errors. What I did was to set the IIS error page from the default 401 page to my own static 401 page. From that page I used javascript to redirect to another handler.
The solution here is to write a custom HttpModule to workaround the MVC frameworks default behavior. Once I was finally able to register the module (cheers David Ebbo) it worked for me. You may want to choose your own criteria for calling SuppressAuthenticationRedirect.
public class SuppressFormsAuthenticationRedirectModule : IHttpModule {
private static readonly object SuppressAuthenticationKey = new Object();
public static void SuppressAuthenticationRedirect(HttpContext context) {
context.Items[SuppressAuthenticationKey] = true;
}
public static void SuppressAuthenticationRedirect(HttpContextBase context) {
context.Items[SuppressAuthenticationKey] = true;
}
public void Init(HttpApplication context) {
context.PostReleaseRequestState += OnPostReleaseRequestState;
context.EndRequest += OnEndRequest;
}
private void OnPostReleaseRequestState(object source, EventArgs args) {
var context = (HttpApplication)source;
var response = context.Response;
var request = context.Request;
if (response.StatusCode == 401 && request.Headers["X-Requested-With"] ==
"XMLHttpRequest") {
SuppressAuthenticationRedirect(context.Context);
}
}
private void OnEndRequest(object source, EventArgs args) {
var context = (HttpApplication)source;
var response = context.Response;
if (context.Context.Items.Contains(SuppressAuthenticationKey)) {
response.TrySkipIisCustomErrors = true;
response.ClearContent();
response.StatusCode = 401;
response.RedirectLocation = null;
}
}
public void Dispose() {
}
public static void Register() {
DynamicModuleUtility.RegisterModule(
typeof(SuppressFormsAuthenticationRedirectModule));
}
}
For me this ended up being simple. Most IIS web sites with anonymous authentication also have a default Windows Auth enabled
Turn off the Windows Authentication which is what pops up the login screen when the site detects the 401 even from an ajax call.
<security>
<authentication>
<anonymousAuthentication enabled="true" />
<windowsAuthentication enabled="false" />
</authentication>
</security>
Wait ! I thought you said Ajax request, how can you get a popup on ajax request ? I am pretty sure somewhere else you are triggering the call to the URL even before AJAX call. From your scenario its proved that when you cancel the popup, your actual ajax request is being made and hence you can do a ajax redirect.
The idea is to send back a 401 response for unauthenticated requests, and then handle that in the AJAX error handler
You can get an ajax response only if you send a ajax request, if you send normal http request then you will get a popup. This has nothing to do with .Net or Java :)