私はMVCアプリを持っていると示したように、私はそれのためのカスタムroleproviderを書いた:HttpContext.Current.User.IsInRole(「myRoleの」)にそれをフックアップする方法roleprovider MVCのカスタム
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using VectorCheck.Models;
namespace VectorCheck.Security
{
public class MyRoleProvider : RoleProvider
{
private VectorCheckRepository<User> _repository { get; set; }
public MyRoleProvider()
{
_repository = new VectorCheckRepository<User>();
}
public MyRoleProvider(VectorCheckRepository<User> repository)
{
_repository = repository;
}
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)
{
var user = _repository.GetUser(username);
return new string[] { user.Role.Name };
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
var user = _repository.GetUser(username);
return string.Compare(user.Role.Name, roleName, true) == 0;
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
をこれが実際に動作します
[Authorize(Roles = "Administrator")]
コントローラやアクション以上:よく使用してコントローラとアクションへのアクセスを制限しています。
使用しているが、私はまた、ビューにいくつかのものへのアクセス制限をしたい:そう上書きなっていないが
HttpContext.Current.User.IsInRole("Administrator")
このメソッドは、私のroleproviderの一部ではありません。
誰もこの方法でそれを行う方法を知っていますか?
マイロールプロバイダでこのトピックに関する
本当に良いチュートリアルは、しかしメソッドIsInRoleが含まれていません。それはRoleProviderを継承し、メソッドIsUserInRoleを持ちます。 – AnonyMouse
HttpContext.Current.UserのIsInRoleメソッドは、IPrincipalを実装する型です。 RoleProviderが登録されており、認証されたユーザーからリクエストが入った場合、IPrincipalはRolePrincipalのインスタンスになります。上のメソッドから、RolePrincipalのIsInRoleがRoleProviderのGetRolesForUserメソッドを呼び出すので、正しく呼び出されるようにブレークポイントを設定する必要があることがわかります。 –