2016-07-26 8 views
1

私のプロジェクトのASPの中で、私はASP.NET Identity 2.2.1を使用しています。多くの場所で私は現在の(ログインしている)ユーザーの電子メールを取得する必要があります。 は今、私はこれを使用して、そのユーザーを見つけることだ:Security.Principal.IIdentityユーザーのメールを取得するための拡張メソッド

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>()); 
var email = user.Email; 

私はGetUserId<T>は私が自分自身の拡張メソッドを作成しましたMicrosoft.AspNet.Identity

IdentityExtensionsクラスの中に発見することができます拡張メソッドであることに気付きました

:以下
var email = User.Identity.GetUserEmail() 

が私の拡張機能である:それはとしてそれを取得できるようにすることで、電子メールを取得簡素化
public static class MyIIdentityExtensions 
{ 
    public static string GetUserEmail(this IIdentity identity) 
    { 
     if (identity == null) 
     { 
      throw new ArgumentNullException("identity"); 
     } 
     var ci = identity as ClaimsIdentity; 
     if (ci == null) return null; 
     var um = HttpContext.Current.GetOwinContext().GetUserManager<UserManager>(); 
     if (um == null) return null; 
     var user = um.FindById(ci.GetUserId<int>()); 
     if (user == null) return null; 
     return user.Email; 
    } 
} 

しかし、私はこれを簡素化することができ、それははるかに複雑build-in extension methods

よりもですか?たぶん、これを行うためのメソッドの構築がありますか?私が欲しいのは、現在ログインしているユーザーのためにEmailをUser.Identityから取得する簡単な方法です。

答えて

2

UserManagerを使用する場合は、GetUserEmailメソッドを呼び出すたびにデータベースにヒットします。

代わりに、電子メールをクレームとして追加することができます。 ApplicationUserクラス内

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
{ 
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
    // Add custom user claims here 
    userIdentity.AddClaim(new Claim(ClaimTypes.Email, this.Email)); 
    return userIdentity; 
} 

は、その後、あなたの拡張メソッドは、それが

public static class IdentityExtensions 
{ 
    public static string GetUserEmail(this IIdentity identity) 
    { 
     if (identity == null) 
     { 
      throw new ArgumentNullException("identity"); 
     } 
     var ci = identity as ClaimsIdentity; 
     if (ci != null) 
     { 
      return ci.FindFirstValue(ClaimTypes.Email); 
     } 
     return null; 
    } 
} 
+0

私は完全にGenerateUserIdentityAsync'方法 'を忘れて取得するGenerateUserIdentityAsync方法があります。私も同じコメントを '/ /ここにカスタムユーザーの主張を追加する'。もう1つの「余分な」質問があります。ユーザーがログに記録するときに返されるJWTトークンからその要求を削除できますか?私が望むのは、JWTトークン内に最小限のデータセットを返すことです。しかし、反対側からは、すべての要求でトークンからそのクレームを取り除くと、私はそのクレームを持たないので、私はその電子メールアドレスを取得することができません。 – Misiu

+0

@ミシューコメントの行は、デフォルトのmvc5テンプレートからあります:) あなたの余分な質問については、あなたは何をしたいのか明確ではありません。リクエストによってはクレームを追加したいのですか? – tmg

+0

混乱して申し訳ありません。その主張をサーバー側でアクセス可能にしたいが、JWTトークン内のクライアントには送信しない。おそらくこれは可能ではありませんが、私は確信しています。 – Misiu

関連する問題