簡體   English   中英

ASP.NET MVC自定義授權

[英]ASP.NET MVC custom authorization

我正在使用具有兩種截然不同類型的用戶的ASP.NET MVC構建Web應用程序。 我將舉一個例子,說一種類型是內容生產者(發布者),另一種類型是內容消費者(訂閱者)。

我不打算使用內置的ASP.NET授權,因為用戶類型的分離是二分法,您既是發布者又是訂閱者,而不是兩者。 因此,內置授權比我需要的更為復雜。 另外,我正計划使用MySQL。

我正在考慮將它們與枚舉字段(從技術上講是int字段)存儲在同一張表中。 然后創建一個CustomAuthorizationAttribute,在其中傳遞該頁面所需的userType。

例如,PublishContent頁面將需要userType == UserType.Publisher,因此只有發布者才能訪問它。 因此,創建此屬性使我可以訪問HttpContextBase,它包含標准的User字段(類型為IPrincipal)。 如何將我的UserType字段添加到此IPrincipal? 因此,我的屬性如下所示:

public class PublisherAuthorizationAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        if (!httpContext.User.Identity.UserType == UserTypes.Publisher)
            return false;

        return true;
    }
}

還是有人認為我的整個方法有缺陷?

我仍然會使用內置的ASP.NET表單身份驗證,只是根據您的需要對其進行自定義。

因此,您需要獲取User類以實現IPrincipal接口,然后編寫自己的自定義Cookie處理。 然后,您只需使用內置的[Authorize]屬性即可。

目前我有類似以下內容...

在我的global.asax中

protected void Application_AuthenticateRequest()
{
    HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);
    if (cookie == null)
        return;

    bool isPersistent;
    int webuserid = GetUserId(cookie, out isPersistent);

    //Lets see if the user exists
    var webUserRepository = Kernel.Get<IWebUserRepository>();

    try
    {
        WebUser current = webUserRepository.GetById(webuserid);

        //Refresh the cookie
        var formsAuth = Kernel.Get<IFormsAuthService>();

        Response.Cookies.Add(formsAuth.GetAuthCookie(current, isPersistent));
        Context.User = current;
    }
    catch (Exception ex)
    {
        //TODO: Logging
        RemoveAuthCookieAndRedirectToDefaultPage();
    }
}

private int GetUserId(HttpCookie cookie, out bool isPersistent)
{
    try
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
        isPersistent = ticket.IsPersistent;
        return int.Parse(ticket.UserData);
    }
    catch (Exception ex)
    {
        //TODO: Logging

        RemoveAuthCookieAndRedirectToDefaultPage();
        isPersistent = false;
        return -1;
    }
}

AccountController.cs

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(LogOnForm logOnForm)
{
    try
    {
        if (ModelState.IsValid)
        {
            WebUser user = AccountService.GetWebUserFromLogOnForm(logOnForm);

            Response.Cookies.Add(FormsAuth.GetAuthCookie(user, logOnForm.RememberMe));

            return Redirect(logOnForm.ReturnUrl);
        }
    }
    catch (ServiceLayerException ex)
    {
        ex.BindToModelState(ModelState);
    }
    catch
    {
        ModelState.AddModelError("*", "There was server error trying to log on, try again. If your problem persists, please contact us.");
    }

    return View("LogOn", logOnForm);
}

最后是我的FormsAuthService:

public HttpCookie GetAuthCookie(WebUser webUser, bool createPersistentCookie)
{
    var ticket = new FormsAuthenticationTicket(1,
                                               webUser.Email,
                                               DateTime.Now,
                                               DateTime.Now.AddMonths(1),
                                               createPersistentCookie,
                                               webUser.Id.ToString());

    string cookieValue = FormsAuthentication.Encrypt(ticket);

    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
                         {
                             Path = "/"
                         };

    if (createPersistentCookie)
        authCookie.Expires = ticket.Expiration;

    return authCookie;
}

HTHS
查爾斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM