2011-01-27 11 views
0

これまでに登録/ログインシステムを実装したことはありませんでしたので、C#/ ASP.NET(ASP.NETの内蔵機能を使用していません。メンバーシッププロバイダ)。私が少し不明なのは、セッション中またはセッション間にユーザーをログインさせ続けるためにセッション/クッキーを利用する方法です。あなたは、ユーザーが要求したが、原因認証に訪問することができませんでしたか、ユーザーがあなたにリダイレクトされる場所の制御を維持したい場合はSetAuthCookieセッション用のユーザシステムを正しく実装する方法

+1

うまくいけば、これはプロダクションコードにはなりませんか? – BrokenGlass

+0

これはもちろん学習目的です。 –

答えて

0

そのを使用することができますページにリダイレクトするRedirectFromLoginを使用することができます

protected void Login_User(object sender, EventArgs e) 
{ 
    string username = usernameField.Text; 
    string password = passwordField.Text; 
    User user = UserRepository.FindUser(username); 
    if (user != null) 
    { 
     if (user.Password.Equals(Hash(password))) 
     { 
      // How do I properly login the user and keep track of his session? 
     } 
     else 
      Response.Write("Wrong password!"); 
    } 
    else 
     Response.Write("User does not exist!"); 
} 
+0

どこでHttpContext.Current.Userを再割り当てしますか? global.asaxでApplication_AuthenticateRequestイベントを使用して各リクエストを確認しようとしましたが、セッションはこのイベントに存在しません。 – TDaver

+0

私はPostAuthenticateRequest(global.asax)で割り当てます。単にHttpContext.Current.User =新しいWebUser(...)を入力します。セッションに割り当てる必要はありません – Bonshington

0

適切なログインシステムにはかなり複雑です。

  1. はSystem.Security.Principal.IPrincipal
  2. 割り当てIPrincipal誘導体
  3. System.Web.HttpConext.Current.User
  4. にSystem.Security.Principal.IIdentity inherrit別のクラスを継承するクラスを作成しますクッキーを使用したくない場合は、IPrincipalをSessionに配置してください。
  5. HttpContext.Current.Userが失われた場合、セッションからの取得(最初のイベント、たとえばpage_init)によって再割り当てします。私のコードのために、私はクッキーとしてFormsAuthenticationTicketを使用し、イベントにGlobal.asaxのに再割り当てPostAuthenticateRequest

HttpContext.Current.Userを使用しての良いところは、uはmethod属性をマークすることができます。

[Authorize] // authorized user only 
public void btn_click(...){...} 

iは、通常のasp.netのためかわからないが、それは

をuはSystem.Web.Securitiy.FormsAuthenticationTicketを試し、クッキーを使用する場合は、ASP MVC

に非常によく働くとをFormsAuthenticationサンプル

public class WebUser:System.Security.Principal.IPrincipal 
{ 
    ... 
    public System.Security.Principal.IIdentity Identity{get; private set;} 
    public WebUser(...) 
    { 
    this.Identity = new WebIdentity(...); 
    HttpContext.Current.User = this; 
    } 
} 
public class WebIdentity : System.Security.Principal.IIdentity 
{ 
    ... 
} 

public void Login(...) 
{ 
    var newUser = new WebUser(...); 
} 
0

使用この:

public class FormsAuthenticationService 
{ 
    public void SignIn(string userName, bool createPersistentCookie) 
    { 
     if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); 

     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
    } 

    public void SignOut() 
    { 
     FormsAuthentication.SignOut(); 
    } 
} 
関連する問題