I implemented custom authentication/authorization based on this tutorial http://www.mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx
It works fine. I implemented it because I don't want to have stored procedures in my database and possibility to use different RDBMS.
But I have one issue here. I authenticate user but I don't know how to store UserId somewhere so when I need to get something from database based on UserID to get it. Something like:
List<Product> products = productsRepository.GetProductsByUserId(User.UserID);
How to make this?
BTW Is there any better way to make custom authentication/authorization than this from this tutorial?
Thanks
发布评论
评论(3)
如果您实际上已经实现了所有方法,并且正在填充内置 MembershipUser,那么只需
Membership.GetUser().ProviderUserKey
将返回 UserId。If you've actually implemented all the methods, and you're populating the built-in MembershipUser, then simply
Membership.GetUser().ProviderUserKey
will return ther UserId.在我的解决方案中我使用
也许这对你有用
in my solution I use
maybe this can be of use to you
如果您使用 FormsAuthentification,除了用户名之外,您还可以在 cookie/票证中编码一些自定义用户数据。但您必须手动创建 FormsAuthenticationTicket 并在登录期间将 UserData 属性设置为用户的 id。这样你就可以同时拥有用户名和用户名。用户身份。
然后你可以为 Controller 或 HttpContext 类提供一个扩展方法:
但是如果你不需要 UserId 和 UserId ,您的用户的 UserName 数据,
HttpContext.User.Identity.Name
或Controller.User.Identity.Name
将包含您当前用户的用户名If you're using FormsAuthentification you can encode some custom user data in your cookie / ticket besides UserName. But you have to manually create a FormsAuthenticationTicket and set UserData property to the user's id during login. This way you can have both UserName & UserId.
Then you can have an extension method for Controller or HttpContext classes:
But if you don't need both UserId & UserName data for your user, than
HttpContext.User.Identity.Name
orController.User.Identity.Name
will have the username for your current user