私は新しい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クラスを作成する必要がありますか? どうすればいいですか?どうすれば作れますか?私に説明できますか?私は私の場合に特定の役割を設定する方法を理解できません。 どうすればいいですか?ありがとう。
あなたのコードはSQLインジェクションに簡単にオープンできます:String find_admin_query = "SELECT admin FROM customer where userName = '" + model.userName + "AND admin =' true '"; usernameが: ';ユーザーから削除; - –