670

かなり単純なことを行う必要があります。ASP.NET MVC アプリケーションで、カスタム IIdentity / IPrincipal を設定したいと考えています。どちらが簡単/より適しています。のようなものを呼び出すことができるように、デフォルトを拡張したいと思いUser.Identity.IdますUser.Identity.Role。派手なものはなく、いくつかの追加のプロパティです。

たくさんの記事や質問を読みましたが、実際よりも難しくしているように感じます. 簡単だと思いました。ユーザーがログオンする場合、カスタム IIdentity を設定したいと考えています。それでApplication_PostAuthenticateRequest、global.asax に実装しようと思いました。ただし、それはすべての要求で呼び出され、データベースからすべてのデータを要求してカスタム IPrincipal オブジェクトを配置するすべての要求でデータベースへの呼び出しを行いたくありません。それも非常に不必要で、遅く、間違った場所 (そこでデータベース呼び出しを行う) にあるように見えますが、私は間違っている可能性があります。または、そのデータはどこから来るのでしょうか?

そこで、ユーザーがログインするたびに、必要な変数をセッションに追加し、Application_PostAuthenticateRequestイベント ハンドラーのカスタム IIdentity に追加できると考えました。しかし、私Context.Sessionnullそこにいるので、それも仕方ありません。

私はこれに1日取り組んできましたが、何かが足りないと感じています。これは難しいことではありませんよね?また、これに付属するすべての (半) 関連のものに少し混乱しています。MembershipProvider, MembershipUser, RoleProvider, ProfileProvider, IPrincipal, .... このすべてが非常に混乱していると思うのIIdentityFormsAuthentication私だけですか?

余分なデータを IIdentity に保存するためのシンプルでエレガントで効率的なソリューションを誰かが教えてくれたら、それは素晴らしいことです! SO にも同様の質問があることは知っていますが、必要な答えがそこにある場合は、見落としていたに違いありません。

4

9 に答える 9

857

これが私のやり方です。

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

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

    interface ICustomPrincipal : IPrincipal
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
    }
    
  2. カスタムプリンシパル

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

    public class CustomPrincipalSerializeModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
  4. LogIn メソッド - カスタム情報を使用して 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 serializer = new JavaScriptSerializer();
    
        string userData = serializer.Serialize(serializeModel);
    
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                 1,
                 viewModel.Email,
                 DateTime.Now,
                 DateTime.Now.AddMinutes(15),
                 false,
                 userData);
    
        string encTicket = FormsAuthentication.Encrypt(authTicket);
        HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        Response.Cookies.Add(faCookie);
    
        return 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 serializer = new JavaScriptSerializer();
    
            CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(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)
    

そしてコードで:

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

コードは自明だと思います。そうでない場合は、お知らせください。

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

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

次に、各コントローラーについて:

public class 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<TModel> : WebViewPage<TModel>
{
    public virtual new CustomPrincipal User
    {
        get { return base.User as CustomPrincipal; }
    }
}

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

<pages pageBaseType="Your.Namespace.BaseViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>

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

@User.FirstName
@User.LastName
于 2012-05-09T21:24:50.230 に答える
111

ASP.NET MVC について直接話すことはできませんが、ASP.NET Web フォームの場合FormsAuthenticationTicket、ユーザーが認証されたら、それを作成して Cookie に暗号化するのがコツです。この方法では、データベース (または AD など、認証を実行するために使用するもの) を 1 回呼び出すだけで済み、その後の各要求は、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

于 2009-06-30T15:28:27.393 に答える
64

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

protected void btnLogin_Click(object sender, EventArgs e)
{         
    //Hard Coded for the moment
    bool isValid=true;
    if (isValid) 
    {
         string userData = String.Empty;
         userData = userData + "UserID=" + userID;
         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), true, userData);
         string encTicket = FormsAuthentication.Encrypt(ticket);
         HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
         Response.Cookies.Add(faCookie);
         //And send the user where they were heading
         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)
    {
        //Extract the forms authentication cookie
        FormsAuthenticationTicket authTicket = 
               FormsAuthentication.Decrypt(authCookie.Value);
        // Create an Identity object
        //CustomIdentity implements System.Web.Security.IIdentity
        CustomIdentity id = GetUserIdentity(authTicket.Name);
        //CustomPrincipal implements System.Web.Security.IPrincipal
        CustomPrincipal newUser = new CustomPrincipal();
        Context.User = newUser;
    }
}

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

(CustomPrincipal)this.User
or 
(CustomPrincipal)this.Context.User

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

于 2009-11-20T10:55:35.707 に答える
16

MVC は、コントローラー クラスからハングする OnAuthorize メソッドを提供します。または、カスタム アクション フィルターを使用して承認を実行することもできます。MVC を使用すると、非常に簡単に実行できます。これについてのブログ記事をここに投稿しました。http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0

于 2011-06-23T12:21:43.827 に答える
11

ビューで使用するためにいくつかのメソッドを @User に接続する必要がある場合の解決策を次に示します。深刻なメンバーシップのカスタマイズに対する解決策はありませんが、元の質問がビューのみに必要な場合は、おそらくこれで十分でしょう。以下は、authorizefilter から返された変数をチェックするために使用され、一部のリンクが表示されるかどうかを確認するために使用されます (いかなる種類の承認ロジックやアクセス許可にも使用されません)。

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Security.Principal;

    namespace SomeSite.Web.Helpers
    {
        public static class UserHelpers
        {
            public static bool IsEditor(this IPrincipal user)
            {
                return null; //Do some stuff
            }
        }
    }

次に、web.config 領域に参照を追加し、ビューで以下のように呼び出します。

@User.IsEditor()
于 2013-03-09T23:10:04.923 に答える
2

ページの背後にあるコードでのアクセスを簡素化したい場合は、Webフォームユーザー(MVCではない)のLukePコードに加えて、以下のコードをベースページに追加し、すべてのページでベースページを派生させます。

Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
    Get
        Return DirectCast(MyBase.User, CustomPrincipal)
    End Get
End Property

したがって、背後のコードで簡単にアクセスできます。

User.FirstName or User.LastName

Webフォームのシナリオで欠けているのは、ページに関連付けられていないコードで同じ動作を取得する方法です。たとえば、httpmodulesでは、常に各クラスにキャストを追加する必要がありますか、それともこれを取得するためのよりスマートな方法がありますか?

私はあなたの例を私のカスタムユーザーのベースとして使用したので、あなたの答えとLukePに感謝します(今では、、、、そしてUser.Roles他の多くの素晴らしいものがあります)User.TasksUser.HasPath(int)User.Settings.Timeout

于 2012-12-24T18:32:33.783 に答える
0

LukeP によって提案された解決策を試してみたところ、Authorize 属性がサポートされていないことがわかりました。ということで、ちょっと改造。

public class UserExBusinessInfo
{
    public int BusinessID { get; set; }
    public string Name { get; set; }
}

public class UserExInfo
{
    public IEnumerable<UserExBusinessInfo> BusinessInfo { get; set; }
    public int? CurrentBusinessID { get; set; }
}

public class PrincipalEx : ClaimsPrincipal
{
    private readonly UserExInfo userExInfo;
    public UserExInfo UserExInfo => userExInfo;

    public PrincipalEx(IPrincipal baseModel, UserExInfo userExInfo)
        : base(baseModel)
    {
        this.userExInfo = userExInfo;
    }
}

public class PrincipalExSerializeModel
{
    public UserExInfo UserExInfo { get; set; }
}

public static class IPrincipalHelpers
{
    public static UserExInfo ExInfo(this IPrincipal @this) => (@this as PrincipalEx)?.UserExInfo;
}


    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginModel details, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            AppUser user = await UserManager.FindAsync(details.Name, details.Password);

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid name or password.");
            }
            else
            {
                ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                AuthManager.SignOut();
                AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);

                user.LastLoginDate = DateTime.UtcNow;
                await UserManager.UpdateAsync(user);

                PrincipalExSerializeModel serializeModel = new PrincipalExSerializeModel();
                serializeModel.UserExInfo = new UserExInfo()
                {
                    BusinessInfo = await
                        db.Businesses
                        .Where(b => user.Id.Equals(b.AspNetUserID))
                        .Select(b => new UserExBusinessInfo { BusinessID = b.BusinessID, Name = b.Name })
                        .ToListAsync()
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                string userData = serializer.Serialize(serializeModel);

                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                         1,
                         details.Name,
                         DateTime.Now,
                         DateTime.Now.AddMinutes(15),
                         false,
                         userData);

                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(faCookie);

                return RedirectToLocal(returnUrl);
            }
        }
        return View(details);
    }

そして最後に Global.asax.cs

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

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            PrincipalExSerializeModel serializeModel = serializer.Deserialize<PrincipalExSerializeModel>(authTicket.UserData);
            PrincipalEx newUser = new PrincipalEx(HttpContext.Current.User, serializeModel.UserExInfo);
            HttpContext.Current.User = newUser;
        }
    }

呼び出すだけで、ビューとコントローラーのデータにアクセスできるようになりました

User.ExInfo()

ログアウトするには、電話するだけです

AuthManager.SignOut();

AuthManager の場所

HttpContext.GetOwinContext().Authentication
于 2018-06-26T09:02:53.333 に答える