ASP.NET MVC 응용 프로그램을 만들고 있는데 이것이 내 문제입니다.권한 부여시 추가 비즈니스 로직을 구현할 위치는 어디입니까?
컨트롤러에서 작업에 액세스 할 때 권한이 부여 된 사용자가 권한 부여 된 역할에 로그인했는지 확인하는 것 외에 사용자 i가 있으면 논리를 포함해야합니다 (일반 사용자가 관리자를 편집하는 것을 허용하고 싶지 않습니다.)
어디에서이 논리를 구현해야합니까? AuthorizeAttribute 메서드를 재정의하고 단순히이 논리를 거기에 추가 할 싶었지만이 경우 사용자가 특성 매개 변수를 편집하려면 보내야 할 수도 있지만 허용되지 않습니다.
다른 옵션은 컨트롤러에 개인 메서드를 만드는 것이지만 다른 컨트롤러에서이 논리를 사용하려면이 코드를 반복해서 반복해야합니다.
올바른 해결책은 무엇입니까? 당신이 볼 수 있듯이 내가 그들을 전달하는 방법을 잘 모릅니다 때문에
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeRolesAttribute : AuthorizeAttribute
{
private string _roles { get; set; }
private UserEntity _user { get; set; }
private UserEntity _loggedUser { get; set; }
public AuthorizeRolesAttribute(string Roles, string User, int Id)
{
_user = new UserEntity();
_loggedUser = new UserEntity();
_roles = Roles;
}
//Called when access is denied
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Account", action = "LogOn" })
);
}
//Core authentication, called before each action
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool b = false;
string[] roles = _roles.Split(',');
//Is user logged in?
if (httpContext.User.Identity.IsAuthenticated)
{
//If user is logged in and we need a custom check:
if (roles.Any(r => httpContext.User.IsInRole(r)) && HasPermission(_user, _loggedUser))
b = true;
}
//Returns true or false, meaning allow or deny. False will call HandleUnauthorizedRequest above
return b;
}
private bool HasPermission(UserEntity user, UserEntity loggedUser)
{
if (user.IsAdmin) return false;
if (loggedUser.IsAdmin || loggedUser.IsApplicationAdmin) return true;
if (loggedUser.IsAmbassador)
{
if (user.IsApplicationAdmin)
{ return false; }
else
{ return true; }
}
return false;
}
}
순간 메신저에서 바로 빈 가짜 객체에게 _user와 생성자 _loggedUser를 작성. 내가 알고있는 것처럼
저는 이것을 구현해야하며 이미했는지 알고 있습니다. 하지만 나는 UserEntity 클래스를 말할 수있는 사용자 객체를 필요로한다. 나는 그것을 할 수 없다는 것을 안다. 적어도 나는 나의 사용자들에게 독특한 사용자의 이메일을주고 싶다. 내 사용자 정의 속성을 구현할 때, 이렇게 할 수 있습니까? [CustomAttribute (Roles = "admin, administrator"), Email = Model.UserToEdit] ... 나는 꽤 확신 할 수 없다. 나는 단지 하드 코딩 할 수있다. Email = [email protected] ... 그러나 나는 모른다. 이메일은 그 시간에 있어야합니다. – Martin