Using EF and Asp .Net Identity in an MVC 5 project. I would like to associate records in the database with particular users. The problem is, I have two separate DbContexts. ApplicationDbContext handles Identity functions: authentication, authorization, etc... My other DbContext (MyDbcontext) handles the actual business of the application. I would like to associate records in MyDbContext with users in ApplicationDbcontext. Do I need to open ApplicationDbContext, get my user info, close it, then open MyDbContext and perform some work? Can I open both at the same time? Do I need some kind of mapping table in MyDbcontext? For a bonus, can I get user info in my EF migrations seed method for MyDbContext?
You could have your app context inherit from identity context, but assuming you don't want to do that the next best option would be to configure a copy of the user model in your app context and add the DbSet<ApplicationUser> to your app context. You could also just store updatedBy and createdBy without doing a relation.
Related
We have an application hosted in Azure and it works just fine. This application is based on MVC4 along with SimpleMembership and Entity Framework with Code first. When the application is hosted in the web it just works. Code first creates DB, Roles and the Admin user.
Now we have a requirement of providing the same application to different Companies on a SAAS based Model. For that we had two approaches.
We can store the information of all the companies on the same database.
We can store the information each company in their own and separate database.
We want to go with the second approach so that each company will have their own Database. Each time a company register a separate database for them (But there will be only one web application) will be initializes and their Roles and Admin user will be created. So that when a person of that particular user logs in they will operate with their own database.
But the problem arises when any method or properties from the WebSecurity class is called from the SimpleMembership provider. Lets say an user from company "ABC" is logged in we can initialize the WebSecurity.InitializeDatabaseConnection() to use the DataBase associated with te ABC Database. Whe some one else logs in from another Company lets say "XYZ" company we need to tell the WebSecurity to use the database associated with XYZ Database. Now as WebSecurity is initialized with the ABC Database it does not work with XYZ databse and twrowing an error saying WebSecurity can only be initialized once.
Now can you please help me figuring out a way so that my WebSecurity can work with dynamic Context then that will be great. Or you can let me know a solution to work with multiple databases. Please note that we do not want to restructure our app and re write it from the beginning.
I am using MVC3, C#, EF4.1 and SQL Server 2008.
I have a seperate Domain project for holding the POCO classes for interacting with the DB via EF.
I have implemented "UpdatedOn" using DB triggers. All works fine. However since I need to store the application username rather than the gneric DB username, I require a different mechanism. I have read different posts on here which talks about DBContext.Save(Username) or DI approaches. However I am wondering whether I could add code to my Domain Model project which could do this centrally. I use the Membership Provider, and it is this "Username" that I would need to be passed to the Domain Model.
I would appreciate some advice on a straigh forward approach to this issue.
Many thanks.
What is understand form your description is that , you need to override SaveChanges() method for dbcontext i.e add logic for record insertion/updation here, so that on every commit to the database there must be an entry to the attribute ( UpdatedBy ).
I am trying to convert my vb.net 2010 web forms application into a C# MVC 4 application. Since my membership is already setup, I would prefer to just continue using the membership provider instead of the simplemembershipprovider.
Hi,
I am using PluralSight to learn MVC, but have not been able to find any reference on how to convert membership code to mvc.
I have a custom table that is linked by UserID to the mememberships User table. This custom table, asp_customUser, stores additional information about the user.
In the account controller, there is a register action, with the view and model. The register process does not handle roles, much less my custom data.
What I would like to know is, how do I add roles and custom user information to the database, when part of the fields in the registration view come from the membership library and the other part go to my custom table.
Thanks
Yes, you can use the old membership. Just copy and paste your membership provider from the old web.config to the new one.
If this is running on a different computer, you may need to set the machine key, however, in order for it to be able to correctly validate the password hashes.
You would then remove the Simple membership initialization attribute from the Account controller, and you would need to remove all the other simple membership code. You would also be giving up the OpenId authentication, because normal membership does not work with WebSecurity, so you would have to remove all that as well.
When we wanted to extend the membership class we inherited the base membership class and used all the fields in it and the tables linked to it and then create an additional database table with a FK linked to the id in the membership table. Any additional parameters where in the new table and extended class and any standard parameters were in the std membership table and standard class.
I am creating a asp.net mvc project which I want to manage the roles in the database.
I have a database with a table, in the table Called Premissions I have a column (AdministratorRole) that contains roles for my mvc project, the value will hold something like 'Domain\John Smith' (the users). I want my mvc project to check this column each time it starts up.
In my mvc project i am using the Authorize attribute in the controllers:
[Authorize(Roles = Roles.AdministratorRole)]
I was thinking of creating a Interface so I can use a IQueryable to query the database, and then add something in the Global.asax file in the application_start method so that it runs the interface first and check all roles. (How can I do this?)
This is so we can maintain the roles in the database rather than in the code of the project.
How can I do this please?
Thanks
ASP.Net uses a Provider model for Membership and Roles. If you are doing something custom, then you simply need to create a Custom RoleProvider.
You can implement a RoleProvider.
ASP.NET role management enables you to easily use a number of
different providers for your ASP.NET applications. You can use the
supplied profile providers that are included with the .NET Framework,
or you can implement your own provider.
There are two primary reasons for creating a custom role provider.
You need to store role information in a data source that is not
supported by the role providers included with the .NET Framework, such
as a FoxPro database, an Oracle database, or other data source.
You need to manage role information using a database schema that is
different from the database schema used by the providers that ship
with the .NET Framework. A common example of this would be
authorization data that already exists in a SQL Server database for a
company or Web site.
I come from 5 years of experience with ASP.NET Web Forms, and I'm new to ASP.NET MVC. I'm now trying to learn MVC with some tutorials, video tutorials, and books.
I'm using Visual Studio 2012 and the brand new ASP.NET MVC 4 to build a little web application to manage my portfolio of mutual funds. This should let me get inside the new pattern and learn lots of new things...
My application should also let some other friends to do the same. So it has to manage different users' portfolios.
I've built a little DB with Entity Framework Code First, so I have some basic models: Fund, Portfolio, Share, Deposit, Source and User. One user can have many portfolios with many funds inside of them. Each user has their own deposits list. Each fund has many share values (one/day). The Source model is simply a table where I put one URL for every website source for the share data of a specific fund. So, one fund has many sources. I then use a scraper class to get data from those websites once a day.
This is the main structure of the application. Now, I need to know what would be the best way to:
1) Manage a user's account.
Should I integrate the ASP.NET Membership DB structure on my DB and use it instead of my custom User table to manage users?
2) Manage user content: portfolios, funds, etc.
What is the easiest and most elegant way in the MVC pattern, to implement authentication and all the authorization validations to make the user getting his own data? Do I need to check this inside every action on every controller?
So, in other words, how do I have to implement my controllers? E.g.:
[Authorize]
public class PortfolioController : Controller
{
private FundMonitorContext db = new FundMonitorContext();
public ActionResult Index()
{
// Check user ID and give back to the view only his portfolios...
var portfolio = db.Portfolios.List();
return View(portfolio.ToList());
}
...
public ActionResult Details(int id = 0)
{
...
}
//Other actions...
}
I would really appreciate every suggestion!
It's a choice you have to make yourself but I like to create my own Membership Provider, and it is not that hard. With your own provider you can make it in your own way, not like what Microsoft thought was cool 10 years ago. Example: http://www.codeproject.com/Articles/165159/Custom-Membership-Providers. In .NET 4.5 it is even more easier with SimpleMembershipProvider to create your own provider.
With the [Authorize] attribute you are telling the controller that only autorized user will be accepted. When a user signs in you can put the username/userid in the FormsAuthentication cookie, so you can very easy get the users username/userid. You can also create Authtication ticktes in the cookie if you want to put more data in it. To make it easier to test I hardly recommend to create a binding between HttpContext.User and IPrincipal, http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx.
Use Identity 2.0 for authentication and authorization. i found this blog http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx quite helpful. Basically, you'll get claims based auth and can then decorate your actions with the AuthorizeAttribute such as
[Authorize(Roles="Admin, Moderators")]
public ActionResult MyAction(...)
and you can look at the claims via the User.Identity property in the controller.