SORU
5 Mayıs 2010, ÇARŞAMBA


Nasıl ASP.NET MVC için özel üyelik sağlayıcısı oluşturmak 2 muyum?

Nasıl ASP.NET MVC için özel bir üyelik oluşturun 2 ASP.NET üyelik sağlayıcısı dayalı mı?

CEVAP
6 Mayıs 2010, PERŞEMBE


Yeni bir proje için bir özel üyelik sağlayıcısı içeren oluşturduk ve MembershipProvider soyut sınıf ValidateUser yöntem bozdu:

public class MyMembershipProvider : MembershipProvider
{ 
    public override bool ValidateUser(string username, string password)
    {    
        // this is where you should validate your user credentials against your database.
        // I've made an extra class so i can send more parameters 
        // (in this case it's the CurrentTerritoryID parameter which I used as 
        // one of the MyMembershipProvider class properties). 

        var oUserProvider = new MyUserProvider();  
        return oUserProvider.ValidateUser(username,password,CurrentTerritoryID);
    }
}

Daha sonra referans ekleme ve benim Web'den işaret ederek ASP.NET MVC 2 projem için sağlayıcı bağladım.config:

<membership defaultProvider="MyMembershipProvider">
    <providers>
        <clear />
        <add name="MyMembershipProvider"
            applicationName="MyApp"
            Description="My Membership Provider"
            passwordFormat="Clear"
            connectionStringName="MyMembershipConnection"
            type="MyApp.MyMembershipProvider" />
    </providers>
</membership>

RoleProvider soyut sınıf devraldığı özel bir sınıf oluşturmak gerekiyor ve GetRolesForUser yöntemi geçersiz kılar. ASP.NET bu MVC Yetki veren bu yöntem, geçerli oturum açan kullanıcı için atanan bulmak için kullanır ve kullanıcı denetleyicisi eylem erişmek için izin verilir.

Burada atmamız gereken adımlar:

1) RoleProvider soyut sınıfı miras alır ve GetRolesForUser yöntemi geçersiz kılan özel bir sınıf Oluşturun:

public override string[] GetRolesForUser(string username)
{
    SpHelper db = new SpHelper();
    DataTable roleNames = null;
    try
    {
        // get roles for this user from DB...

        roleNames = db.ExecuteDataset(ConnectionManager.ConStr,
                    "sp_GetUserRoles",
                    new MySqlParameter("_userName", username)).Tables[0];
    }
    catch (Exception ex)
    {
        throw ex;
    }
    string[] roles = new string[roleNames.Rows.Count];
    int counter = 0;
    foreach (DataRow row in roleNames.Rows)
    {
        roles[counter] = row["Role_Name"].ToString();
        counter  ;
    }
    return roles;
}

2) rolü bizim web) ASP.NET MVC 2 Uygulama sağlayıcısı ile Bağlayın.config:

<system.web>
...

<roleManager enabled="true" defaultProvider="MyRoleProvider">
    <providers>
        <clear />
        <add name="MyRoleProvider"
            applicationName="MyApp"
            type="MyApp.MyRoleProvider"
            connectionStringName="MyMembershipConnection" />
    </providers>
</roleManager>

...
</system.web>

3) Yetki Seti(Roller=",") xxx yyy istedi Denetleyicisi yukarıda Aksiyon/:

[Authorization(Roles = "Customer Manager,Content Editor")]
public class MyController : Controller
{
    ...... 
}

İşte bu! Şimdi çalışıyor!

4) İsteğe bağlı: Authorize AccessDenied bir Sayfa için istenmeyen bir rol yönlendirebilirsiniz böylece öznitelik özel bir set:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyAuthorizationAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The name of the master page or view to use when rendering the view on authorization failure.  Default
    /// is null, indicating to use the master page of the specified view.
    /// </summary>
    public virtual string MasterName { get; set; }

    /// <summary>
    /// The name of the view to render on authorization failure.  Default is "Error".
    /// </summary>
    public virtual string ViewName { get; set; }

    public MyAuthorizationAttribute ()
        : base()
    {
        this.ViewName = "Error";
    }

    protected void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
        validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (AuthorizeCore(filterContext.HttpContext))
        {
            SetCachePolicy(filterContext);
        }
        else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // auth failed, redirect to login page
            filterContext.Result = new HttpUnauthorizedResult();
        }
        else if (filterContext.HttpContext.User.IsInRole("SuperUser"))
        {
            // is authenticated and is in the SuperUser role
            SetCachePolicy(filterContext);
        }
        else
        {
            ViewDataDictionary viewData = new ViewDataDictionary();
            viewData.Add("Message", "You do not have sufficient privileges for this operation.");
            filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
        }
    }

    protected void SetCachePolicy(AuthorizationContext filterContext)
    {
        // ** IMPORTANT **
        // Since we're performing authorization at the action level, the authorization code runs
        // after the output caching module. In the worst case this could allow an authorized user
        // to cause the page to be cached, then an unauthorized user would later be served the
        // cached page. We work around this by telling proxies not to cache the sensitive page,
        // then we hook our custom authorization code into the caching mechanism so that we have
        // the final say on whether a page should be served from the cache.
        HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
        cachePolicy.SetProxyMaxAge(new TimeSpan(0));
        cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
    }
}

Şimdi kendi yaptı bizim öznitelik kullanıcılarımızın engellendi görüntüleyin yönlendirmek için kullanabilirsiniz:

[MyAuthorization(Roles = "Portal Manager,Content Editor", ViewName = "AccessDenied")]
public class DropboxController : Controller
{ 
    .......
}

İşte bu! Süper!

İşte tüm bu bilgi almak için kullandım bazı bağlantılar:

Özel rol sağlayıcısı: http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx

Bu Bilgi yardımcı olur umarım!

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • boburnham

    boburnham

    11 Temmuz 2006
  • Mindy

    Mindy

    20 NİSAN 2006
  • Mr. H

    Mr. H

    1 Temmuz 2012