Amazon Ad

Saturday, 30 April 2016

How to generate dynamic URL from javascript.

Dear all,

I was given a task to generate dynamic url using javascript, After going through all the aspects I decided to work with history object available in javascript. Almost every modern browser today supports modern techniques used in html5. There are basically two methods, Apart from external plugins for url rewriting we can use these inbuilt javascript functions.

1. PushState as the name suggests pushes the history object in the history, just like stack push. It adds the object in the history object which is taken automatically by the browser. The first object is taken as the current object. For Instance,

window.history.pushState(null, response.pageTitle, '/developer/consturction/House');

Here, the statObj is an object which is the object taking the object value. Next parameter is page title and last parameter is urlPath is path which is displayed on the browser.
This is used in most of the cases when the url is to be created dynamically based on user action on the browser without page post back or reload. In the above example, When executed the URL of the browser will become, http(s)://yourdomain/developer/construction/House.

2 ReplaceState as the name suggests, it replaces the exising object with a new object. For example,

window.history.replaceState(stateObj,response.pageTitle,urlPath);

Here the parameters are the same except for the functionality.

Thanks
Ritesh

Friday, 8 April 2016

Authorize your WEB API to send data only to your website only

Hi,

I was wondering how we could implement security in web API, I wanted to send JSON data only to my desired website(s). Therefore, I decided to  create a custom Authorize Attribute in C# which will authorize any request and will help in implementing security for WEB API.

First we will create a class like below

public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        private string _responseReason = "";
        public bool ByPassAuthorization { get; set; }

        List<string> allowedWebsites = new List<string>();

        public ApiAuthorizeAttribute()
        {
            //List of authorized websites
            allowedWebsites.Add("localhost");
            allowedWebsites.Add("dev.test.com");
            allowedWebsites.Add("staging.test.com");          
            allowedWebsites.Add("new-test.test.com");
            allowedWebsites.Add("test.com");
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            if (!string.IsNullOrEmpty(_responseReason))
                actionContext.Response.ReasonPhrase = _responseReason;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
           
            //checking against our custom table goes here
            if (!this.IsValidRequest(actionContext))
            {
                this.HandleUnauthorizedRequest(actionContext);
                _responseReason = "Access Denied";
                return false;
            }

            return true;
            //return base.IsAuthorized(actionContext);
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //logic that will run before even authorizing the customer / user. if this logic fails
            // then the user checking against our custom database table will not processed.
            // you can skip this if you don't have such requirements and directly call
            base.OnAuthorization(actionContext);
          
        }

        public bool IsValidRequest(HttpActionContext actionContext)
        {

            //Check if a valid api page is requested
            /*var apiAttributes = GetApiAuthorizeAttributes(actionContext.ActionDescriptor);
            if (apiAttributes != null && apiAttributes.Any())
                return true;
            return false;*/
            string url = HttpContext.Current.Request.UrlReferrer.Host;
            bool isAllowed=allowedWebsites.Contains(url);
            return isAllowed;
        }
    }

Secondly, We have to implement it see how its done below
 
        [HttpGet]
        [ApiAuthorizeAttribute]
        [ActionName("GetData")]
        public List<DataMaster> GetData()
        {
             //your code goes here..
        }

------------------

In case of webforms we have to use global.asax file to achieve the same result. Create a function in global.asax for ex.

protected bool CheckRequest()
        {
            List<string> allowedWebsites = new List<string>();
            allowedWebsites.Add("test");
            allowedWebsites.Add("localhost");

            if (Request.Url != null)
            {
                string requestfrom = Request.Url.GetLeftPart(UriPartial.Authority);
                requestfrom = requestfrom.Substring(requestfrom.IndexOf('/') + 2);
                requestfrom = requestfrom.Substring(0,requestfrom.IndexOf(':'));

                bool isAllowed = allowedWebsites.Contains(requestfrom);
                return isAllowed;
            }
            else
            {
                return true;
            }
        }

Then in  Application_BeginRequest event in global .asax do this:

 protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (!CheckRequest())
            {
                Response.Write("<center><h1>A suspicious activity has been detected, Your IP has been recorded for further investigation.</h1></center>");
                Response.End();
            }
       }

Thats it!!
 

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...