How to Implement Role Based Authorization in MVC3 with Fluent NHibernate? - asp.net-mvc-3

Our MVC3 application is using Fluent NHibernate and requires implementation of user login, authentication and authorization.
I've seen articles using the [Authorize] method in the controller classes. However, I'm not sure how this all works in our situation given that Fluent NHibernate is in use.
Can anyone share some suggestions as to how to make this work?

You could write a custom role provider implementing the RoleProvider class. In your custom implementation you of the RoleProvider class you could use whatever database access technology you want - FluentNhibernate or whatever. Basically you are interested in implementing the IsUserInRole method.
Then decorate your controllers/actions with the Authorize attribute:
[Authorize(Roles = "Admin")]
public ActionResult Foo()
{
return Content("Only administrators can see this message");
}
And here's another blog post that covers writing a custom role provider in more details.

Related

VS2013 (RTW): Authentication differences in SPA template vs MVC5 template?

I've been playing with the new ASP.NET identity offerings in the VS2013 RTW MVC template (for "indivual user accounts"), and it works great: I am able to integrate Facebook login while customizing the way the data is serialized.
All well and good, but I noticed that if I create a new SPA app (instead of MVC), the authentication story seems very different. As an example:
From the SPA template:
public AccountController()
: this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
{
}
public AccountController(UserManager<IdentityUser> userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
From the MVC template:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
This is just the difference in constructors of the Account controller. There are many, many other differences as well. With the MVC version I was able to easily derive my own context class from ApplicationDBContext, and use that to store my own tables alongside the authentication tables. I couldn't figure out how to customize the data storage in the SPA template.
Also, the SPA template includes and uses this class:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
The MVC template doesn't define (or use) this class.
I don't understand why there needs to be any differences at all between an MVC template and an SPA template.
Could anyone give me some guidance as to why authentication is handled so differently in these two templates? Starting a project from scratch, is there a preferred path to follow between the two? (It seems like the code in the MVC template is best, especially in terms of customizing how the data is stored by defining a custom EF Context class.)
Thanks...
-Ben
Take MVC and SPA project templates as Controller vs ApiController implementation sample.
As well as CookieAuthentication and oAuthAuthentication.
MVC uses Controller at the first request as well as all subsequent requests (having request defined Action Methods).
SPA uses Controller at the first request to SPA and all other interactions are handled by ApiController.
MVC uses cookie authentication.
SPA uses oAuth authentication.
Now in real apps, we need to take mix of both. Stating this, you can use the IdentityModel.cs (ApplicationDBContext) and it's customized copy of MVC project in your SPA too.
In oAuth implementation, the token is issued in GrantResourceOwnerCredentials method of ApplicationOAuthProvider. The user verification uses the same database of Identity framework by default. Moreover, oAuth provide authentication check in ApiController. In the sample implementation, oAuth's ResourceOwner flow is provided where user's username and password are verified.
In my opinion, templates are starting point examples.
I did notice the same thing when I first looked at all the posts about changing the model for the user and I couldn't find the model in the SPA template. Of course, the difference as #jd4u pointed out is that one is based on Controller and the other on ApiController.
So, I decided to see what it would take to make the SPA solution use the same Identity Model extension as the MVC template. I created a post that goes through the process that I went through. There is a link at the bottom to download the code from GitHub.

Can RoleProvider be used without MembershipProvider?

I would like to use RoleProvider in my application so that I can use the AuthorizeAttribute on my controller actions like so:
[Authorize(Roles = "Admin")]
However, I don't need (and don't want to use) a MembershipProvider as most of the authentication code has already been built in our ASP.net 4.5 web application.
So can I simply use a custom RoleProvider without using/implementing an out-of-the-box MembershipProvider or custom MembershipProvider and be able to use the AuthorizeAttribute?
Thank you.

MVC 4 - custom memebership provider with Oracle database

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.

Ninject and Custom Membership provider Mvc3 [duplicate]

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.

User Define Role and Right on Membership Provider on MVC

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

Resources