2012-03-11 18 views
3

私は新しいMVC 3ユーザーです。私はSQLデータベースを使用してadminを作成しようとしています。 まず、Customerエンティティでboolean型のadminフィールドを使用してCustomerエンティティとadminを定義できます。 通常のカスタマーではなく、プロダクトページでのみ管理者にアクセスしたいと思っています。 [Authorize]の代わりに[Authorize(Roles = "admin")]を作成したいと思います。 しかし、実際に自分のコードで管理者の役割をどうやって作るのか分かりません。 次に、私のHomeControllerでこのコードを書いた。MVC 3カスタムロールを承認する

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")] 
public class ProductController : Controller 
{ 
    public ViewResult Index() 
    { 
     var product = db.Product.Include(a => a.Category); 
     return View(product.ToList()); 
    } 
} 

カスタム[承認(役割は= "管理者")]にしたいです。 AuthorizeAttributeクラスを作成する必要がありますか? どうすればいいですか?どうすれば作れますか?私に説明できますか?私は私の場合に特定の役割を設定する方法を理解できません。 どうすればいいですか?ありがとう。

+1

あなたのコードはSQLインジェクションに簡単にオープンできます:String find_admin_query = "SELECT admin FROM customer where userName = '" + model.userName + "AND admin =' true '"; usernameが: ';ユーザーから削除; - –

答えて

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プロジェクトを作成すると、これがすべてセットアップされます。ビジュアルスタジオで、ソリューションエクスプローラの上にある "asp.net configuration"アイコンをクリックします。ここで役割を管理し、役割に割り当てることができます。

2

私はこの質問が少し古いことを知っていますが、ここで私は何か似たようにしました。私は、ユーザーが正しいセキュリティアクセスを持っていた場合、私がチェックするために使用されるカスタム認可属性を作成しました:

[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()); 
    } 
} 

[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" }; 
     } 
    } 
} 

は今カスタム属性(あなたはまた、個々のコントローラのアクションを飾ることができます)とコントローラーを飾ります

関連する問題