ユーザーがどの役割を果たしているかを確認するためにAsp.netMVCが使用するデータソースは何ですか。そして、自分のデータベーステーブルで動作するように変更するにはどうすればよいですか(書き込むときに[Autorize(Roles="admin")]
、ユーザーがロールに属しているかどうかをテーブルでチェックします)
2368 次
1 に答える
4
ユーザーがどの役割を果たしているかを確認するためにAsp.netMVCが使用するデータソースは何ですか。
RoleProvider
web.configで構成されているを使用します。custom role provider
カスタムテーブルを使用する場合は、クラスから継承しRoleProvider
て抽象メンバーを実装することで、を作成できます。IsUserInRole
この場合に使用されるのはこのメソッドであるため、このメソッドは常に実装する必要があります。
public class MyRoleProvider: RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
// go and hit your custom datasource to verify if the user
// is in the required role and return true or false from this
// method
...
}
}
次に、デフォルトのロールプロバイダーを置き換えるために、カスタムロールプロバイダーをweb.configに登録できます。
<system.web>
...
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<add name="MyRoleProvider" type="Mynamespace.MyRoleProvider" />
</providers>
</roleManager>
</system.web>
また、プロバイダーを使用したくない場合(previous question
そのように思われる場合)Authorize
、ロールプロバイダーをまったく使用していないが、独自のカスタムコードを使用しているカスタム属性を作成する必要があります。
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
{
// no user is authenticated => no need to go any further
return false;
}
// at this stage we have an authenticated user
string username = httpContext.User.Identity.Name;
return IsInRole(username, this.Roles);
}
private bool static IsInRole(string username, string roles)
{
// the username parameter will contain the currently authenticated user
// the roles parameter will contain the string specified in the attribute
// (for example "admin")
// so here go and hit your custom tables and verify if the user is
// in the required role
...
}
}
最後に、ロールプロバイダーに基づくデフォルトの属性に依存するのではなく、このカスタム属性でコントローラーアクションを装飾します。
[MyAutorize(Roles = "admin")]
public ActionResult Index()
{
...
}
于 2013-02-17T14:13:17.907 に答える