In my application user can personalize their settings like background-image,use https etc.
How should i add these setting to users page.I mean should i store these setting like bacjground-image in session.What is the better way of dong it.I am using ASP.Net MVC.
Please help.
Maybe my answer on the question how to change the themes in asp.net mvc 2 can help you.
ASP.Net Profiles is used in such cases
There are really two options here
You can use the Profile functionality build into ASP.NET
Build your own class and then store the user settings in a table in the database
With option one there are plenty of tutorials and a good video on the ASP.NET website: http://www.asp.net/general/videos/how-do-i-customize-my-site-with-profiles-and-themes
With option two you would want to produce a user settings class which might look like this:
public class UserSettings{
public int UserId {get;set;}
public string BackgroundImage {get;set;}
public bool UserHttps {get;set;}
}
There would be a database table or some sort of persistent store the class was mapped onto. If you want to avoid a trip to the database every request you can pull an instance of the class from the database the first time the user logs in and then cache them somewhere. The cache could be the session, a cookie, the application cache etc.
Related
<authentication mode="Forms"/>
<forms loginUrl="~/Login/Login" defaultUrl="~/Login/Something" protection="All"></forms>
</authentication>
One way is to add Authorization tag to every Controller to secure application from unauthorized user.Other way is to use session variables to store user information .So,my question is from hacking perspective,how we can secure our application form hackers?Is there any other way to secure application?
Note: This answer should not be viewed as complete in any way, security is always hard and if it's important to you - always consult with a third party security and penetration testing company. This is just a few things you should consider to make your MVC application safer (not necessarily safe).
Protect controllers
First step is to apply [Authorize] to your controllers, to make sure there is some sort of valid authentication before accessing a method. Preferably add Authorize to all controllers and make exceptions with [AllowAnonymous] to make it secure-by-default.
Authorize the user
Even though you've added [Authorize] to the controller, that only means that the user is logged in, not that the user should have access to whatever method is being accessed. The first step is to extend the attribute by specifying a set of roles for the method: [Authorize(Roles = "Administrator"]
Depending on the application, you might also have to check that the current user belongs to the company/group or whatever that is being edited, to prevent someone from modifying data that doesn't belong to them.
Don't leak data into models
If you're using your actual data models as view models, you are at risk of allowing the user to enter more data than they're supposed to. Consider this example:
class Employee {
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
Assume that we for some reason allow our employees to change their name, and we use the Employee model for that. But of course we only make an edit field for the Name, and not the Salary as that would be stupid :D. However, due to how the model-binding works, a smart Employee could just add <input type="text" name="Salary" value="2147483647"> to the form when changing their name, and our gullible db.Entry(employee).State = EntityState.Added; followed by db.SaveChanges() would update their salary as well.
Solution? Either make a view model with only the Id and Name property, to make it impossible to change the salary, or use the Bind attribute to only include the properties we allow: public IActionResult Update([Bind(Include="Id,Name")]Employee model).
XSS
A very important part is to protect your users from bad dynamic content. If I can enter HTML and Javascript that's displayed to some other user, I can abuse that to steal their authentication token for example. Making to never render user-entered data as HTML is a first step to prevent this. You should also make sure to always use the anti-forgery token in your forms as well. Adding CSP headers is a good practice to prevent someone from injecting scripts that shouldn't be there.
We are building a MVC API + Entity project, right now we are creating our log layer, we wanna log every single entity that we add, alter or delete, however we need to log the user id that is performing the action as well, the id is provided with the Header [Authorization].
Our log is performed as the action previous to the database action, because of that we would need to add the user id to every method signature on all layers until the DAL.
After researching a bit on the internet, looking at Global Variables, HTTPContext, etc, we did not find any solution that did not "harm" the project layers, any ideias ? How should we proceed ?
You could use DI to inject the current user into whatever DAL classes need it. For example, I use Ninject to do this so I don't need to have the user id as a parameter on every update function:
kernel.Bind<IPrincipal>().ToMethod(c => HttpContext.Current.User);
Then in whatever classes in the app need it:
[Inject]
public IPrincipal CurrentUser { get; set; }
I am in search of an good approach to import data from ms access and bind it to any Model of an MVC pattern
Here is the approach which we are thinking to following
Approach 1 :
Open Ms Access file
Open database
Open all tables
Import data of all tables and bind them to an model
Close all tables
Close database
Close file
Approach 2 :
Connect Ms Access Database in Asp.Net MVC
Open the database
pass an query
fetch data and bind it to model
close database
Which approach is better and how I can Implement it?
UPDATE:
I have implemented Approach 2 and its works fine , does anyone know how to implement Approach 1
Both approaches will require you to connect to your database and map the contents into your model. I'm assuming Approach 1 is 'when the web app starts connect and copy all the database contents into memory and access if from there' and Approach 2 is 'when I need to display some data, connect the the database and copy the specific contents to my model'.
If this is the case, then Approach 2 is recommended (and you've stated you have done this so all is good).
Approach 1 may work ok-ish for smaller sized databases but:
You loose all the [acid][1]-y goodness that your database provides
Your stuck with global collection variables - not the most loved concept in web apps
You have an entire database unnecessarily in memory. Your slow point in web apps is usually the network, a few milliseconds to load data when needed is nothing compared with the time it takes for your html to reach the browser
If you were to try approach one (not recommended, do not do, a kitten is harmed each time this code is run) , then the easiest way would be to have something like this in your global.asax.cs file:
public class MvcApplication : System.Web.HttpApplication {
public static List<MyTable1> globalTable1;
public static List<MyTable2> globalTable2;
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var DatabaseMagic = new DatabaseAccessClass("a:\path\to\database.mdb");
globalTable1 = DatabaseMagic.getDataForTableOne(); //However you do your loading and mapping
globalTable2 = DatabaseMagic.getDataForTableTwo(); //ditto
}
Then in your controllers:
public ActionResult Index()
{
return View(MvcApplication.globalTable1);
}
And your view:
#model List<MvcApplication1.MvcApplication.MyTable1>
#{
ViewBag.Title = "Index";
}
<h2>Blah</h2>
<ul>
#foreach (var i in Model) {
<li>#i.idField - #i.contentField </li>
}
</ul>
(Did I mention don't do this?)
Use Entity Framework.Create ViewModel to map.
What you should do is build your model according to your table. So the model class should have properties which correspond to your table fields. Then when you require the Model you would query againist the DB and populate the model's properties accordingly.
I did not understood Approach 1.
Is it a requirement to use Access? I have seen there are lot of problems with file based database (such as Access) so better import all the data to SQL Server or some other database from Access and then use option 2.
As your database already created you can use Entity Framework database first approach to bind it.
You need to add using System.Data.OleDb; in Header file
And add these Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\myAccessFile.mdb;
Persist Security Info=False; line in connection string use connection string fetch
update ms-access database using OleDbCommand , OleDbConnection
and ms-access query just like sql query
In my MVC application I have Player and Coach objects, and a user can be one or the other. I also have Team objects and what I want to know is how I prevent a user who is in a list of Players or is the Coach of a Team gaining access to a route like /Teams/Details/2 where 2 is the id of a team other than that which he/she is part of.
Thanks in advance!
Since you want to restrict an id that they aren't a part of, this seems like a situation where you can Inherit from the AuthorizeAttribute and provide your implementation for AuthorizeCore
Your implementation could check their role/team id and decide what to do / redirect.
public class TeamAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return UserIsInTeam(httpContext); //whatever code you are using to check if the team id is right
}
}
You can now apply it like any other attribute.
[TeamAuthorize]
The very simplest solution would be to change the URLs from using IDs to random GUIDs. You would almost eliminate the chance of someone guessing another valid value. Of course, this is not secure by definition (mostly because someone could get the other URL from history or another source), but in some scenarios this is enough.
A better solution is to create a new attribute based on IActionFilter interface that implements OnActionExecuting method and checks the ID by using this.ControllerContext.HttpContext.User.Identity.Name and this.RouteData.Values["id"]. You will then apply this attribute to your controller methods.
In our current system we implemented row level security in controller methods by just adding the code that verifies the user permissions as the first line in each method. The checking code is the same as with the attribute and it requires the same amount of code to add. This approach has one additional benefit - it is easier to implement scenarios like where a coach would be able to see the details of other teams but not modify them (we have one action and view for both reading and updating depending on permissions).
You would also use the last approach if you need to go to the database to check the permissions and you are using IoC frameworks such as Ninject with constructor based injection - since you will not have access to those values in the attribute.
I'm trying to set up NHibernate in an ASP.NET MVC application using a DDD approach. However, I do get an error when trying to lazy load an objects related entity. Heres how I've structured my application:
Infrastructure layer:
Contains mapping files, repository implementations and a NHibernate bootstrapper to configure and build a session factory.
Heres a repository example:
public class CustomerRepository : ICustomerRepository
{
public Customer GetCustomerById(int customerId)
{
using (var session = NHibernateBootstrapper.OpenSession())
return session.Get<Customer>(customerId);
}
}
Domain layer:
Has simple POCO classes, repository and service interfaces
Application layer:
Contains Service implementations.
Heres a service example:
public class CustomerService : ICustomerService
{
private ICustomerRepository _repository;
public CustomerService(ICustomerRepository repository)
{
_repository = repository;
}
public Customer GetCustomerById(int customerId)
{
return _repository.GetCustomerById(customerId);
}
}
Presentation layer:
Contains the ASP.NET MVC application. And this is where I discovered my problem.
Using the MVC approach, I have a controller which, using the CustomerService service, gets a customer and displays the customer in a View (strongly typed). This customer has a related entity Contact, and when I try to access it in my View using Model.Contact, where Model is my Customer object, I get an LazyInitializationException.
I know why I get this. It's because the session used to retrieve the Customer in the CustomerRepository is dead by now. My problem is how I can fix this. I would like if I could avoid getting the related Contact entity for the Customer in my repository, because some views only need the Customer data, not the Contact data. If this is possible at all?
So to the question: is it possible to wait querying the database, until the presentation layer needs the related entity Contact?
I think that what I need is something like what this article describes. I just can't figure out how to implement it in infrastructure layer, or where should it be implemented?
Thanks in advance. Any help will be much appreciated!
As for session management it is common to use single session per request. You can see an example of implementation here. It is an open source project that were designed to setup new asp.net applications with the help of Nhibernate wery easy. source code can be founded here.
Hope it helps.
I also recommend Sharp Architecture.
Another approach, as well as suggestion, is to avoid passing entities to views. There're other problems with it except session management - business rules leaking into views, bloated/spagetti code in there, etc. Use ViewModel approach.
Another problem you'll get is storing your entities in Session. Once you try to get your Customer from Session["customer"] you'll get the same exception. There're several solutions to this, for example storing IDs, or adding repository methods to prevent lazy-loading of objects you're going to store in session - read NHibernate's SetFetchMode - which, of course, you can also use to pass entity to views. But as I said you better stick with ViewModel approach. Google for ViewModel, or refer to ASP.NET MVC In Action book, which uses samples of code from http://code.google.com/p/codecampserver/. Also read this, for example.
Are all your properties and methods in your Customer class marked virtual?
How are you opening and closing your session? I use an ActionFilterAttribute called TransactionPerRequest and decorate all my controllers with it.
Check out this for an implementation.