2011-09-16 6 views
18

양식 인증과 함께 MVC 3을 사용하고 있습니다. 내 컨트롤러 또는 방법에, 나는 다음과 같은 일을 오전 :ASP.NET - 역할 인증 실패시 오류 페이지로 리디렉션

[Authorize (Roles = "developer")] 

을이 상황에서, 나는 사용자와하지 않을 경우 기록됩니다 있는지 확인 로그인 페이지로 돌아가려면. 그러나 해당 사용자에 대한 'IsInRole'검사가 false를 반환하면 '승인되지 않음'과 같은 다른보기로 이동해야합니다.

이와 같은 작업을 수행하는 가장 좋은 방법은 무엇입니까? 필자는 새로운 Authorization 속성을 만들지 않기를 원했기 때문에 전체 애플리케이션에서 모든 Authorize 속성을 리팩터링 할 필요가 없었지만 필요한 경우이 경로를 찾아야합니다.

답변

44

일을 할 수있는 HandleUnauthorizedRequest 방법을 재정의하는 사용자 지정 권한 부여 속성 : 다음

public class MyAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      // The user is not authenticated 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
     else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) 
     { 
      // The user is not in any of the listed roles => 
      // show the unauthorized view 
      filterContext.Result = new ViewResult 
      { 
       ViewName = "~/Views/Shared/Unauthorized.cshtml" 
      }; 
     } 
     else 
     { 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
    } 
} 

과 :

[MyAuthorize(Roles = "developer")] 
public ActionResult Develop() 
{ 
    ... 
} 
+0

완벽하게 작동했습니다. – Brandon

+0

완벽한 ... 고마워 ... – Shaz

+3

이 사용자 지정 구현은 어디에 배치합니까? –

1

또한 401 개 상태 코드에 대한 사용자 지정 오류 페이지로이 작업을 수행 할 수 있습니다.

구현 세부 정보는 this question을 참조하십시오.

0

당신은 권한을 가지지 않으므로 this처럼 사용할 수 있습니다. 그것은 방법이됩니다. 인증 제어가 필요하지 않습니다.

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      // The user is not authenticated 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
     else 
     { 
      filterContext.Result = new ViewResult 
      { 
       ViewName = "~/Views/Shared/Unauthorized.cshtml", 
      }; 
     } 
    } 
관련 문제