2016-09-28 7 views
0

Microsoft.ASPNET.Identityプロバイダを使用していて、カスタムプリンシパルを設定したいとします。私が代わりにアイデンティティと校長と一緒に遊んのientityプロバイダASP.NET IDプロバイダのカスタムプリンシパルを設定する

+0

なぜ必要なのですか?それをするには? –

+0

だから私は各コントローラアクション内のオブジェクトにアクセスし、毎回 – dagda1

答えて

0

と似た何かを行うことができ、私はどうしたらどのように

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
    { 
     HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 

     if(authCookie != null) 
     { 
      using (var db = new GSCM.Logic.GSCMDatabase()) 
      { 
       FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); 
       var id = new GenericIdentity(ticket.Name); 
       var principal = new VmUserLogin(id); 
       var found = db.LoadInternalUser(ticket.Name); 
       if(found != null) 
       { 
        Mapper.Map(found, principal); 
       } 

       HttpContext.Current.User = principal; 
      } 
     } 
    } 

:以前FomrsAuthenticationで、私はこのような何かをやっているだろう

は、アプリケーションで必要なユーザー情報のためのインタフェースを作成します

public interface ICurrentUserService 
    { 
     VmUserLogin CurrentUser{get; } 
    } 

だけ注入し、あなたのコントローラ内部で、で最後ICurrentUserServiceあなたはIoCコンテナを使用する必要が

public class MyController : Controller 
    { 
     private readonly ICurrentUserService _currentUserService; 

     public MyController(ICurrentUserService currentUserService) 
     { 
      _currentUserService = currentUserService; 
     } 

     public ActionResult Index() 
     { 
      return View(_currentUserService.CurrentUser); 
     } 
} 

public class HttpLoggedInUserService : ICurrentUserService 
    { 
     private readonly IUserRepository _userRepository; 
     private VmUserLogin _currentUser; 

     public HttpLoggedInUserService(IUserRepository userRepository) 
     { 
      _userRepository= userRepository; 
     } 
     public VmUserLogin CurrentUser 
     { 
      get 
      { 
       if (_currentUser == null) 
       { 
        if (HttpContext.Current.Items.Contains("CurrentUser")) 
         return HttpContext.Current.Items["CurrentUser"] as VmUserLogin ; 

        var loginName = HttpContext.Current.User.Identity.Name.ToLower(); 
        _currentUser = _userRepository.GetByLoginName(loginName); 

        HttpContext.Current.Items["CurrentUser"] = _currentUser ; 
       } 

       if (_currentUser == null) 
       { 
        HttpContext.Current.Response.Redirect("/NoAccess"); 
        return null; 
       } 

       return _currentUser ; 
      } 
     } 
    } 

以下のようにWebプロジェクト内でこのインタフェースの実装を作成し、このソリューション必要に応じてコントローラ、ビジネス層、さらにはデータアクセス層に現在ログインしているユーザーを注入することができます。これらの層のどれもがどのように取得されたかを知ることはできません

+0

をロードする必要はありませんが、それを使用したいすべてのアクションで呼び出す必要があります – dagda1

+0

データベースからユーザーを一度取得し、キャッシュされます要求のライフサイクル中の残りのコールについては、クッキーを使用したい場合やセッション中に保存することもできます。 –

関連する問題