문제

i는 새로운 MVC 3 사용자이고 SQL 데이터베이스를 통해 관리자를 만들려고합니다. 우선 고객 엔티티가 있으며 관리자는 고객 엔티티에서 부울 유형 인 관리 필드를 통해 정의 할 수 있습니다. 정상적인 고객이 아닌 제품 페이지에서만 관리자에게만 액세스하려고합니다. [Authorize] 대신 [Authorize (Rolle="Admin")]를 만들고 싶습니다. 그러나 저는 어떻게 내 코드에서 관리 역할을 수행 할 수있는 방법을 모르겠습니다. 그런 다음 내 홈 컨트롤러 에서이 코드를 작성했습니다.

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

이제 내 소스 코드입니다.'Authorizeatribute'클래스를 만들어야합니까? 내가해야한다면 어떻게해야합니까?나에게 설명해 주시겠습니까?내 경우에 특정 역할을 설정하는 방법을 이해할 수 없습니다. 어떻게 할 수 있는지 도와주세요.고마워.

도움이 되었습니까?

해결책

role.isinrole 사용법이 올바르지 않습니다.그게 뭐야 [Authorize (Roles="Admin")]는 호출 할 필요가 없습니다.

코드의 역할을 어디서나 설정하지 않습니다.사용자 정의 역할 관리를 원한다면 자신의 역할 공급자를 사용하거나 여기에 표시된대로 Auth 토큰에 저장할 수 있습니다.

http://www.codeproject.com/기사 / 36836 / 양식 - 인증 및 역할 기반 인증 섹션에서 : 에 유의하십시오


// 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 구성"아이콘을 클릭하십시오.여기서 역할을 관리하고 역할에 할당 할 수 있습니다.

다른 팁

나는이 질문이 조금 오래되었다는 것을 알고 있지만 여기서 내가 비슷한 것을 어떻게했는지 여기에 있습니다.사용자가 올바른 보안 액세스가 있는지 확인하는 사용자 지정 권한 부여 속성을 작성했습니다.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top