2017-08-10 85 views
0

我想要實現類似描述here,但我有2個問題:在我的控制器的構造函數,HttpContext,因此User,都是空的,我似乎無法得到在那UserManager<T>類...令牌身份驗證 - 設置自定義用戶屬性

在我的控制器行動我可以得到UserHttpContext,但我不想處理索賠轉換的個案!我想創建一個「BaseController」,有一個「MyExtendedUserPrincipal」,並在我的行動只讀它的東西...

我不使用常規的SQL用戶管理中間件...我認爲多數民衆贊成在爲什麼我不能得到一個UserManager<T>

回答

1

UserManager<T>類不開箱,你必須自己定義它。您可以使用默認實現,或者根據需要定義自己的類。

例如:

MyUserStore.cs

這就是用戶來自(例如DB),並在那裏你可以從任何ClaimsPrincipal檢索要求自己的用戶。

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; 
    }); 
} 

的.cs myController的

然後,在你的控制器,你可以訪問UserManager<MyUser>類:

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); 
    } 
}