MVC 3はカスタムロールを承認します
-
11-12-2019 - |
質問
私は新しいMVC 3ユーザーで、私はSQLデータベースを介して管理しようとしています。 まず第一に、私は顧客エンティティと管理者が顧客エンティティでブール型である管理フィールドを通して管理することができます。 通常の顧客ではなく、製品ページでのみ管理者にアクセスすることをお勧めします。 そして、[承認]ではなく[承認(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);
}
}
.
最後に、カスタムを作成したい[承認(roles="admin")]
[Authorize(Roles="admin")]
public class ProductController : Controller
{
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}
.
これらは私のソースコードです。「AuthorizeTtribute」クラスを作る必要がありますか? 私がしなければならないならば、どうすれば私はそれを作ることができますか?私に説明できますか?私の場合に特定の役割を設定する方法を理解することはできません。 どうやってできるのか私に助けてください。ありがとう。
解決
あなたのrole.isinroleの使用法は正しくありません。それは何をどうですか [authorize(roles="admin")]が使用されますが、それを呼び出す必要はありません。
あなたのコードでは、どこでも役割を設定していません。カスタムロール管理をしたい場合は、ここに示すように、独自の役割プロバイダを使用するか、それらを認証トークンに保存することができます。
http://www.codeproject.com/論文/ 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では、Solution Explorerの上の「ASP.NET構成」アイコンをクリックしてください。ここでロールとロールへの割り当てを管理できます。
他のヒント
私はこの質問が少し古いですが、ここに私が似たようなことをした方法です。ユーザーが正しいセキュリティアクセスがあるかどうかを確認するために使用したカスタム認証属性を作成しました。
[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());
}
}
.