Amazon Ad

Friday 31 January 2020

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://developers.google.com/recaptcha/intro

Step 2: Use the below example code:

.ASPX

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Captchav3._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
        <h3>Login Form</h3>
        <asp:HiddenField ID="LoginId" runat="server" />
        Login:<asp:TextBox ID="txtLogin" runat="server"></asp:TextBox><br />
        Password:<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
        <script src="https://www.google.com/recaptcha/api.js?render=6Lc7ctQUXXXXXzgKdup36qsMS-y_Hc6JCwAn_Bd"></script>
        <script>
            grecaptcha.ready(function () {
                grecaptcha.execute('6Lc7ctQUXXXXXzgKdup36qsMS-y_Hc6JCwAn_Bd', { action: 'umslogin' }).then(function (token) {
                    document.getElementById('<%= LoginId.ClientID%>').value = token;
            });
        });
        </script>
</asp:Content>



C#

 public partial class _Default : Page
    {
        private static string Token = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            Token = LoginId.Value;
        }
        private static ResponseToken response = new ResponseToken();
      
        private string CaptchaVerify()
        {
            if (response.score == 0)
            {
                var responseString = RecaptchaVerify(Token);
                response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);

            }
            return JsonConvert.SerializeObject(response);
            //return "";
        }
        private static string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
        private static async Task<string> RecaptchaVerify(string recaptchaToken)
        {
            string url = apiAddress + "?secret=6Lc7ctQUXXXXXL--lngI_gIyRFyToplpKvZmMVlj&response=" + recaptchaToken;
            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    string responseString = httpClient.GetStringAsync(url).Result;
                    return responseString;
                    //dynamic json = JsonConvert.DeserializeObject(responseString);
                    //return json.success;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            dynamic o = JsonConvert.DeserializeObject(CaptchaVerify());
            if (o.Success.Value)
            {
                if (o.score.Value > 0.3)
                {
                    Response.Write("<h1>Valid Request</h1>");
                    if (txtLogin.Text == "admin" && txtPassword.Text == "admin")
                    {
                        Response.Write("Logged In Successfully");
                    }
                }
                else
                {
                    Response.Write("<h1>Not a Valid Request</h1>");
                    Response.StatusCode = 403;
                }
            }
            else
            {
                Response.Write("<h1>Not a Valid Request</h1>");
                Response.StatusCode = 403;
            }

        }
    }
    public class ResponseToken
    {

        public DateTime challenge_ts { get; set; }
        public float score { get; set; }
        public List<string> ErrorCodes { get; set; }
        public bool Success { get; set; }
        public string hostname { get; set; }
    }

Wednesday 29 January 2020

How to restrict IP address for your .NET Application using web.config

Sometimes we face a situation when a certain request is deliberately accessing our resources with consent. In this situation we can block on ip or domain to access our resources in asp.net.



First of all you need to make sure that your OS allows IP restriction, for this, you should do the following:

Windows Server 2012 or Windows Server 2012 R2

On the taskbar, click Server Manager.
In Server Manager, click the Manage menu, and then click Add Roles and Features.
In the Add Roles and Features wizard, click Next. Select the installation type and click Next. Select the destination server and click Next.
On the Server Roles page, expand Web Server (IIS), expand Web Server, expand Security, and then select IP and Domain Restrictions.

Click Next.
On the Select features page, click Next.
On the Confirm installation selections page, click Install.
On the Results page, click Close.

Windows 8 or Windows 8.1

On the Start screen, move the pointer all the way to the lower left corner, right-click the Start button, and then click Control Panel.
In Control Panel, click Programs and Features, and then click Turn Windows features on or off.
Expand Internet Information Services, expand World Wide Web Services, expand Security, and then select IP Security.
Click OK.
Click Close.


Step 1

Change ApplicationHost.config file to allow ipsecurity

You will need to edit the project specific version of the ApplicationHost.config file

<section name="ipSecurity" overrideModeDefault="Allow" />

Step 2

Add the following section in web.config

<system.webserver>
<security>
         <ipSecurity allowUnlisted="false">
            <add ipAddress="192.168.100.1" /><!-- block ip 192.168.100.1 -->
            <add ipAddress="169.254.0.0" subnetMask="255.255.0.0" /><!-- block ip 169.254.0.0 with subnet -->
         </ipSecurity>
      </security>
</system.webserver>

or

You can create an xml file for the blocked list

Create an xml file for instance RestrictedIP.xml as
<?xml version="1.0"?>
<ipSecurity allowUnlisted="false">
       <add ipAddress="xxx.xxx.xxx.xxx" /><!-- block ip xxx.xxx.xxx.xxx here xxx represents your ip number -->
       <add ipAddress="xxx.xxx.x.x" subnetMask="255.255.0.0" /><!-- block ip xxx.xxx.x.x with subnet -->
</ipSecurity>

In your web.config file you need to do the following

<system.webserver>
<security>
         <ipSecurity configSource="RestrictedIP.xml" />
</security>

Friday 3 January 2020

How to upload download files from google drive using API v3 in asp.net c#

Below is the code to upload and download files using Google drive API v3 in asp.net c#. Please check the official page for your reference,

the link is https://developers.google.com/drive/api/v3/quickstart/dotnet. Before you start you must enable Google drive api access for your account. The mentioned link has all the details regarding the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Services;
using System.Web.Script.Services;
using System.Security.Cryptography.X509Certificates;

namespace GoogleDriveAPIWorking
{
    public partial class _Default : Page
    {

        //Reference from https://developers.google.com/drive/api/v3/quickstart/dotnet

        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        //, DriveService.Scope.DriveFile
        static string[] Scopes = { DriveService.Scope.Drive,
                          DriveService.Scope.DriveAppdata,
                          DriveService.Scope.DriveFile,
                          DriveService.Scope.DriveMetadataReadonly,
                          DriveService.Scope.DriveReadonly,
                          DriveService.Scope.DriveScripts };
        static string ApplicationName = "Testing Google Drive API";
        static DriveService service;

        private void initGService()
        {
            try
            {
                UserCredential credential;
                using (var stream = new FileStream(Server.MapPath("~/credentials.json"), FileMode.Open, FileAccess.Read))
                {
                    // The file token.json stores the user's access and refresh tokens, and is created
                    // automatically when the authorization flow completes for the first time.
                    string credPath = Server.MapPath("token.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                         GoogleClientSecrets.Load(stream).Secrets,
                         Scopes,
                         "user",
                         CancellationToken.None,
                         new FileDataStore(credPath, true)).Result;

                    string s = "Credential file saved to: " + credPath;

                }

                // Create Drive API service.
                service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
            }
            catch (Exception ex)
            {

            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!Page.IsPostBack)
            {

                initGService();
            }
            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name, webContentLink)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            //Console.WriteLine("Files:");
            //fileList.InnerHtml = "Your Files:<br/>";
            if (files != null && files.Count > 0)
            {
                int i = 1;
                foreach (var file in files)
                {
                    //fileList.InnerHtml += "<div style='text-decoration:underline;font-color:blue' onclick='downloadfile(\"" + file.Id + "\");return

false;'>" + file.Name + "</a><br/>";
                    //Console.WriteLine("{0} ({1})", file.Name, file.Id);

                    LinkButton lb = new LinkButton();
                    lb.ID = "id" + i;
                    lb.Text = file.Name;
                    lb.CommandArgument = file.Id + "|" + file.WebContentLink;
                    lb.Command += new CommandEventHandler(DownloadFile);
                    Panel1.Controls.Add(lb);
                    Panel1.Controls.Add(new LiteralControl("<br />"));
                    i++;
                }
            }
            else
            {
                fileList.InnerHtml = "No files found.";
            }
            //Console.Read();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {


            byte[] by = fu.FileBytes;
            string filename = fu.FileName;
            string contentType = fu.PostedFile.ContentType;

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = filename
            };

            FilesResource.CreateMediaUpload request;
            //using (var stream = new System.IO.FileStream(Server.MapPath("files") + "/photo.jpg", System.IO.FileMode.Open))
            using (var stream = fu.FileContent)
            {
                request = service.Files.Create(fileMetadata, stream, contentType);
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;
            fileList.InnerHtml = "<br/><br/>" + "File ID: " + file.Id;

            //UploadFileToDrive(Server.MapPath("files") + "/photo.jpg");
            //Console.WriteLine("File ID: " + file.Id)
        }


        public void DownloadFile(object sender, EventArgs e)
        {

            LinkButton btn = (LinkButton)(sender);
            string[] arr = btn.CommandArgument.Split('|');
            string fileId = arr[0];
            string DownloadUrl = arr[1];

            string status = "";
            try
            {
                //create a folder "Downloaded" in your project, before running this code
                string saveTo = HttpContext.Current.Server.MapPath("Downloaded");
                var stream = new System.IO.MemoryStream();
                var request = service.Files.Get(fileId);

                Google.Apis.Drive.v3.Data.File file = request.Execute();
                string fname = file.Name;
                string fext = file.FileExtension;


                // Add a handler which will be notified on progress changes.
                // It will notify on each chunk download and when the
                // download is completed or failed.
                request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                        case Google.Apis.Download.DownloadStatus.Downloading:
                            {
                                downloadstatus.InnerHtml += "<br/>Downloaded : " + (progress.BytesDownloaded.ToString());
                                status = "Downloaded : " + (progress.BytesDownloaded.ToString());
                                break;
                            }
                        case Google.Apis.Download.DownloadStatus.Completed:
                            {
                                downloadstatus.InnerHtml += "<br/>Download complete.";
                                status = "Success";
                                SaveStream(stream, saveTo + "//" + fname);
                                downloadstatus.InnerHtml += "File Saved to location " + saveTo;
                                break;
                            }
                        case Google.Apis.Download.DownloadStatus.Failed:
                            {
                                downloadstatus.InnerHtml = "<br/>(Download failed.";
                                status = "Failed";
                                break;
                            }
                    }
                };
                request.Download(stream);

            }
            catch (Exception ex)
            {
                status = ex.ToString();
            }
        }

        //Save file from stream to local location
        private static void SaveStream(System.IO.MemoryStream stream, string saveTo)
        {
            using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                stream.WriteTo(file);
            }
        }
    }
}

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:...