【问题标题】:Token Authentication- Set custom User Property令牌认证 - 设置自定义用户属性
【发布时间】:2017-08-11 14:33:28
【问题描述】:

我想实现类似于here 描述的东西,但我有两个问题:在我的控制器的构造函数上,HttpContextUser 都是空的,我似乎无法找到那UserManager<T>类...

在我的控制器操作中,我可以获得UserHttpContext,但我不想逐个处理声明转换!我想创建一个“BaseController”,有一个“MyExtendedUserPrincipal”,并且在我的操作中只读取其中的内容...

我没有使用常规的 SQL 用户管理中间件...我认为这就是为什么我无法获得 UserManager<T>

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

    UserManager<T> 类不是开箱即用的,您必须自己定义它。您可以使用默认实现,也可以根据需要定义自己的类。

    例如:

    MyUserStore.cs

    这是用户的来源(例如数据库),您可以从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;
        });
    }
    

    MyController .cs

    然后,在您的控制器中,您可以访问UserManager&lt;MyUser&gt; 类:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多