I want to do GetPassword() on MembershipUser but the custom membership provider in the application is throwing NotImplemented exception, let me know some workaround to get any users password ?
Thanks
If you are using a custom membership provider, that means you have created a class that inherits MembershipProvider. When you inherit this class, visual studio will typically go ahead and auto generate the abstract methods that you inherit from MembershipProvider. One of those methods is GetPassword(), and it's up to you to program the logic for it. By default, it throws that exception reminding you that you haven't written the logic for it yet.
If you didn't want to do a custom membership provider, you can use a SqlMembershipProvider instead and let visual studio create the necessary tables and stored procedures to handle everything. A custom membership provider is used when you want full control over the programming logic.
Related
So, I am creating a class library that handles user information like username, password, etc. I want to do this so that I can just reference this library with any of my web apps and not have to continuously rewrite the user information part.
In, the user information class library, I want to handle the login. I've done this before in app_code that was a part of the web project by using HttpContext.Current.Session. But, when I try to use it in my class library (even while using System.Web) it throws a compile error saying that HttpContext does not exist in this context. How can I get access to it?
When creating a utility type class that works with a dependency like HttpContext, your best bet is to pass the context or the session into the class either via a constructor or the method call. That way, it is explicit to the consumers of your class that it requires this object to function. This also allows you to test your class in isolation.
Even better, if you are working with a few specific properties that have basic types then you can accept those properties as inputs. That way, you are not creating any dependencies on a UI framework for your utility library.
I have to build website with MVC 4 on top of Oracle database. Also I don't want these webpages_Membership or webpages_OAuthMembership tables. Is it necessary to write my own membership provider and role provider? I found this - it might be good solution, but maybe there is a simplier way?
If you don't want to use the tables created by Simple Membership Provider, from solution explorer go to Filters, InitializeSimpleMembershipAttribute.cs and make sure autoCreateTables is set to false:
WebSecurity.InitializeDatabaseConnection("MyContext", "TableToPointTo",
"UserIdColumn", "UserNameColumn", autoCreateTables: false);
Simple Membership Provider inherits from Extended Membership Provider so if you wanted to create your own custom provider you would do something like this:
public class MyMembershipProvider : ExtendedMembershipProvider
{
// inherited methods
}
If you want to look at the logic in the SimpleMembershipProvider class, you can see the source code here.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Inject repository to custom membership provider with Ninject
I have searched much about this topic too much the most close answer was here
MVC 3 ninject custom membership context disposed error
but I don't have any idea about the details all I have in my application is a domain contains my entities and abstraction for repositories and the implementation everything works fine when I use my Ninject binding like this
public class NinjectControllerFactory : DefaultControllerFactory{
readonly IKernel _kernel;
public NinjectControllerFactory(){
_kernel=new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType){
return controllerType == null
? null
: (IController) _kernel.Get(controllerType);
}
void AddBindings(){
_kernel.Bind<IٍSomeRepository>()
.To<EFSomeRepository>();
but I have no idea how to bind the customer membership provider I have read about this that I have to inject via a poperty but I don't know how, any ideas ?
First, you should be using Ninject.MVC3 rather than your own controller factory. Ninject.MVC3 takes care of hooking everything up, you just need to provide your mappings in App_Start\NinjectWebCommon.cs
Second, don't bother with using Ninject for Membership, unless you're using a custom membership provider. Even then, it's a lot less of a pain if you don't mix Ninject and Membership. I would suggest not bothering with it unless you really know what you're doing.
The problem is that Membership is a static class, that creates a static instance of the Membership Provider. This means it doesn't get destroyed at the end of the request. There are ways around this, but in general, it's just a lot easier to use Membership as-is than try to make it work with DI.
The question you linked to solves a specific problem, relating to injecting business logic into your custom membership provider. If you need to do this, then it might be a good choice. However, I find that most custom membership providers tend to be very simple.
I'm trying to setup an 'Authorization' Filter on an Action, creating my own ActionFilterAttribute where I do a database lookup to determine if a user has access to a certain resource.
On my class inheriting from ActionFilterAttribute, I have created an Injected(Ninject) property to hold the service that I am using for the database access. I have a parameterless constructor so that I can use this as an attribute on my actions. In the 'OnActionExecuting' Method, I am able to gain access to the Injected property (it's not null), but the base DBCotext that it is using is closed.
This working fine, up until the RTM of MVC3, where the Release Notes stated:
Breaking Changes:
In previous versions of ASP.NET MVC, action filters are create per
request except in a few cases. This
behavior was never a guaranteed
behavior but merely an implementation
detail and the contract for filters
was to consider them stateless. In
ASP.NET MVC 3, filters are cached more
aggressively. Therefore, any custom
action filters which improperly store
instance state might be broken.
The first time I use this filter, it works as expected, but if I refresh the page or another user access this filter, I get the error:
The operation cannot be completed
because the DbContext has been
disposed.
which is what I guess I should expect given the breaking changes notes.
My question is this, what would be the preferred/recommended way of accomplishing what I need to do? Should this be in an ActionFilterAttribute, or should this 'authorization' be done somewhere else?
I'd do authentication in Application_AuthenticateRequest and authorization in your attribute using Thread.CurrentPrincipal, but your method should work too. You just need to count with fact that DbContext will be different for each request but your attribute won't. Something like this should do the trick (I'm assuming you are using DependencyResolver):
public class MyMightyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = (DbContext)DependencyResolver.Current.GetService(typeof(DbContext))
// authenticate, authorize, whatever
base.OnActionExecuting(filterContext);
}
}
I have been battling with this for a while and finally solved my problem. So here is my solution in the hope it may help someone else.
The setup:
1. I have an MVC3 project, a custom action filter that accesses the db using EF5 via a business service.
2. I use Unity and unity.MVC to resolve my dependencies on a per request basis.
3. I use property injection into my custom Action filter, as it has a parameterless constructor.
The result.
Dependency injection works correctly for all the services used by actions, my EF DbContext is correctly disposed of at the end of each request.
The Problem
Although my property dependency is resolved in my custom action filter, it contains a stale instance of my DbContext (e.g. it seems to have been cached from the previous request)
As mentioned in previous posts, MVC3 is more aggressive with filter caching and the state of a filter cannot be relied on. So the suggestion was to resolve the dependency in the OnActionExecuting method. So I removed my injected property and did just that called resolve on my unity container. However I still got a stale version of the DbContext. Any changes in the DB were correctly queried in my main actions, but the custom action filter didn’t pick them up.
The solution.
Unity.MVC Manages per-request lifetime by using child containers and disposing these at the end of each request. By resolving my dependency’s in the action filter from my unity container I was resolving from the parent container which is not disposed of on each request.
So rather than
IoC.Instance.CurrentContainer.Resolve<IService>();
I used this to obtain an instance of the child container rather than parent.
var childContainer = HttpContext.Current.Items["perRequestContainer"] as IUnityContainer;
var service = childContainer.Resolve<IServcie>();
I'm sure there must be a clean way to achive the same result, so please add suggestions.
Ok slight refinement to allow my unit test to inject a mock of the service.
1. remove the dependency resolve from the the OnActionexecuting and add two constructors.
public MyCustomActionfilter() : this(((IUnityContainer)HttpContext.Current.Items["perRequestContainer"].Resolve<IService>())
and
public MyCustomActionfilter(IService service)
{
this.service = service;
}
Now the constructor resolves your service and stores it as a private readonly. This can now be consumed in your OnActionExecutng function. Unit tests can now call the second constructor and inject a mock.
Dear All,
I am using the membership provider of MVC framework, Now i want to implement the Role and Right on My project, All the Role and Right is available on database so how can i implement the Role and Right? is there is any built in function which can i use? also i am using the Ado .net Data Entity Framework..
If I'm understanding what you want to do correctly, you have to annotate your Controller class or ActionResult with the Authorize attribute like this:
[Authorize(Roles="Domain Admins", Users="testuser")]
public class TestController : Controller {
}
Then as long as your membership provider is setup you should be good to go.
It may be worth mentioning that you can always check if a user is in a role with the following code.
User.IsInRole("Domain Admins");
If your using MVC2 then the default project template makes it easy. You should check out the AccountController and AccountModels in a default MVC2 template.
It sounds like you need a custom role provider:
http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx
http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx
http://www.codeproject.com/KB/aspnet/WSSecurityProvider.aspx