2011-09-16 19 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

あなたは権限を持っていなければこの方法のように使うことができます。それは方法になります。 許可制御は不要です

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", 
      }; 
     } 
    } 
関連する問題