2017-08-10 20 views
0

hereのようなものを実現したいのですが、2つの問題があります。コントローラのコンストラクタでHttpContextとなるため、Userはnullです。私のコントローラのアクションにどこそのUserManager<T>クラス...トークン認証 - カスタムユーザープロパティを設定する

私はUserHttpContextを得ることができます、しかし、私は、クレーム変換ケース・バイ・ケースを処理する必要はありません!私は "BaseController"を作成したいと思います。MyExtendedUserPrincipalを持っています。私のアクションには、それからのものだけが読み込まれます...

私は通常のSQLユーザー管理ミドルウェアを使用していません...私はthatsなぜ私は保留を得ることができませんUserManager<T>

答えて

1

UserManager<T>クラスは、あなたがそれを自分で定義する必要があります。デフォルトの実装を使用するか、必要に応じて独自のクラスを定義することができます。例えば

:ユーザーが(例えばDB)から来て、どこがClaimsPrincipalからのいかなる請求から独自のユーザーを取得することができる場所

MyUserStore.cs

です。

public class MyUserStore: IUserStore<MyUser>, IQueryableUserStore<MyUser> 
{ 
    // critical method to bridge between HttpContext.User and your MyUser class   
    public async Task<MyUser> FindByIdAsync(string userId, CancellationToken cancellationToken) 
    { 
     // that userId comes from the ClaimsPrincipal (HttpContext.User) 
     var user = _users.Find(userId); 
     return await Task.FromResult(user); 
    } 
} 

Startup.cs

public void ConfigureServices(IServiceCollection services)   
{ 
    // you'll need both a user and a role class. You can also implement a RoleStore if needed 
    services 
     .AddIdentity<MyUser, MyRole>() 
     .AddUserStore<MyUserStore>(); 

    services.Configure<IdentityOptions>(options => 
    { 
     // This claim will be used as userId in MyUserStore.FindByIdAsync 
     options.ClaimsIdentity.UserIdClaimType = ClaimTypes.Name; 
    }); 
} 

MyControllerは.cs

次に、あなたのコントローラでは、あなたはUserManager<MyUser>クラスにアクセスすることができます210

public class MyController : Controller 
{ 
    private readonly UserManager<User> _userManager; 
    public MyController(UserManager<User> userManager) 
    { 
     _userManager = userManager; 
    } 


    [HttpGet("whatever")] 
    public async Task<IActionResult> GetWhatever() 
    { 
     // this will get your user from the UserStore, 
     // based on the ClaimsIdentity.UserIdClaimType from the ClaimsPrincipal 
     MyUser myUser = await _userManager.GetUserAsync(User); 
    } 
}