4

私の Web アプリケーションでは、登録済みのユーザーが新しいコンテンツを追加し、後で編集することができます。コンテンツの作成者だけが編集できるようにしたい。ログに記録されたユーザーが作成者と同じかどうかを確認するすべてのアクション メソッドでコードを手動で記述する以外に、これを行うスマートな方法はありますか? コントローラー全体に使用できる属性はありますか?

4

2 に答える 2

6

コントローラー全体に使用できる属性はありますか?

Authorizeはい、カスタム属性で属性を拡張できます。

public class AuthorizeAuthorAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            // the user is either not authenticated or
            // not in roles => no need to continue any further
            return false;
        }

        // get the currently logged on user
        var username = httpContext.User.Identity.Name;

        // get the id of the article that he is trying to manipulate
        // from the route data (this assumes that the id is passed as a route
        // data parameter: /foo/edit/123). If this is not the case and you 
        // are using query string parameters you could fetch the id using the Request
        var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string;

        // Now that we have the current user and the id of the article he
        // is trying to manipualte all that's left is go ahead and look in 
        // our database to see if this user is the owner of the article
        return IsUserOwnerOfArticle(username, id);
    }

    private bool IsUserOwnerOfArticle(string username, string articleId)
    {
        throw new NotImplementedException();
    }
}

その後:

[HttpPost]
[AuthorizeAuthor]
public ActionResult Edit(int id)
{
    ... perform the edit
}
于 2012-04-09T06:40:48.597 に答える
0

私は...するだろう:

  1. コンテンツ レコードに対して db.aspnet_Users 列の UserId (Guid) を保存します。
  2. 現在のユーザー Guid を保存されたコンテンツ ユーザー Guid に対して検証する、コンテンツ モデルの拡張メソッドを記述します。
  3. 管理者ログインのこの機能をオーバーライドするコードをいくつか書きます (管理者ロールを作成します)。
于 2012-04-08T17:43:49.540 に答える