Program Tip

ASP.NET MVC의 사용자 인증 및 권한 부여

programtip 2020. 12. 5. 10:27
반응형

ASP.NET MVC의 사용자 인증 및 권한 부여


ASP.NET MVC에서 사용자 권한 부여 / 인증을위한 가장 좋은 방법은 무엇입니까?

실제로 두 가지 접근 방식이 있습니다.

  • 기본 제공 ASP.NET 인증 시스템을 사용합니다.
  • 내 사용자, 권한, 사용자 그룹 테이블 등이있는 사용자 정의 시스템을 사용하십시오.

두 번째 옵션을 선호합니다. User가 내 도메인 모델의 일부이기 때문입니다 (그리고 ASP.NET의 기본 제공 항목에 대한 경험 전혀 없습니다 ).하지만 사람들이이 분야에서 무엇을했는지 듣고 싶습니다.


실제로 세 번째 접근 방식이 있습니다. asp.net 멤버십 기능은 공급자 모델을 기반으로합니다. 사용자 지정 공급자를 작성할 수 있으므로 데이터 저장 방법에 대한 고유 한 구현을 제공 할 수 있지만 asp.net 멤버 자격의 많은 이점을 유지할 수 있습니다.

주제에 대한 일부 기사 :

http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx

http://www.asp.net/learn/videos/video-189.aspx

http://www.15seconds.com/issue/050216.htm

http://davidhayden.com/blog/dave/archive/2007/10/11/CreateCustomMembershipProviderASPNETWebsiteSecurity.aspx


사용자 지정으로 이동하십시오. MembershipProvider는 내 취향에 비해 너무 무겁습니다. 예, 간단한 방법으로 구현할 수 있지만 NotSupportedException 또는 NotImplementedException의 악취납니다 .

완전히 사용자 지정 구현으로 IPrincipal, IIdentity 및 FormsAuth를 계속 사용할 수 있습니다. 그리고 자신의 로그인 페이지 등을 수행하는 것이 얼마나 어렵습니까?


가장 쉬운 방법은 asp.net 사용자 이름을 역할 이름으로 사용하는 것입니다. 권한을 처리하기 위해 고유 한 authorizarion 속성을 작성할 수 있습니다.

public class CustomAuthorizationAttribute:AuthorizeAttribute
{
    public CustomAuthorizationAttribute():base()
    {
        Users = "registereduser";
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //You must check if the user has logged in and return true if he did that.
        return (bool)(httpContext.Session["started"]??false); 

    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.HttpContext.Response.Redirect("SessionManagement/Index/?returningURL=" + 
            filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.ToString()));

    }

}

코드는 AuthorizeCore를 처리하여 사용자가 세션을 시작한 경우 true를 반환하고 HandleUnauthorizedRequest를 처리하여 사용자를 로그인 페이지로 리디렉션해야합니다 (선택적으로 반환 URL을 첨부 할 수 있음).

그런 다음 권한이 필요한 컨트롤러 메서드에서 속성을 설정합니다.

public class SecretPageController {
    [CustomAuthorizationAttribute]
    ActionResult Index() {
        //Method that requires authorization
        return View();
    }

}

또한 웹 구성에서 인증 방법을 "양식"으로 설정하십시오.

Web.config :

  <authentication>
      <forms timeout="120"></forms>
  </authentication>

제어 장치:

public SessionManagementController:Controller {
    public ActionResult Index(string returningURL)
    {
        return View("Index", new SessionModel() { ReturningURL = returningURL});
    }
    [HttpPost]        
    public ActionResult Index(SessionModel mod)
    {
        if (UserAuthenticated(mod.UserName, mod.Password))
        {
            FormsAuthentication.SetAuthCookie("registereduser", false);
            if (mod.UrlRetorno != null)
            {
                return Redirect(mod.ReturningURL);                    
            }
            return RedirectToAction("Index", "StartPage");
        }
        mod.Error = "Wrong User Name or Password";
        return View(mod);
    }
    bool UserAuthenticated(string userName, string password) {
       //Write here the authentication code (it can be from a database, predefined users,, etc)
        return true;
    }

    public ActionResult FinishSession()
    {
        HttpContext.Session.Clear();//Clear the session information
        FormsAuthentication.SignOut();
        return View(new NotificacionModel() { Message = "Session Finished", URL = Request.Url.ToString() });
    }

}

컨트롤러에서 사용자가 사용자 이름과 비밀번호를 입력 할 때 양식 인증 쿠키를 TRUE (FormsAuthentication.SetAuthCookie ( "registereduser", true))로 설정하여 사용자 이름 (예제에서는 registereduser)이 인증되도록 신호를 보냅니다. 그런 다음 사용자가 로그 아웃하고 ASP.NET에 FormsAuthentication.SignOut ()을 호출하여 그렇게하도록 지시합니다.

모델:

class SessionModel {
    public string UserName {get;set;}
    public string Password {get;set;}
    public string Error {get;set;}
}  

모델을 사용하여 사용자 데이터를 저장하십시오.

보기 (SessionModel 유형을 나타냄) :

        <div class="editor-label">
            <%: Html.LabelFor(model => model.UserName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.UserName) %>
            <%: Html.ValidationMessageFor(model => model.UserName) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Password) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Password) %>
            <%: Html.ValidationMessageFor(model => model.Password) %>
        </div>
        <div class="field-validation-error"><%:Model==null?"":Model.Error??"" %></div>
        <%:Html.HiddenFor(model=>model.ReturningURL) %>
        <input type="submit" value="Log In" />

Use a view to get the data. In this example, there is a hidden field to store the returning URL

I hope this helps (I had to translate the code, so I'm not sure if it is 100% correct).


Yet another approach is to use ASP.NET membership for authentication, link your User class to ASP.NET members, and use your User class for more granular permissions. We do this, because it allows changing authentication providers very easily, while still retaining the ability to have a complex permission system.

In general, it's worth remembering that authentication/identity and storing permissions are not necessarily the same problem.


You may be interested in RPX for a free API to authenticate your users

http://blog.maartenballiauw.be/post/2009/07/27/Authenticating-users-with-RPXNow-(in-ASPNET-MVC).aspx

Try the ASP.Net MVC Membership Starter Kit for an administrative API

Screenshots

http://www.squaredroot.com/2009/08/07/mvcmembership-release-1-0/

Old locations changesets (historic)

http://mvcmembership.codeplex.com/SourceControl/list/changesets

New Location:

http://github.com/TroyGoode/MembershipStarterKit


This is a forth approach. Using the web matrix security classes you can use simple membership provider which can use EF so users and roles can be part of your domain model but also part of the IPrincipal and IIdentity MVC helpers.

I have created an example Github project to see how this can be used with automated self registration and email signup / password reset and the like.

참고URL : https://stackoverflow.com/questions/524086/user-authentication-and-authorisation-in-asp-net-mvc

반응형