使用ASP.NET MVC WebSecurity 過程記錄

需安裝兩個套件
Microsoft.AspNet.WebHelpers
WebMatrix.WebData

Web.config 的<system.web> 需增加

<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>

如何將ASP.NET MVC全站鎖住

當使用ASP.NET MVC在開發管理後台或系統時,關於權限的設定,第一步就是先將全站鎖住,再將Login那一頁用[AllowAnonymous] 開放。

Step01.在App_Start的檔案夾中找得 FilterConfig.cs,增加
filters.Add(new AuthorizeAttribute());

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            //增加這一行
            filters.Add(new AuthorizeAttribute());
        }
    }

Step02.需安裝兩個nuget套件
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.Cookies

Step03.新增一個OWIN Startup的類別,並命名為Startup.cs

public class Startup
{
     public void Configuration(IAppBuilder app)
     {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            //作為辨識的的Cookie屬性
            AuthenticationType = "ApplicationCookie",
            //如果無權限存取401 最後導頁的位置
            LoginPath = new PathString("/Account/Login")
        });
    }
}