ASP.NETMVC-カスタムIIdentityまたはIPrincipalを設定します



Asp Net Mvc Set Custom Iidentity



解決:

これが私のやり方です。

IIdentityとIPrincipalの両方を実装する必要がないため、IIdentityの代わりにIPrincipalを使用することにしました。



  1. インターフェースを作成する

    インターフェイスICustomPrincipal:IPrincipal {int Id {get;設定; } string FirstName {get;設定; } string LastName {get;設定; }}
  2. CustomPrincipal



    public class CustomPrincipal:ICustomPrincipal {public IIdentity Identity {get;プライベートセット; } public bool IsInRole(string role){falseを返す; } public CustomPrincipal(string email){this.Identity = new GenericIdentity(email); } public int Id {get;設定; } public string FirstName {get;設定; } public string LastName {get;設定; }}
  3. CustomPrincipalSerializeModel-カスタム情報をFormsAuthenticationTicketオブジェクトのuserdataフィールドにシリアル化するため。

    public class CustomPrincipalSerializeModel {public int Id {get;設定; } public string FirstName {get;設定; } public string LastName {get;設定; }}
  4. ログインメソッド-カスタム情報を使用してCookieを設定する

    if(Membership.ValidateUser(viewModel.Email、viewModel.Password)){var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First(); CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel(); serializeModel.Id = user.Id; serializeModel.FirstName = user.FirstName; serializeModel.LastName = user.LastName; JavaScriptSerializerシリアライザー=新しいJavaScriptSerializer(); string userData = serializer.Serialize(serializeModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1、viewModel.Email、DateTime.Now、DateTime.Now.AddMinutes(15)、false、userData);文字列encTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName、encTicket); Response.Cookies.Add(faCookie); RedirectToAction( 'Index'、 'Home');を返します。 }
  5. Global.asax.cs-Cookieを読み取り、HttpContext.Userオブジェクトを置き換えます。これは、PostAuthenticateRequestをオーバーライドすることによって行われます。



    protected void Application_PostAuthenticateRequest(Object sender、EventArgs e){HttpCookie authCookie = Request.Cookies [FormsAuthentication.FormsCookieName]; if(authCookie!= null){FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializerシリアライザー=新しいJavaScriptSerializer(); CustomPrincipalSerializeModel serializeModel = serializer.Deserialize(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.Id = serializeModel.Id; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; HttpContext.Current.User = newUser; }}
  6. Razorビューでのアクセス

    @((User as CustomPrincipal).Id)@((User as CustomPrincipal).FirstName)@((User as CustomPrincipal).LastName)

およびコード内:

(CustomPrincipalとしてのユーザー).Id(CustomPrincipalとしてのユーザー).FirstName(CustomPrincipalとしてのユーザー).LastName

コードは一目瞭然だと思います。そうでない場合は、私に知らせてください。

さらに、アクセスをさらに簡単にするために、ベースコントローラーを作成し、返されたUserオブジェクト(HttpContext.User)をオーバーライドできます。

public class BaseController:Controller {protected virtual new CustomPrincipal User {get {return HttpContext.User as CustomPrincipal; }}}

次に、コントローラーごとに:

パブリッククラスAccountController:BaseController {// ...}

これにより、次のようなコードでカスタムフィールドにアクセスできるようになります。

User.Id User.FirstName User.LastName

ただし、これはビュー内では機能しません。そのためには、カスタムWebViewPage実装を作成する必要があります。

public abstract class BaseViewPage:WebViewPage {public virtual new CustomPrincipal User {get {return base.User as CustomPrincipal; }}} public abstract class BaseViewPage:WebViewPage {public virtual new CustomPrincipal User {get {return base.User as CustomPrincipal; }}}

Views /web.configでデフォルトのページタイプにします。

  

ビューでは、次のようにアクセスできます。

@ User.FirstName @ User.LastName 

ASP.NET MVCについて直接話すことはできませんが、ASP.NET Webフォームの場合、秘訣は作成することです。FormsAuthenticationTicketを作成し、ユーザーが認証されたらCookieに暗号化します。このように、データベースを1回(またはADまたは認証の実行に使用しているもの)呼び出すだけで、後続の各要求はCookieに保存されているチケットに基づいて認証されます。

これに関する良い記事:http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html(壊れたリンク)

編集:

上記のリンクが壊れているので、上記の回答でLukePのソリューションをお勧めします:https://stackoverflow.com/a/10524305-受け入れられた回答をその回答に変更することもお勧めします。

編集2: 壊れたリンクの代替:https://web.archive.org/web/20120422011422/http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html


これは仕事を成し遂げるための例です。 bool isValidは、いくつかのデータストア(ユーザーデータベースなど)を調べることによって設定されます。 UserIDは、私が管理しているIDです。メールアドレスなどの追加情報をユーザーデータに追加できます。

protected void btnLogin_Click(object sender、EventArgs e){//今のところハードコードされていますbool isValid = true; if(isValid){string userData = String.Empty; userData = userData + 'UserID =' + userID; FormsAuthenticationTicketチケット=新しいFormsAuthenticationTicket(1、ユーザー名、DateTime.Now、DateTime.Now.AddMinutes(30)、true、userData);文字列encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName、encTicket); Response.Cookies.Add(faCookie); //そして、ユーザーを見出しの場所に送信しますstring redirectUrl = FormsAuthentication.GetRedirectUrl(username、false); Response.Redirect(redirectUrl); }}

golbal asaxに次のコードを追加して、情報を取得します

protected void Application_AuthenticateRequest(Object sender、EventArgs e){HttpCookie authCookie = Request.Cookies [FormsAuthentication.FormsCookieName]; if(authCookie!= null){//フォーム認証Cookieを抽出しますFormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); // Identityオブジェクトを作成します// CustomIdentityはSystem.Web.Security.IIdentityを実装しますCustomIdentityid = GetUserIdentity(authTicket.Name); // CustomPrincipalはSystem.Web.Security.IPrincipalを実装しますCustomPrincipalnewUser = new CustomPrincipal(); Context.User = newUser; }}

後で情報を使用する場合は、次のようにカスタムプリンシパルにアクセスできます。

(CustomPrincipal)this.Userまたは(CustomPrincipal)this.Context.User

これにより、カスタムユーザー情報にアクセスできるようになります。