2017-08-10 82 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); 
    } 
}