3

私は新しいMVC3ユーザーであり、SQLデータベースを介して管理者を作成しようとしています。まず、Customerエンティティがあり、adminはCustomerエンティティのブール型であるadminフィールドを介して定義できます。通常の顧客ではなく、製品ページでのみ管理者にアクセスできるようにしたい。そして、[Authorize]の代わりに[Authorize(Roles = "admin")]を作成したいと思います。ただし、コードで管理者の役割を実際に作成するにはどうすればよいかわかりません。次に、HomeControllerで、このコードを記述しました。

public class HomeController : Controller
{

    [HttpPost]
    public ActionResult Index(Customer model)
    {
        if (ModelState.IsValid)
        {
            //define user whether admin or customer
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
            String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'";
            SqlCommand cmd = new SqlCommand(find_admin_query, conn);
            conn.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            //it defines admin which is true or false
            model.admin = sdr.HasRows;
            conn.Close();

            //if admin is logged in
            if (model.admin == true) {
                Roles.IsUserInRole(model.userName, "admin"); //Is it right?
                if (DAL.UserIsVaild(model.userName, model.password))
                {
                    FormsAuthentication.SetAuthCookie(model.userName, true);
                    return RedirectToAction("Index", "Product");
                }
            }

            //if customer is logged in
            if (model.admin == false) {
                if (DAL.UserIsVaild(model.userName, model.password))
                {
                    FormsAuthentication.SetAuthCookie(model.userName, true);                   
                    return RedirectToAction("Index", "Home");
                }
            }
                ModelState.AddModelError("", "The user name or password is incorrect.");
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

そしてDALクラスは

 public class DAL
{
    static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());

    public static bool UserIsVaild(string userName, string password)
    {
        bool authenticated = false;
        string customer_query = string.Format("SELECT * FROM [Customer] WHERE userName = '{0}' AND password = '{1}'", userName, password);      
        SqlCommand cmd = new SqlCommand(customer_query, conn);
        conn.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        authenticated = sdr.HasRows;
        conn.Close();
        return (authenticated);
    }
}

最後に、カスタム[Authorize(Roles = "admin")]を作成します

[Authorize(Roles="admin")]
public class ProductController : Controller
{
  public ViewResult Index()
    {
        var product = db.Product.Include(a => a.Category);
        return View(product.ToList());
    }
}

これらは私のソースコードです。'AuthorizeAttribute'クラスを作成する必要がありますか?私がしなければならない場合、どうすればそれを作ることができますか?説明してもらえますか?私の場合、特定の役割を設定する方法がわかりません。どうすればいいのか教えてください。ありがとう。

4

2 に答える 2

2

この質問は少し古いことは知っていますが、これが私が似たようなことをした方法です。ユーザーが正しいセキュリティアクセス権を持っているかどうかを確認するために使用するカスタム認証属性を作成しました。

[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        // Get the roles from the Controller action decorated with the attribute e.g.
        // [AccessDeniedAuthorize(Roles = MyRoleEnum.UserRole + "," + MyRoleEnum.ReadOnlyRole)]
        var requiredRoles = Roles.Split(Convert.ToChar(","));

        // Get the highest role a user has, from role provider, db lookup, etc.
        // (This depends on your requirements - you could also get all roles for a user and check if they have the correct access)
        var highestUserRole = GetHighestUserSecurityRole();

        // If running locally bypass the check
        if (filterContext.HttpContext.Request.IsLocal) return;

        if (!requiredRoles.Any(highestUserRole.Contains))
        {
            // Redirect to access denied view
            filterContext.Result = new ViewResult { ViewName = "AccessDenied" };
        }
    }
}

次に、カスタム属性でコントローラーを装飾します(個々のコントローラーアクションを装飾することもできます)。

[AccessDeniedAuthorize(Roles="user")]
public class ProductController : Controller
{
    [AccessDeniedAuthorize(Roles="admin")]
    public ViewResult Index()
    {
        var product = db.Product.Include(a => a.Category);
        return View(product.ToList());
    }
}
于 2013-02-25T12:22:52.607 に答える
1

Role.IsInRoleの使用法が正しくありません。これが[Authorize(Roles = "Admin")]の使用目的であり、呼び出す必要はありません。

コードでは、どこにもロールを設定していません。カスタムロール管理を実行する場合は、次に示すように、独自のロールプロバイダーを使用するか、認証トークンにそれらを保存できます。

http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization は、次のセクションに注意してください。


// Get the stored user-data, in this case, user roles
            if (!string.IsNullOrEmpty(ticket.UserData))
            {
                string userData = ticket.UserData;
                string[] roles = userData.Split(',');
                //Roles were put in the UserData property in the authentication ticket
                //while creating it
                HttpContext.Current.User = 
                  new System.Security.Principal.GenericPrincipal(id, roles);
            }
        }


ただし、ここでのより簡単なアプローチは、asp.netの組み込みメンバーシップを使用することです。「インターネットアプリケーション」テンプレートを使用して新しいMVCプロジェクトを作成すると、これがすべてセットアップされます。Visual Studioで、ソリューションエクスプローラーの上にある[asp.net構成]アイコンをクリックします。ここで役割と役割への割り当てを管理できます。

于 2012-03-11T23:34:10.517 に答える