Chào mừng đến với Diễn đàn lập trình - Cộng đồng lập trình.
Trang 1 của 2 12 CuốiCuối
Kết quả 1 đến 10 của 14
  1. #1
    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=&quot;Data Source=.;Initial Catalog=LoginAccount;Persist Security Info=True;User ID=sa;Password=duc10a2;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />  </connectionStrings>
    - Giới thiệu Về Provider
    + 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    {...
    - trong đó Roles ="Admin" là quyền có thể vào.bạn có thể bổ xung thêm nhiều quyền vd như

    Mã:
    [Authorize(Roles = "Admin,ThanhVien,Mod")]//Chi co Admin hoặc ThanhVien hoặc Mod Mới vào được controllers này
    + Quản lý một Accitons.

    Mã:
    ...[Authorize(Roles = "Admin,ThanhVien")] //Chi co Admin va ThanhVien Moi Dung duoc acction nay        [HttpPost] //phuong thuc get        public ActionResult DoiMatKhau(ChangePasswordModel model)        {...
    + Quản lý Một Acctions hoặc Controllers mà chỉ cần nó đăng nhập là vào được thì làm như sau.

    Mã:
    ...[Authorize(Roles = "")] //Chi can dang nhap la dung duoc Action nay        [HttpGet] //phuong thuc get        public ActionResult PhanQuyen()...
    + Ngoài ra ta còn có thể Quản lý bằng tài khoản.vd.

    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()...
    Các thuộc tính lấy quyền hoặc tên tài khoản trong code.

    + 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        }
    2, cần thêm một đoạn provider trong web.config

    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>...
    Link dowload code: http://www.mediafire.com/?5fsto16scg7yf0q

  2. #2
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Trích dẫn Gửi bởi dangbon
    Mã:
    HttpContext.Current.User.Identity.IsAuthenticated
    cái này thay cho seasion cũng đc phải không bạn ?. Thế bao nhiêu lâu thì nó hết tác dụng(thời gian sống của nó ý).
    không phải đâu bạn ạ.cái đó chỉ là kiểm tra xem đã có quyền hay chưa thôi.vd nó trả về true tức là đã đang nhập (có 1 quyền nào đó)
    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

    Trích dẫn Gửi bởi ducnv_b01048
    không phải đâu bạn ạ.cái đó chỉ là kiểm tra xem đã có quyền hay chưa thôi.vd nó trả về true tức là đã đang nhập (có 1 quyền nào đó)
    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
    bạn xem dòng này trong web.config nhe
    Mã:
    <forms loginUrl="~/Account/LogOn" timeout="2880" />
    cai timeout hình như thời gian đó bạn.test thử xem nhé mình chưa test được

  3. #3
    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
    cái này thay cho seasion cũng đc phải không bạn ?. Thế bao nhiêu lâu thì nó hết tác dụng(thời gian sống của nó ý).

  4. #4
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Trích dẫn Gửi bởi ducnv_b01048
    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=&quot;Data Source=.;Initial Catalog=LoginAccount;Persist Security Info=True;User ID=sa;Password=duc10a2;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />  </connectionStrings>
    - Giới thiệu Về Provider
    + 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    {...
    - trong đó Roles ="Admin" là quyền có thể vào.bạn có thể bổ xung thêm nhiều quyền vd như

    Mã:
    [Authorize(Roles = "Admin,ThanhVien,Mod")]//Chi co Admin hoặc ThanhVien hoặc Mod Mới vào được controllers này
    + Quản lý một Accitons.

    Mã:
    ...[Authorize(Roles = "Admin,ThanhVien")] //Chi co Admin va ThanhVien Moi Dung duoc acction nay        [HttpPost] //phuong thuc get        public ActionResult DoiMatKhau(ChangePasswordModel model)        {...
    + Quản lý Một Acctions hoặc Controllers mà chỉ cần nó đăng nhập là vào được thì làm như sau.

    Mã:
    ...[Authorize(Roles = "")] //Chi can dang nhap la dung duoc Action nay        [HttpGet] //phuong thuc get        public ActionResult PhanQuyen()...
    + Ngoài ra ta còn có thể Quản lý bằng tài khoản.vd.

    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()...
    Các thuộc tính lấy quyền hoặc tên tài khoản trong code.

    + 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        }
    2, cần thêm một đoạn provider trong web.config

    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>...
    Link dowload code: http://www.mediafire.com/?5fsto16scg7yf0q
    Ban ơi cho mình hỏi tí nha ví dụ như mình có 1 bảng csdl trong đó có 1 bảng nhân viên,1 bảng khách hàng,và bảng phân quyền thì khi đó mình muốn làm phần đăng nhập và sau đó phân quyền thì mình phải làm sao mình làm trên asp.net MVC3. cám ơn bạn rất nhiều

  5. #5
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Trích dẫn Gửi bởi baothi
    Ban ơi cho mình hỏi tí nha ví dụ như mình có 1 bảng csdl trong đó có 1 bảng nhân viên,1 bảng khách hàng,và bảng phân quyền thì khi đó mình muốn làm phần đăng nhập và sau đó phân quyền thì mình phải làm sao mình làm trên asp.net MVC3. cám ơn bạn rất nhiều
    bạn viết code sử lý đoạn này!hàm 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
            }

  6. #6
    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; }        }     }}
    Đây là phần Customize Principal

    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; }    }}
    Trong file Global.asax

    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;            }        }
    Phần view

    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; }        }    }}
    config trong view/Web.config

    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>
    Phần tiếp theo là code RoleProvinder

    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();        }    }}
    Web.Config

    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>

  7. #7
    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á.

  8. #8
    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]

  9. #9
    ừ.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^^.

  10. #10
    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.?

 

 
Trang 1 của 2 12 CuốiCuối

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •