Secure webApplication - asp.net

I am building an application(asp.net) with online payment so i want to make these payment page SSL enable. How can i do that..
Help me..
Thanks

Create class similar to
public class SecurePage : Page
{
protected override void OnInit( EventArgs e )
{
//retrieve appsettings value. set to false for localhost or dev environment
var sslRequired = bool.Parse(WebConfigurationManager.AppSettings["Security-SSL-Required"] ?? "true");
var currentUrl = System.Web.HttpContext.Current.Request.Url;
if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase) && sslRequired)
{
//build the secure uri
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
//use the default port.
secureUrlBuilder.Port = -1;
//redirect and end the response.
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
base.OnInit(e);
}
}
Then for pages that require SSL inherit from this base class:
public class Login : SecurePage
{
protected void Page_Load
(
object sender,
EventArgs e )
{
}
}

Related

HTTP module re-writing the URL with some encryption

I am writing one class with the help of HTTPModule to check userIdentity in session before he access any page.If the variable in the session is null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx", false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of encryption in URL for which my Breadcrumbs are not working in the page. The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu

How can I replace HTTPS with HTTP in a URL?

I need to use https on registration pages and http everywhere else. I wrote the following code in global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var currentUrl = System.Web.HttpContext.Current.Request.Url;
if (currentUrl.AbsoluteUri.Contains("Registration"))
{
if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
//build the secure uri
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
//use the default port.
secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
//redirect and end the response.
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
}
}
This is working fine for visiting registration pages, but the scheme doesn't switch back to http when I visit other pages.
Please add the following code in Global.asax Page.
protected void Application_BeginRequest(object sender, EventArgs e)
{
var currentUrl = System.Web.HttpContext.Current.Request.Url;
if (currentUrl.AbsoluteUri.Contains("Registration"))
{
if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
//build the secure uri
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
//use the default port.
secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
//redirect and end the response.
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
}
else if(currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttp;
secureUrlBuilder.Port = 80;
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
}

Find all textbox control in a page

i am trying to use http Module to disable textbox of each page. Here is my sample coding
public void context_OnPreRequestHandlerExecute(object sender, EventArgs args)
{
try
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
Page page = app.Context.Handler as Page;
if (page != null)
{
page.PreRender += OnPreRender;
page.PreLoad += onPreLoad;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
public void OnPreRender(object sender, EventArgs args)
{
Page page = sender as Page;
if (page.IsCrossPagePostBack)
{
DisableAllTextBoxes(page);
}
}
private static void DisableAllTextBoxes(Control parent)
{
foreach (Control c in parent.Controls)
{
var tb = c as Button;
if (tb != null)
{
tb.Enabled = false;
}
DisableAllTextBoxes(c);
}
}
This coding can work very well but when i use server.transer to another page. Button are not able to disable already.
For example webform1 transfer to webform2. Webform 1's button is able to disable but webform2 is not able to disable. Can anyone solve my problem?
Server.Transfer DOES NOT go through all http module pipline (thats why context_OnPreRequestHandlerExecute isn't executed for you )
you should try Server.TransferRequest or response.redirect or HttpContext.Current.RewritePath
Use LINQ to get all your textbox controls.
Don't use Server.Transfer()
Create an extension method on ControlCollection that returns an IEnumerable. That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
foreach (var t in textboxes)
{
t.Enabled = false;
}
...
public static class Extensions
{
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
}
Taken from this answer.

Set culture using cookie in asp.net, not updated

I'm using asp.net and want to make it possible for the user to set the culture to use in the website by himself. In MasterPage I have the following code to set a language cookie:
protected void Page_Load(object sender, EventArgs e) {
if (Request.QueryString["setLanguage"] != null)
{
HttpCookie languageCookie = new HttpCookie("language");
languageCookie.Value = Request.QueryString["setLanguage"];
languageCookie.Expires = DateTime.Now.AddDays(10);
Response.SetCookie(languageCookie);
}
}
In Global.asax I use the cookie like this:
protected void Application_BeginRequest(object sender, EventArgs e) {
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["language"];
if (languageCookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(language);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
}
}
The problem is that after I set the cookie with Response.SetCookie I need to reload the page to get the new language. How can I make my code so when the user set a new language the page is reloaded with the new language directly?
You can do
Response.Redirect(Request.PathAndQuery);
But why not just set the language after setting the Cookie? You can even use the BeginRequest event to check for specific input being posted and use it as an alternative condition for setting the language.
I had the same issue with the language being selected by the user. In order for it to work you have to do it on
protected override void InitializeCulture()
{
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["language"];
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(language);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
}
In order for it to work on every page of the site, I created a class that inherited from System.Web.UI.Page and implemented there
public class myBasePage : System.Web.UI.Page
{
protected override void InitializeCulture()
{
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["language"];
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(language);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
base.InitializeCulture();
}
}
from then on I had all my pages inherit from myBasePage.
This way, I used a Server (Postback) control to set the language and the page would get reloaded, and the language would be set.
If you are using Asp.Net MVC
//A foreigner, has possibly brew a cookie for me
public class SpeakNativeTongueAttribute : ActionFilterAttribute, IActionFilter
{
const string cookieName = "culture";
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
var cookieKeys = filterContext.RequestContext.HttpContext.Request.Cookies.AllKeys;
if (cookieKeys.Contains(cookieName))
{
//eat the cookie
var theCultureCookie = filterContext.RequestContext.HttpContext.Request.Cookies[cookieName];
var theCulture = theCultureCookie.Value;
//say thanks in native tongue
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(theCulture);
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(theCulture);
}
else
{
//Didn't receive a cookie, don't speak their language, those bastards!
}
}
}

load different css for site localization

I need to load different css file depending on the language that the user selects. I need to do this only in my master page.
If you are using the built-in themes and globalization support you could use a httpModule: (untested)
public class PageModule : IHttpModule
{
public void Dispose()
{
}
public void Init(System.Web.HttpApplication context)
{
context.PreRequestHandlerExecute += Application_PreRequestHandlerExecute;
}
public void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//Adds a handler that executes on every page request
HttpApplication application = default(HttpApplication);
application = (HttpApplication)sender;
Page page = application.Context.CurrentHandler as Page;
if ((page != null))
page.PreInit += Page_PreInit;
}
public void Page_PreInit(object sender, EventArgs e)
{
//If current context has no session then abort
if (HttpContext.Current.Session == null)
return;
//Get current page context
Page page = (Page)sender;
switch (page.Culture) {
case "en-US":
page.Theme = "en-USTheme";
break;
case "fr-FR":
page.Theme = "fr-FRTheme";
break;
default:
page.Theme = "DefaultTheme";
break;
}
}
}
you could write the selected language in a cookie. Then in you master page inspect the value saved in the cookie and assign the correct stylesheet.

Resources