Wednesday, March 23, 2016

Using forms authentication in ASP.NET MVC

This article mainly focuses on how to use forms authentication to redirect requests to a login page when users try to access a page that requires authentication.

1 Create an MVC project

2 Configure Web.config
   Adding authentication info into the Web.config file, notice that modifying the file under the root directory your project but not under the view folder.

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <authentication mode="Forms">
      <forms name=".timecapture" cookieless="UseCookies" loginUrl="~/Account/Login" 
             timeout="432000" protection="All" path="/" slidingExpiration="true" />
    </authentication>
    <httpRuntime targetFramework="4.5.2" />
  </system.web>

About the attribute in authentication block:
  • mode
    • forms: using in ASP.NET form-based application
    • windows: using in Microsoft Internet Information Services
  • forms element
    • cookieless: UseCookies means that that the cookies will always be used,
    • loginUrl : specifies the URL to which the request is redirected for login
    • timeout: Specifies the time, in integer minutes, after which the cookie expires
    • protection: All means that the application uses both data validation and encryption to help protect the cookie.
    • slidingExpiration: Specifies whether sliding expiration is enabled

3 Set authorize controller
   To restrict access for a specific controller
namespace TimeCapture.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        
        public ActionResult Index()
        {
            return View();
        }

4 Set authorization cookies in the login action which is speified in Web.config
FormsAuthentication.SetAuthCookie(user.Username.ToLower(), true);

When the application is launched, due to the authorization of Home/Index action, the route will change to Account/Login which is defined by web.config. In this action, when login is OK, it will set the authorization cookie for current user.
And you can close and reopen your browser, you will find that the home page is displayed and there is no need to login again, which means the authentication is working. Furthermore, you can clean the cookies on your browser and it will become to need login.


Reference: https://msdn.microsoft.com/en-us/library/532aee0e%28v=vs.100%29.aspx
                  https://msdn.microsoft.com/en-us/library/1d3t3c61%28v=vs.100%29.aspx
Source code: https://github.com/Ming-Kong/TimeCapture


1 comment:

  1. Best Titanium Flat Iron - The Ultimate Guide to Iron
    There are many different ceramic vs titanium flat iron versions of used ford fusion titanium Titanium, with the most commonly grade 23 titanium used in the industry to the following. titanium pans Some of the variants, known as Steel and Steel, t fal titanium

    ReplyDelete