문제

매우 고유 한 두 가지 유형의 사용자가있는 ASP.NET MVC를 사용하여 웹 응용 프로그램을 구축하고 있습니다. 나는 예를 들고 한 유형이 콘텐츠 제작자 (게시자)이고 다른 유형은 콘텐츠 소비자 (가입자)라고 말할 것입니다.

내 내장 ASP.NET 인증 항목을 사용할 계획이 아닙니다. 사용자 유형의 분리는 이분법이므로 게시자이거나 가입자가 아니기 때문입니다. 따라서 빌드 인 승인은 필요한 것보다 더 복잡합니다. 또한 MySQL을 사용할 계획입니다.

나는 그것들을 열거 필드 (기술적으로 int 필드)와 같은 테이블에 보관하는 것에 대해 생각하고있었습니다. 그런 다음 해당 페이지에 필요한 사용자 유형을 통과 할 수있는 CustomAuthorizationAtribute를 작성하십시오.

예를 들어, PublishContent 페이지에는 userType == userType.publisher가 필요하므로 게시자 만 액세스 할 수 있습니다. 따라서이 속성을 작성하면 표준 사용자 필드 (Iprincipal 유형)가 포함 된 HTTPContextBase에 액세스 할 수 있습니다. 이 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 양식 인증을 사용하지만 귀하의 요구에 맞게 사용자 정의합니다.

따라서 iprincipal 인터페이스를 구현하려면 사용자 클래스를 얻은 다음 자신의 사용자 정의 쿠키 처리를 작성해야합니다. 그런 다음 내장 된 [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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top