-
14-08-2012, 11:15 AM #1Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
Quản Lý Tài Khoản Bằng Provider MVC3
Videos demo cho web.
http://www.youtube.com/watch?v=2bR4R...ature=youtu.be
Để chạy được web các bạn cần tạo database.(chạy query file: LoginAccount.sql trong object).
đổi mật khẩu và tên máy cho đúng trong web.config
Mã:<connectionStrings> <add name="LoginAccountEntities" connectionString="metadata=res://*/LoginAccount.csdl|res://*/LoginAccount.ssdl|res://*/LoginAccount.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;Initial Catalog=LoginAccount;Persist Security Info=True;User ID=sa;Password=duc10a2;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /> </connectionStrings>
+ có thể quản lý được các quyền hạn để vào một trang nào đó.
+ có thể quản lý được các tài khoản để vào một trang nào đó
+ cách code đơn giản và hiệu quả.
- Cách quản lý các hàm(Acction trong controllers)
+ Quản lý Cả controllers.
Mã:...[Authorize(Roles = "Admin")]//Chi co Admin Moi Dung Duoc Controller nay public class AdminController : Controller {...
Mã:[Authorize(Roles = "Admin,ThanhVien,Mod")]//Chi co Admin hoặc ThanhVien hoặc Mod Mới vào được controllers này
Mã:...[Authorize(Roles = "Admin,ThanhVien")] //Chi co Admin va ThanhVien Moi Dung duoc acction nay [HttpPost] //phuong thuc get public ActionResult DoiMatKhau(ChangePasswordModel model) {...
Mã:...[Authorize(Roles = "")] //Chi can dang nhap la dung duoc Action nay [HttpGet] //phuong thuc get public ActionResult PhanQuyen()...
Mã:...[Authorize(Users= "Admin")] //Chỉ có tài tài khoản Admin mới vào được hàm này. tài khoản chứ không phải quyền đâu nhé.đừng nhầm :)) [HttpGet] //phuong thuc get public ActionResult PhanQuyen()...
+ HttpContext.Current.User.Identity.IsAuthenticated (true nếu đã có quyền,false chưa có quyền)
+ HttpContext.Current.User.Identity.Name (Lấy tên tai khoản của người dùng)
+ HttpContext.Current.User.IsInRole("Admin") (true nếu đúng là quyền Admin, false nếu không phải quyền Admin).
+ FormsAuthentication.SetAuthCookie("ten tai khoan can lay quyền", true nếu muốn lưu vào cookie false thi không lưu); (Khi gọi hàm này thì nó sẽ tự động gọi hàm GetRolesForUser(string username) trong fie CustomRoleProvider.cs) nó sẽ chuyền giá trị username để lấy quyền.
...
- Nếu những Controllers hoặc Acction nào mà bạn không muốn phân quyền cho nó thì đừng thêm [Authorize(Roles = "Admin,ThanhVien")] cho nó là được.
để dùng Provider cần chú ý những file sauxem trong object nhé)
1, cần có class : CustomRoleProvider.cs (nếu copy sang object khác nhớ đổi tên namespace nhé)
+ trong file này cần sử lý hàm GetRolesForUser(string username) để lấy quyền.
Mã:public override string[] GetRolesForUser(string username) { ////-----------------ket noi voi database de lay quyen cua tai khoan----------------- LoginAccountEntities db = new LoginAccountEntities(); //tao ket noi voi database Account account = db.Accounts.Single(x => x.NameAccount.Equals(username)); //tuong duong voi cau lenh "Select Top 1 From Accounts Where NameAccount = username" if (account != null) /eu tim thay tai khoan { return new String[] { account.Roles }; //tra ve quyen cua nguoi dung } else return new String[] { }; /ew khong tim thay tai khoan thi gan quyen bang null }
Mã:...<system.web> <!--impost quyen/////////////////////////--> <roleManager enabled="true" defaultProvider="MyRoleProvider"> <providers> <clear /> <add name="MyRoleProvider" type="QuanLyAccount.CustomRoleProvider" /><!--QuanLyAccount là tên object nếu bạn copy sang object khac nhớ đổi tên nhé--> </providers> </roleManager> <!--/////////////////////////////////////--> <compilation debug="true" targetFramework="4.0"> <assemblies>...
View more random threads:
- Nhận URL từ Internet Explorer trong lập trình C#
- Tạo bộ đếm số người online trong ASP.NET [Đầy đủ hướng dẫn và source code]
- hướng dẫn tạo report đơn giản trong C#
- Xây dựng Danh sách liên kết trong C#
- Giúp đỡ về cài đặt và cấu hình share point
- Học lập trình C# trực tuyến bằng Video trên microsoft.com
- Xử lý String và Regular Expressions (Regex Class) Trong C#
- Vlog 6: Hướng dẫn lập trình: Tạo notepad đơn giản với C#
- Sắp xếp ListView theo cột bất kỳ trong lập trình C#
- Chuyển file JPEG-GIF-PNG sang Window Media Photo (WDP) trong lập trình C#
-
12-10-2012, 03:43 PM #2Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
Gửi bởi dangbon
false tức chưa
còn cái này mới là lưu tài khoản
+ FormsAuthentication.SetAuthCookie("ten tai khoan can lay quyền", true nếu muốn lưu vào cookie false thi không lưu);
nó là setcookie
bạn tìm hiểu class của nó xem quản lý lưu cookie này bao lâu chứ mình cũng không để ý nó sống bao lâu đâu
Gửi bởi ducnv_b01048
Mã:<forms loginUrl="~/Account/LogOn" timeout="2880" />
-
12-10-2012, 07:58 PM #3Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
rất hay cảm ơn bạn .
Mã:HttpContext.Current.User.Identity.IsAuthenticated
-
16-11-2012, 07:37 PM #4Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
Gửi bởi ducnv_b01048
-
19-11-2012, 08:49 AM #5Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
Gửi bởi baothi
Mã:public override string[] GetRolesForUser(string username) { ////-----------------ket noi voi database de lay quyen cua tai khoan----------------- LoginAccountEntities db = new LoginAccountEntities(); //tao ket noi voi database Account account = db.Accounts.Single(x => x.NameAccount.Equals(username)); //tuong duong voi cau lenh "Select Top 1 From Accounts Where NameAccount = username" if (account != null) /eu tim thay tai khoan { return new String[] { account.Roles }; //tra ve quyen cua nguoi dung } else return new String[] { }; /ew khong tim thay tai khoan thi gan quyen bang null }
-
19-01-2013, 10:36 AM #6Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
Bác ơi cho mình hỏi.
Mình làm theo ví dụ của bác thì chạy ok
Làm theo hướng dẫn này để customize Principal vs Identity cũng ok
http://stackoverflow.com/questions/1...-or-iprincipal.
Nhưng khi làm cả hai một lúc thì thằng RoleProvider nó ko nhận.
Ko biết có phải làm ji thêm ko .
Đây là code của mình. Mình làm login bằng google:
source http://www.mediafire.com/?zvyjdylc2danewg
phần Custom principal
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;using System.Web.Security;using System.Web.Script.Serialization;using CustomAuthen.Models;using DotNetOpenAuth.OpenId;using DotNetOpenAuth.OpenId.RelyingParty;using DotNetOpenAuth.Messaging;using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; namespace CustomAuthen.Controllers{ public class AccountController : BaseController { // GET: /Account/LogOff public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } // // GET: /Account/LogOn public ActionResult LogOn() { var openid = new OpenIdRelyingParty(); var response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: var fetch = response.GetExtension<FetchResponse>(); string email = "none"; string name = "none"; if (fetch != null) { email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); name = "Vũ Chí Dũng"; } FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false); CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel(); JavaScriptSerializer serializer = new JavaScriptSerializer(); serializeModel.FirstName = name; string userData = serializer.Serialize(serializeModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, email, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData); string encTicket = FormsAuthentication.Encrypt(authTicket); FormsAuthentication.SetAuthCookie(email, true); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); break; } return RedirectToAction("Index", "Home"); } else { const string googleEndPoint = "https://www.google.com/accounts/o8/id"; var request = openid.CreateRequest(Identifier.Parse(googleEndPoint)); var fetch = new FetchRequest(); fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email); fetch.Attributes.AddRequired(WellKnownAttributes.Name.Alias); request.AddExtension(fetch); return request.RedirectingResponse.AsActionResult(); } } }}
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CustomAuthen.Controllers{ public class HomeController : BaseController { public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } [Authorize(Roles="admin")] public ActionResult About() { return View(); } }}
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using CustomAuthen.Custom; namespace CustomAuthen.Controllers{ public class BaseController : Controller { protected virtual new CustomPrincipal User { get { return HttpContext.User as CustomPrincipal; } } }}
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Security.Principal; namespace CustomAuthen.Custom{ public class CustomPrincipal : ICustomPrincipal { public IIdentity Identity { get; private set; } public bool IsInRole(string role) { return false; } public CustomPrincipal(string email) { this.Identity = new GenericIdentity(email); } public string FirstName { get; set; } }}
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Security.Principal; namespace CustomAuthen.Custom{ public interface ICustomPrincipal : IPrincipal { string FirstName { get; set; } }}
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web; namespace CustomAuthen.Models{ public class CustomPrincipalSerializeModel { public string FirstName { get; set; } }}
Mã:protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); if (serializeModel != null) { newUser.FirstName = serializeModel.FirstName; } HttpContext.Current.User = newUser; } }
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using CustomAuthen.Custom; namespace CustomAuthen.Views{ public abstract class BaseViewPage : WebViewPage { public virtual new CustomPrincipal User { get { return base.User as CustomPrincipal; } } } public abstract class BaseViewPage<TModel> : WebViewPage<TModel> { public virtual new CustomPrincipal User { get { return base.User as CustomPrincipal; } } }}
Mã:<system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="CustomAuthen.Views.BaseViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <amespaces> </pages> </system.web.webPages.razor>
Mã:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security; namespace CustomAuthen{ public class CustomRoleProvider : RoleProvider { public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { //if (username.Equals("dungvc01004@fpt.edu.vn")) return new string[] { "admin" }; //else // return new string[] { }; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override bool IsUserInRole(string username, string roleName) { throw new NotImplementedException(); } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } }}
Mã:</compilation> <roleManager enabled="true" defaultProvider="CustomRoleProvider"> <providers> <clear/> <add name="CustomRoleProvider" type="CustomAuthen.CustomRoleProvider"/> </providers> </roleManager> <authentication mode="Forms"> <forms loginUrl="~/Home/Index" timeout="2880" /> </authentication>
-
22-01-2013, 12:18 PM #7Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
mình cũng có làm cái này với google rồi vẫn ok mà.bac tham khảo code của mình nhé.bận quá nên không xem được.mà nếu có điều kiện bác nên chuyển lên làm mvc4 cũng .net 4.0 mà.dùng mvc4 thì mấy thằng api google hay facebook làm dễ hơn.cái phân quyền này mình làm chạy ngon trên mvc3 và mvc4
link: https://skydrive.live.com/redir?resi...BtwVUjz0bZ8pic
mục openid_mvc nhá.
-
23-01-2013, 05:32 PM #8Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
Mình có thêm phần custom Principal thì ko nhận đc thằng rule provider chứ ko liên quan đến thằng google login bác ạ [IMG]images/smilies/biggrin.png[/IMG]
-
24-01-2013, 10:01 AM #9Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
ừ.thế đã chạy được chưa?nên dùng một thằng thôi bác.chứ import lắm thằng vào rồi nó xung đột lẫn nhau đây^^.
-
03-04-2013, 02:53 PM #10Junior Member
- Ngày tham gia
- Sep 2015
- Bài viết
- 0
cho mình hỏi dùng thằng này với sql membership provider thì nên dùng cái nào hơn.?
Pallet nhựa Long An đã trở thành một trong những lựa chọn phổ biến cho nhu cầu vận chuyển và lưu trữ hàng hóa trong nhiều ngành công nghiệp. Với đặc tính nhẹ nhàng, chắc chắn và dễ vận chuyển, các...
Thanh lý pallet nhựa Long An giá rẻ