5

私のASP.NETMVCアプリケーションでは、ユーザーが特定のコントローラーにアクセスできるかどうかを確認しようとしています。これは、次のように承認データの注釈によって制限されています。

[Authorize(Roles = "user")]

以下を確認するためにOnAuthorizationをオーバーライドしようとしています:-

  • リクエストが認証されている場合(これはうまく機能します)
  • ユーザーが要求されたビューへのアクセスを許可されている場合(これは機能しません)

私のユーザーロールは、私が作成したSessionManagerオブジェクトに保存されます-SessionManager.ActiveUser.Roles

これが私が擬似コードの形で持っているものですが、誰かが私がこれを正しくするのを手伝ってくれるなら、私はそれを本当に感謝します。

public class HomeBaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            // these values combined are our roleName 

            bool isAuthorised = context.HttpContext.User.IsInRole(context.RequestContext.HttpContext.User.Identity.); 


            if (!context.HttpContext.User.IsInRole(---the roles associated with the requested controller action (e.g. user)---))
            {
                var url = new UrlHelper(context.RequestContext);
                var logonUrl = url.Action("LogOn", "SSO", new { reason = "youAreAuthorisedButNotAllowedToViewThisPage" });
                context.Result = new RedirectResult(logonUrl);

                return;
            } 
        }
    }
4

1 に答える 1

11

ProASP.NET MVC3 Bookに従ってOnAuthorizationをオーバーライドする限り、このメソッドのデフォルトの実装はOutputCache Filterを使用してキャッシュされたコンテンツを安全に処理するため、オーバーライドすることはお勧めしません。

カスタム認証(Forms Authを使用)と承認(ロールプロバイダーロジックを使用)を探している場合は、以下がアプリケーションを保護する方法です。

編集:次のロジックは、組み込みのフォーム認証とロールマネージャーを使用します。ユーザーが認証および承認されると、ユーザーIDを使用して、認証(User.Identity.IsAuthenticated)とロールUser.IsInRole( "admin")の両方を確認できます。

Web.Configの場合:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="15" slidingExpiration="true" enableCrossAppRedirects="false" protection="All" />
</authentication>
<roleManager enabled="true" defaultProvider="MyRolesProvider" cacheRolesInCookie="true" cookieProtection="All">
  <providers>
    <clear />
    <add name="MyRolesProvider" type="MyApp.Library.CustomRolesProvider" />
  </providers>
</roleManager>

ロール認証の場合RoleProviderを拡張し、必要に応じてメソッドをオーバーライドします。

public class CustomRolesProvider : RoleProvider
{
    public override string[] GetRolesForUser(string username)
    {
       // You need to return string of Roles Here which should match your role names which you plan to use.
       //Some Logic to fetch roles after checking if User is Authenticated...    

        return new string[] { "admin" , "editor" };
    }

    //Rest all of them I have kept not implemented as I did not need them...


}

コントローラでこれを使用できるようになりました。

 [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
    ....

    }

認証については、カスタム認証チェックを実装しましたが、フォーム認証を引き続き使用しています。

//This one calls by Custom Authentication to validate username/password
public ActionResult LogOn(LogOnViewModel model, string returnUrl)
{
    if(Authenticate("test","test"))
    {
     .......
    }
}

public bool Authenticate(string username, string password)
{
   //Authentication Logic and Set the cookie if correct else false.
   //..... your logic....
   //.....

   FormsAuthentication.SetAuthCookie(username, false);
}
于 2012-06-27T18:16:47.733 に答える