Simple Single Page / Single User Forms Authentication without DB – C#

simple-loginOn smaller projects, maybe for internal usage, you want to protect a page with a username and password. Below is an easy way you can protect a page (or pages / folders) using a user and pass (kept in the web.config for easy access). This method uses forms authentication but doesn’t require a database or other source for user details since a single user is just stored in the web.config.

You’ll basically need to.

  1. Create a login page (simple .aspx page)
  2. Modify your web.config

 

Let’s start with your web.config. Below are the areas you’ll want to add: Continue reading “Simple Single Page / Single User Forms Authentication without DB – C#”

Simple Single Page / Single User Forms Authentication without DB – C#

Adding a forgot password / reset function to MVC c#

If you’re using any of the out-of-the-box mvc template projects (Visual Studio 2012 / c#), they do a great job with including functionality for user membership including log in, register and change password. However it does seem to be missing a ‘forgot password’ or ‘reset password’ function. Below is how you can quickly add this functionality by modifying the existing controllers and views:

1. Add a new view (I’m calling mine ResetPass) under the Views > Account folder:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ledme2.Models.LoginModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Reset Pass
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <hgroup class="title">
        <h1>Reset Your Password</h1>
    </hgroup>

    <section id="loginForm">
        <h2>Enter the username you wish to reset. An email will be sent with your password and the new password will expire in 3 hours.</h2>
        <% using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
           { %>
        <%: Html.AntiForgeryToken() %>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Enter the username you wish to reset. An email will be sent with your password and the new password will expire in 3 hours.</legend>
            <ol>
                <li>
                    <%: Html.LabelFor(m => m.UserName) %>
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </li>
            </ol>
            <input type="submit" value="Reset" />
        </fieldset>

        <% } %>

        <% if (ViewData["msg"] != null)
           { %>
        <%: ViewData["msg"] %>
        <% } %>
    </section>
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>

<asp:Content ID="Content4" ContentPlaceHolderID="ScriptsSection" runat="server">
</asp:Content>

2. Add these two methods to the AccountController.cs (I’ve left out the code w/ the email function, feel free to add your own):

 [AllowAnonymous]
        public ActionResult ResetPass(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPass(LoginModel model, string returnUrl)
        {
            if (WebSecurity.UserExists(model.UserName))
            {
                string ptoken = WebSecurity.GeneratePasswordResetToken(model.UserName, 190);
                //change to be as secure as you choose
                string tmpPass = Membership.GeneratePassword(10, 4);
                WebSecurity.ResetPassword(ptoken, tmpPass);
                //add your own email logic here
                ViewData["msg"] = "Your new password is: " + tmpPass;
                return View(model);
            }
            else
            {
                ModelState.AddModelError("", "The user name wasn't found.");
            }

            return View(model);
        }

3. Add this code to the Login.aspx view:

<p>
            <%: Html.ActionLink("Reset", "ResetPass") %> your forgotten passord?

</p>

4. Now you should get this result on the login page:

forgot1

And when clicked:
forgot2

Adding a forgot password / reset function to MVC c#

c# Get Email Address from Active Directory (using Username) in Asp.net

dirSometimes it’s handy to grab either a username or email address (why not both?) from active directory. Below are the steps I believe you’ll need to get going quickly. In my example, I’m using VS2012 and .net 4.5.

1. Set your app to use windows authentication, you’ll need to set these to debug in VS:

Your web.config:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Windows" />
    <identity impersonate="true" />

    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
</configuration>

Your project settings:

vs_winauth

2. Now in your application, add a reference to System.DirectoryServices:

dirservices

3. And in your code file:

using System.DirectoryServices;

4. A little function to search through active directory:

 private string uEmail(string uid)
        {
            DirectorySearcher dirSearcher = new DirectorySearcher();
            DirectoryEntry entry = new DirectoryEntry(dirSearcher.SearchRoot.Path);
            dirSearcher.Filter = "(&(objectClass=user)(objectcategory=person)(mail=" + uid + "*))";

            SearchResult srEmail = dirSearcher.FindOne();

            string propName = "mail";
            ResultPropertyValueCollection valColl = srEmail.Properties[propName];
            try
            {
                return valColl[0].ToString();
            }
            catch
            {
                return "";
            }

        }

5. And finally, how you can use:

string uName = "";
uName = uEmail(HttpContext.Current.User.Identity.Name.Replace(@"yourdomain\", ""));

Hope you enjoy! You can also use this method to retrieve other AD details (groups, full name, etc.).

c# Get Email Address from Active Directory (using Username) in Asp.net

IIS / WordPress – Blocking User Agents using Rewrite Rules

wp_logo

If you run WordPress on Windows (and who doesn’t?) and have the need to block specific user agents (bots, crawlers, browsers) below is a decent way I’ve found that uses rewriting rules and works along side the needed WordPress rules:

Adding this rule to your web.config will block the request from the specified agent(s):

 <rule name="RequestBlockingRule1" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_USER_AGENT}" pattern="agent1|agent2|agent3" />
          </conditions>
          <action type="CustomResponse" statusCode="403"
             statusReason="Forbidden: Access is denied."
             statusDescription="You do not have permission to view this page." />
        </rule>

Continue reading “IIS / WordPress – Blocking User Agents using Rewrite Rules”

IIS / WordPress – Blocking User Agents using Rewrite Rules