Question

Je construis une application Web à l'aide d'ASP.NET MVC qui comporte deux types d'utilisateurs très distincts. Je vais citer un exemple et dire qu'un type est celui des producteurs de contenu (éditeurs) et un autre des consommateurs de contenu (abonnés).

Je ne prévois pas utiliser les éléments d'autorisation ASP.NET intégrés, car la séparation de mes types d'utilisateurs est une dichotomie: vous êtes un éditeur ou un abonné, pas les deux. L’autorisation d’installation est donc plus complexe que ce dont j’ai besoin. De plus, je prévois d’utiliser MySQL.

Je pensais à les stocker dans la même table avec un champ enum (techniquement un champ int). Ensuite, créez un CustomAuthorizationAttribute, dans lequel je passerais le userType requis pour cette page.

Par exemple, la page PublishContent nécessiterait userType == UserType.Publisher afin que seuls les éditeurs puissent y accéder. Ainsi, créer cet attribut me donne accès à HttpContextBase, qui contient le champ Utilisateur standard (de type IPrincipal). Comment puis-je obtenir mon champ UserType sur cet IPrincipal? Alors, mon attribut ressemblerait à ceci:

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

Ou bien, y a-t-il quelqu'un qui pense que toute mon approche est défectueuse?

Était-ce utile?

La solution

J'utiliserais encore l'authentification par formulaire ASP.NET intégrée, mais l'adapterais simplement à vos besoins.

Vous devez donc demander à votre classe d'utilisateurs d'implémenter l'interface IPrincipal, puis d'écrire votre propre gestion des cookies personnalisée. Ensuite, vous pouvez simplement utiliser l'attribut [Autoriser] intégré.

Actuellement, j'ai quelque chose de similaire au suivant ...

Dans mon 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);
}

Et enfin mon 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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top