Domanda

Sto creando un'applicazione Web utilizzando ASP.NET MVC che ha due tipi molto distinti di utenti. Ne escogiterò un esempio e dirò che un tipo è produttori di contenuti (editori) e un altro sono consumatori di contenuti (abbonati).

Non ho intenzione di utilizzare la roba di autorizzazione ASP.NET integrata, perché la separazione dei miei tipi di utente è una dicotomia, sei un editore o un abbonato, non entrambi. Pertanto, l'autorizzazione di build-in è più complessa del necessario. Inoltre sto pensando di usare MySQL.

Stavo pensando di memorizzarli nella stessa tabella con un campo enum (tecnicamente un campo int). Quindi creando un CustomAuthorizationAttribute, dove passerei il tipo utente necessario per quella pagina.

Ad esempio, la pagina PublishContent richiederebbe userType == UserType.Publisher, quindi solo gli editori potrebbero accedervi. Quindi, la creazione di questo attributo mi dà accesso a HttpContextBase, che contiene il campo Utente standard (di tipo IPrincipal). Come posso ottenere il mio campo UserType su questo IPrincipal? Quindi, il mio attributo sarebbe simile a:

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;
    }
}

O qualcuno pensa che il mio intero approccio sia difettoso?

È stato utile?

Soluzione

Utilizzerei ancora l'autenticazione dei moduli ASP.NET integrata ma la personalizzerei in base alle tue esigenze.

Quindi dovrai ottenere la tua classe Utente per implementare l'interfaccia IPrincipal e quindi scrivere la tua gestione personalizzata dei cookie. Quindi puoi semplicemente usare l'attributo [Autorizza] incorporato.

Attualmente ho qualcosa di simile al seguente ...

Nel mio 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);
}

E infine il mio 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
Charles

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top