ASP.NET MVCのフレームワークにはすでにAuthorizeAttributeという認証していないユーザーのリクエストは無視するActionFilterがある。これはこれで役に立つ機能なのだが、リクエストをまったく無視されてもユーザーフレンドリーとは呼べないので、もっと便利に、認証していないユーザーのリクエストはログインを促すように変更したいと思う。
-RequiredAuthAttribute.cs-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | [AttributeUsage(AttributeTargets.All, AllowMultiple = true )] public class RequiredAuthAttribute : ActionFilterAttribute { public string Route{ get ; set ; } public string Action { get ; set ; } public RequiredAuthAttribute() { Route = "Account" ; Action = "Login" ; } private string RedirectUrl() { if (Action.CompareTo( "" ) != 0) return "/" + Route + "/" + Action; return "/" + Route; } public override void OnActionExecuting( ActionExecutingContext filterContext) { if (filterContext == null ) { throw new ArgumentNullException( "filterContext is null in the RequiredAuth attribute" ); } if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { string loginUrl = RedirectUrl(); filterContext.HttpContext .Response.Redirect(loginUrl, true ); } } } |
ActionFilterAttributeを継承したRequiredAuthAttributeクラスのOnActionExecutingで、認証されていないリクエストの場合はリクエスト先のURLを変更している。ここでは/Account/Login/に転送している。
実際の使用方法は下記の通りだ。
-ClipController.cs-
1 2 3 4 5 6 | [RequiredAuth] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Comment( int clipId, string commentText) { // code here... } |
上記の例はCommentというActionに対するFilterになる。ActionFilterはController全体に対しても付与できる。
以上で既存のコード部分に手を加えるでなく、簡単に認証が必要なActionを実装することができた。このほかにもRoleベースのフィルタリングなども可能なので、ネタが続くだけ紹介していきたいと思う。
0 件のコメント:
コメントを投稿