web-dev-qa-db-ja.com

ユーザー登録時にクレームを追加する方法

ID2.1.0およびVS2013U4のASP.NETMVC5プロジェクトを使用しています。 dbに保存するために、登録時にユーザーにクレームを追加したい。これらのクレームは、ユーザーのカスタムプロパティを表しています。
管理者がユーザーを作成/編集/削除するためのWebページを作成したので、まだAccountControllerのc​​reateメソッドを使用してユーザーを作成していますが、そのユーザーにログインしたくありません。これらのクレームをユーザーに追加するにはどうすればよいですか?

10
Milan

おそらくすでにUserManagerクラスがあります。これを使用して、ユーザーを作成したり、クレームを追加したりできます。

コントローラの例として:

// gather some context stuff
var context = this.Request.GetContext();

// gather the user manager
var usermanager = context.Get<ApplicationUserManager>();

// add a country claim (given you have the userId)
usermanager.AddClaim("userid", new Claim(ClaimTypes.Country, "Germany"));

これを機能させるには、独自のUserManagerを実装し、それをOWINコンテキストにリンクする必要があります(この例では、ApplicationUserManagerであり、基本的にはclass ApplicationUserManager : UserManager<ApplicationUser> { }であり、構成が追加されました)。ここで少し読んでください: https://msdn.Microsoft.com/en-us/library/dn613290%28v=vs.108%29.aspx

13
pysco68

likeを使用できます

private void SignInAsync(User User)
{
    var claims = new List<Claim>();

    claims.Add(new Claim(ClaimTypes.Name, User.Employee.Name));
    claims.Add(new Claim(ClaimTypes.Email, User.Employee.EmailId));
    claims.Add(new Claim(ClaimTypes.Role, User.RoleId.ToString()));
    var id = new ClaimsIdentity(claims,
                                DefaultAuthenticationTypes.ApplicationCookie);
    var claimsPrincipal = new ClaimsPrincipal(id);
    // Set current principal
    Thread.CurrentPrincipal = claimsPrincipal;
    var ctx = Request.GetOwinContext();
    var authenticationManager = ctx.Authentication;

    authenticationManager.SignIn(id);
}

ログイン後、この関数でユーザーテーブルの値を渡します

 SignInAsync(result);

あなたは次のようなハマグリの価値を得ることができます

var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
 // Get the claims values
        string UserRoleValue = identity.Claims.Where(c => c.Type == ClaimTypes.Role)
                           .Select(c => c.Value).SingleOrDefault();
6
user3966829

実際、ユーザーアカウントの作成と同時にクレームを作成することもできます。

ユーザーマネージャーでCreateAsyncを呼び出す前に、ユーザーオブジェクトにクレームを追加するだけです。

var identityUser = new IdentityUser
{
  UserName = username,
  Email = email,
  // etc...
  Claims = { new IdentityUserClaim { ClaimType = "SomeClaimType", ClaimValue = "SomeClaimValue"} }
};
var identityResult = await _userManager.CreateAsync(identityUser, password);

これにより、ユーザーが作成され、永続性を備えた1つの論理操作としてクレームがユーザーに関連付けられます。

0
Cliff