Security Policies in JavaScript

Introduction

 
Downloading and running programs, that are written by unknown vendors, from the Internet can be dangerous. On the Internet, a program may seem beneficial, but while downloading it, some spyware or a virus might be installed on your system.
 
A JavaScript code provides access to documents or programs available in various websites. However, It follows the JavaScript security model that is based upon Java. According to this model, JavaScript uses a security policy that is a set of rules allowing you to perform different actions under different circumstances. 
 
Example
 
When you try to use the window.Close() method on the main browser window, a confirmation box appears prompting if you really want to allow the window to be closed. This situation is one of the aspects of the JavaScript security,
 
The following are the two security policies in JavaScript:
  1. Same-origin
  2. Singed-script
Let's try to understand both policies.
 

1. The Sign-Origin Policy

 
The primary JavaScript Security policy is the same-origin policy, also known as single-origin policy or the same-site policy. In this policy, when a script attempts to access the properties or methods of a Web page from some other Web page, then the browser performs the same-origin check on the URLs of the various Web pages. If the URL of the new Web page has the same origin as the previous Web page, then only the properties and methods can be accessed. If the URL of the new Web page does not have the same origin, then an error is thrown.
 
Two different Web Pages have the same origin if they are loaded from the same server by using the same protocol and port number.
 
Now, suppose that a script is loaded from http://ww.c-sharpcorner.com/index.jsp. the given URL shows the result of attempting:
  1. http://www.c-sharpcorner.com/defaultpage.jsp
     
    Result: Success
    Same domain and Protocol
     
  2. http://www.c-sharpcorner.com/chapter/info.jsp
     
    Result:
    Success
    Same domain and Protocol
     
  3. https://www..c-sharpcorner.com/sponsers.jsp
     
    Result: Failure
    Different Protocol (https)
      
  4. http://ww.c-sharpcorner.com/index.jsp
     
    Result: Failure
    Different Port (80)
       
  5. http://event.c-sharpcorner.com/index.jsp 
     
    Result: Success
    Different host(event)

2. The Signed-Script Policy

 
In the signed script policy, you create a named policy and apply it to a specific list of web sites. You can define a list of trusted sites to which you are willing to grant certain extended privileges.
 
Example
 
You can create a policy called the Internet and apply it to pages fetched from your corporate internet. If a user wants to access a site that is available in the list of trusted sites then the access is granted by the policy. If the user tries to access a site that is not available in the list of trusted sites then the access is not granted by the Policy.