2013-01-01 23 views
2

我正在創建ASP.NET MVC Web應用程序。我有數據模型用戶:如何在.NET Web應用程序中創建用戶身份驗證?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace Knihovna.Models 
{ 
    public class User 
    { 
     public int UserId { get; set; } 
     public string Name { get; set; } 
     public string Login { get; set; } 
     public string Password { get; set; } 
     public List<Book> Books { get; set; } 
    } 
} 

我需要創建用戶註冊和用戶登錄。應用程序需要知道如果用戶已登錄。

是否有一些最佳實踐如何做到這一點?保存會話中登錄的用戶?

回答

2

我會使用ASP.NET成員資格和角色提供者模型。如果您想要使用自定義表格,可以創建一個從成員資格提供程序繼承的類。有許多方法,你可以實現支持諸如更改密碼,忘記密碼等......但一個用於登錄會的ValidateUser

public sealed class MyMembershipProvider : MembershipProvider 
{ 
    public override bool ValidateUser(string username, string password) 
    { 
     bool isValid = false; 
     // your authentication logic here 
     var ticket = new FormsAuthenticationTicket(
        1, 
        YOUR_USER_ID_HERE, 
        DateTime.Now, 
        DateTime.Now.AddMinutes(30), 
        false, 
        name, 
        FormsAuthentication.FormsCookiePath); 

       var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); 
       HttpContext.Current.Response.Cookies.Add(authCookie); 

     return isValid; 
    } 
} 

您還需要創建一個角色提供,如果你願意就像那裏有不同級別的用戶一樣。爲此,您將繼承RoleProvider類。

public sealed class MyRoleProvider : RoleProvider 
{ 
    // Implement logic here 
} 

要授權您的應用程序的某些區域,您可以使用Authorize屬性。

public class MyController : Controller 
{ 
    [Authorize(Roles="Role1,Role2")] 
    public ActionResult Index() 
    { 
     // Implement your code 
    } 
} 

最後是你必須做的就是它使用您的供應商在web.config一些配置。

<authentication mode="Forms"> 
    <forms loginUrl="~/Login" timeout="2880"/> 
</authentication> 
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="20"> 
    <providers> 
    <clear/> 
    <add name="MyMembershipProvider" type="Your.NameSpace.MyMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false"/> 
    </providers> 
</membership> 
<roleManager enabled="true" defaultProvider="MyRoleProvider" cacheRolesInCookie="true"> 
    <providers> 
    <clear/> 
    <add name="MyRoleProvider" type="Your.NameSpace.MyRoleProvider"/> 
    </providers> 
</roleManager> 

你可以找到MSDN

+0

我實現了自定義的成員提供它現在作爲我除了感謝! – Artegon

2

有關memberhsip和角色提供更多信息,有沒有必要亂用的Session對象。

由於您已經在使用ASP.NET MVC,因此您的Controllers文件夾中可能有一個AccountController。該控制器具有適當的基本認證方法。

我建議你看看本教程由ASP.NET團隊解釋,然後告訴你如何在ASP.NET MVC中使用認證+授權。

爲ASP.NET MVC 默認Visual Studio項目模板自動啓用窗體身份驗證創建新的ASP.NET MVC應用程序 時。它還自動將預先構建的 帳戶登錄頁面實施添加到項目中 - 這使得 真正易於在站點中集成安全性。

NerdDinner Step 9: Authentication and Authorization

+0

我需要真正非常複雜的用戶登錄操作。不幸的是它是學校項目,所以我需要自己編程。你有什麼建議? – Artegon

相關問題