+1-888-365-2779
Try Now
More in this section

Forums / Security / Access from a certain IP address

Access from a certain IP address

10 posts, 2 answered
  1. Godthaab
    Godthaab avatar
    22 posts
    Registered:
    06 Oct 2003
    11 Aug 2009
    Link to this post
    Is there anyone who has a bit of code that can validate a user from a specific IP address and provide access to the website. It should be used in conjunction with an Intranet. Our client does not want to use cookie only this simple validation.
  2. Nikolai
    Nikolai avatar
    216 posts
    Registered:
    21 Nov 2016
    12 Aug 2009
    Link to this post
    Hello Godthaab,


    You can create a custom module that checks the IP of the user. The module could redirect the user to appropriate error page.

    How to:

    1. Create new Class file in your application's App_Code folder.(IPValidationHttpModule in this expample)
    2. Use the copy/paste the following code inside:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
     
    /// <summary> 
    /// Summary description for IPValidationHttpModule 
    /// </summary> 
    public class IPValidationHttpModule : IHttpModule 
        #region IHttpModule Members 
     
        public void Dispose() 
        { 
        } 
     
        public void Init(HttpApplication context) 
        { 
            context.BeginRequest += new EventHandler(context_BeginRequest); 
        } 
     
        void context_BeginRequest(object sender, EventArgs e) 
        { 
            System.Web.HttpContext context = System.Web.HttpContext.Current; 
     
            if (!context.Request.Url.PathAndQuery.Contains("/NotTheIP.aspx")) 
            { 
                string userIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
             
                if (string.IsNullOrEmpty(userIp)) 
                { 
                    userIp = context.Request.ServerVariables["REMOTE_ADDR"]; 
                } 
                if (userIp != "111.111.111.111"
                { 
                    context.Response.Redirect("~/NotTheIP.aspx"); 
                } 
            } 
     
        #endregion 
     

    3. Create new aspx page called "NotTheIP" . This page will act as an error page.
    4. Open the web.config file and go to "<modules>" section
    5. Register the new module like this:
    <add name="ipvalid" type="IPValidationHttpModule,  App_Code"/> 

    Now each time a user request the home page his IP will be checked and if it is different than "111.111.111.111" he will be redirected to the "NotTheIP" error page.

    Hope this helps.

    Regards,
    Nikolai
    the Telerik team

    Instantly find answers to your questions on the newTelerik Support Portal.
    Check out the tipsfor optimizing your support resource searches.
    Answered
  3. Godthaab
    Godthaab avatar
    22 posts
    Registered:
    06 Oct 2003
    13 Aug 2009
    Link to this post
    Thank you Nikolai, it works perfectly! There is however a small error. 
    <add name="ipvalid" type="IPValidationHttpModule, App_Code"/> 
     must be in <httpModules> and not in the <modules>.

    In this project using VB myself and others might use the translation to VB:
    (If you use a translator who http://converter.telerik.com/ code will not work correctly)

    Imports Microsoft.VisualBasic
    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web

    ''' <summary> 
    ''' Summary description for IPValidationHttpModule 
    ''' </summary> 
    Public Class IPValidationHttpModule

        Implements IHttpModule

        Public Sub Dispose() Implements IHttpModule.Dispose

            ' Add code to clean up the
            ' instance variables of a module.

        End Sub

        Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
            AddHandler context.BeginRequest, AddressOf context_BeginRequest
        End Sub

        Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
            Dim context As System.Web.HttpContext = System.Web.HttpContext.Current

            If Not context.Request.Url.PathAndQuery.Contains("/NotTheIP.aspx") Then
                Dim userIp As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")

                If String.IsNullOrEmpty(userIp) Then
                    userIp = context.Request.ServerVariables("REMOTE_ADDR")
                End If
                ' if (userIp != "")
                If userIp <> "111.111.111.111" Then
                    context.Response.Redirect("~/NotTheIP.aspx")
                End If

            End If
        End Sub

    End Class
  4. Godthaab
    Godthaab avatar
    22 posts
    Registered:
    06 Oct 2003
    14 Aug 2009
    Link to this post
    I am unfortunately forced to use the Login module. I forgot an employee also must be able to log on from home or from a customer.

    I have tried me with two methods:
    ...
     if (strClientIP == "87.239.65.x" | strClientIP == "94.101.209.x")
            {
                Authenticated = true;
                Response.Redirect("~/Homepage.aspx");

            }
     ...
     I am logged in, but will be sent to ~/sitefinity/login.aspx?ReturnUrl=%2fHomepage.aspx
     Authenticated = true; is not enough for a full validation.
     
     The second method:
             if (strClientIP == "87.239.65.x" | strClientIP == "94.101.209.x")
            {
                Login1.UserName = "User"
                Login1.Password = "Password"    

            }
            
    The problem here is that Login1.Password is "Readonly" and I can not see that it can be changed.

    I will be very happy if you have a solution to the problem?

    (
    In my client's old solution I used this simple old fashion Xlt Script :-)
    ...
    <xsl:choose>
          <xsl:when test="$IPadresse='93.101.209.x'">
            <strong>Velkommen Infonet!</strong><br/>
    <form action="composite-56.htm" name="frmLogin" onsubmit="var strErrors=''; if (this.username.value=='') strErrors += '- Brugernavn\n'; if (this.password.value=='') strErrors += '- Kodeord\n'; if (strErrors) alert('Du mangler at udfylde nogle felter.\n\nUdfyld venligst:\n' + strErrors + '\nog tryk Send.\n\n'); return (strErrors == '');" method="post">
              <p>
                <input size="20" type="hidden" name="username" value="user@company.dk" />
              </p>
              <p>
                <input type="hidden" size="20" name="password" value="Password" />
              </p>
              <p align="left">
                <input type="submit" value="Login" size="20" />
              </p>
              <input type="hidden" name="login" value="LoginSetCookies" />   
    </form>
    </xsl:when>
    ....
    The only thing the user must do is to click on submit.
    )

  5. Nikolai
    Nikolai avatar
    216 posts
    Registered:
    21 Nov 2016
    17 Aug 2009
    Link to this post
    Hello Godthaab,

    Try changing the if statement as below:

    if (strClientIP.StartsWith("87.239.65.") || strClientIP.StartsWith("94.101.209.")) 
            { 
                Authenticated = true
                Response.Redirect("~/Homepage.aspx"); 
     
            } 

    Regards,
    Nikolai
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  6. Godthaab
    Godthaab avatar
    22 posts
    Registered:
    06 Oct 2003
    17 Aug 2009
    Link to this post
    Hi Nikolai, thanks for your reply. 
    As I wrote was I to Method 1. logged in, but the problem is that it apparently is not enough, because I will be sent to /sitefinity/login.aspx? ReturnUrl =% 2fhomepage.aspx.
    Although Authenticated = true;! 

    Sitefinity may need UserID as username or something else... ?

    Metod 1:
    if (strClientIP.StartsWith("192.168.1."))
            {
                Authenticated = true;
                Response.Redirect("~/Homepage.aspx");

            }
                    else
            {
                Authenticated = false;
                Response.Redirect("~/ByeBye.aspx");
            }
            
  7. Nikolai
    Nikolai avatar
    216 posts
    Registered:
    21 Nov 2016
    17 Aug 2009
    Link to this post
    Hi Godthaab,

    I made some modifications to the IPValidationHttpModule. Now if the user's IP is correct, the FormsAuthentication cookie is set.
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Security; 
    using Telerik.Security.Data; 
    using Telerik.Security; 
     
    /// <summary> 
    /// Summary description for IPValidationHttpModule 
    /// </summary> 
    public class IPValidationHttpModule : IHttpModule 
        #region IHttpModule Members 
     
        public void Dispose() 
        { 
        } 
     
        public void Init(HttpApplication context) 
        { 
            context.BeginRequest += new EventHandler(context_BeginRequest); 
        } 
     
        void context_BeginRequest(object sender, EventArgs e) 
        { 
            System.Web.HttpContext context = System.Web.HttpContext.Current; 
     
            if (!context.Request.Url.PathAndQuery.Contains("/NotTheIP.aspx")) 
            { 
                string userIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
             
                if (string.IsNullOrEmpty(userIp)) 
                { 
                    userIp = context.Request.ServerVariables["REMOTE_ADDR"]; 
                     
                } 
                if (userIp != "111.111.111.111"
                { 
                    context.Response.Redirect("~/NotTheIP.aspx"); 
                     
                } 
                else 
                { 
                    var userManager = new Telerik.Security.UserManager(); 
                    FormsAuthentication.SetAuthCookie("admin"true); 
                    var aCookie = FormsAuthentication.GetAuthCookie("admin"true); 
                    UserManager.Default.SetAuthenticationCookie(aCookie); 
                } 
            } 
     
        #endregion 
     



    Sincerely yours,
    the Telerik team

    Instantly find answers to your questions on the newTelerik Support Portal. 
    Answered
  8. Godthaab
    Godthaab avatar
    22 posts
    Registered:
    06 Oct 2003
    17 Aug 2009
    Link to this post
    Thank you Nicolai! 
    However, I have put the new bit of code in the "Method" 1 
    Because if it is as App_Code\IPValidationHttpModule.cs, all have the same rights. The 300 employees may not have such as "Admin" rights ☺.
    By placing code in a UserControl can "SuperUser" and "Admin" log on individually.

    Thanks again for your great help!
  9. Nikolai
    Nikolai avatar
    216 posts
    Registered:
    21 Nov 2016
    17 Aug 2009
    Link to this post
    Hello Godthaab,

    You can set the cookie like this:
    var userManager = new Telerik.Security.UserManager(); 
    FormsAuthentication.SetAuthCookie("manager"true); 
    var aCookie = FormsAuthentication.GetAuthCookie("manager"true); 
    UserManager.Default.SetAuthenticationCookie(aCookie); 
    and this way the user called manager will log in.

    Basically the whole IP approach will require that you keep track of all IP and then based on the IP you should return the correct user name.
    I am not sure that putting this in a user control will work correctly though - you can try it.

    Greetings,
    Nikolai
    the Telerik team

    Instantly find answers to your questions on the newTelerik Support Portal.
    Check out the tipsfor optimizing your support resource searches.
  10. Godthaab
    Godthaab avatar
    22 posts
    Registered:
    06 Oct 2003
    18 Aug 2009
    Link to this post
    Hey Nikolai 
    I have tested the following and I think it works as intended. 
    Others who have a Intra-/extranet might benefit from the code. 
    All code:

    Create Access.aspx to be "Homepage". Insert UserControl Access.ascx on the page and that's it.

    Access.ascx:
    -----------
    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Access.ascx.cs" Inherits="_access" %>
    -----------

    Access.ascx.cs:
    ---------------
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Telerik.Cms.Web.UI;
    using System.ComponentModel;
    using System.Web.Security;
    using Telerik.Security.Data;
    using Telerik.Security;

    public partial class _access : UserControl
    {
        void Page_Load(object sender, EventArgs e)
        {
            string strClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (strClientIP == null)
            {
                strClientIP = Request.ServerVariables["REMOTE_ADDR"];
            }

            if (strClientIP.StartsWith("192.168.1."))
            {
                var userManager = new Telerik.Security.UserManager();
                FormsAuthentication.SetAuthCookie("User@compagni.dk", true);
                var aCookie = FormsAuthentication.GetAuthCookie("User@compagni.dk", true);
                UserManager.Default.SetAuthenticationCookie(aCookie);
                Response.Redirect("~/homepage.aspx");
            }
            else
            {
                Response.Redirect("~/NoAccess.aspx");
            }
        }
    }

    ---------------
Register for webinar
10 posts, 2 answered