How to handle session information in an Asp.net MVC app with dependency injection - asp.net

I have a multitenant application where I want to keep track of two things across the app: The user and The tenant.
I have this three cases:
Anonymous Users: In this case user is null, and tenant is tracked by querystring.
Authenticated Users: user comes from cookie, tenant is saved in session.
Jobs: I have jobs in my app to do some work, the user in this case is null and the tenant is set manually.
In all my services I use the user and the tenant.
I tought at first of using an object per http session in my DI container, but this wouldn't work with the Jobs.
Any toughts on how can I handle this information, I'm currently using it in a Session variable, but I have many problems with this implementation, and I need to have a lot of special cases to handle jobs and unauthenticated users.

The least you should do is abstracting access to user context. For instance:
public interface IUserContext {
IPrincipal User { get; }
Tenant Tenant { get; }
}
You might want to have a separate ITenantContext abstraction, but let's stick to one for now.
Your system will probably have two applications: windows service that runs the jobs, and a web application that handles user interaction. Both applications have their own entry point, their own Composition Root, and their own unique DI configuration.
For the web application, I imagine the implementation to look as follows:
public AspNetUserContext : IUserContext
{
private readonly ITenantRepository tenantRepository;
public AspNetUserContext(ITenantRepository tenantRepository) {
this.tenantRepository = tenantRepository;
}
public IPrincipal User {
get { return HttpContext.Current.User; }
}
public Tenant Tenant {
get {
if (this.User.Identity.IsAuthenticated) {
return this.tenantRepository.GetByName(
HttpContext.Current.Session["tenant"]);
} else {
return this.tenantRepository.GetByName(
HttpContext.Current.Request.QueryString["tenant"]);
}
}
}
}
For the job service, things might look completely diffetent at first, but with the service, the processing of one job can be considered a request. So that means that when the request start, you need to set the context (something that ASP.NET does for us in the backgroudn). The IUserContext might look as follows:
public JobServiceUserContext : IUserContext
{
[ThreadStatic]
private static IPrinciple user;
[ThreadStatic]
private static Tenant tenant;
public IPrincipal User {
get { return this.user; }
set { this.user = user; }
}
public IPrincipal User {
get { return this.tenant; }
set { this.tenant = tenant; }
}
}
Now the execution of a job can be wrapped with some logic that sets the proper context, for instance:
public class JobRunner {
private readonly JobServiceUserContext context;
private readonly IJobDactory jobFactory;
public JobServiceUserContext(JobServiceUserContext context,
IJobDactory jobFactory) {
this.context = context;
this.jobFactory = jobFactory;
}
public void RunJob(JobDetails job) {
try {
this.context.User = job.User;
this.context.Tenant = job.Tenant;
IJob job = this.jobFactory.Create(job.Type);
job.Execute(job.Data);
Activator.CreateInsta
} finally {
// Reset
this.context.Tenant = null;
this.context.User = null;
}
}
}
UPDATE
In case they are both running within the same application, and the jobs are running on a background thread, you can introduce a proxy implementation for IUserContext that transparently switches to the right implementation. For instance:
public SelectingUserContextProxy : IUserContext {
private readonly Func<bool> selector;
private readonly IUserContext trueContext;
private readonly IUserContext falseContext;
public SelectingUserContextProxy(Func<bool> selector,
IUserContext trueContext, IUserContext falseContext) {
this.selector = selector;
this.trueContext = trueContext;
this.falseContext = falseContext;
}
public IPrincipal User { get { return this.Context.User; } }
public Tenant Tenant { get { return this.Context.Tenant; } }
private IUserContext Context {
get { return selector() ? trueContext : falseContext; }
}
}
And you can register this as follows:
var jobContext = new JobServiceUserContext();
container.RegisterSingle<IUserContext>(
new SelectingUserContextProxy(
() => HttpContext.Current != null,
trueContext: new AspNetUserContext(),
falseContext: jobContext));

Related

ASP.NET MVC 5 + EF6 + Ninject - Multitenancy Database

I have a business ASP.NET MVC5 application where each customer has his own database. I want to use EF6 and Ninject for DI. For login I'm using ASP.NET Identity.
For each user exists a UserClaim where the name of the database is specified:
UserId = 1 | ClaimType = "db_name" | ClaimValue = "Customer0001"
UserId = 2 | ClaimType = "db_name" | ClaimValue = "Customer0002"
and so on... This means it is one web-application with a "shared" database for user authentication and on the other side each customers has his own database - all databases are located on the same database server (MS SQL Server).
The user need to login in, after login he should receive data from his personal database (specified in the UserClaim-Table).
For Ninject I think I have to something like this
private void AddBindings() {
kernel.Bind<EFDBContext>().ToMethod(c => new EFDBContext("db_name"));
}
But how would I get the UserClaim into the bindings? (I don't want to use a Session, because sessions can get lost).
And what steps after the bindings are necessary?
For example at the AccountRepository the EFDBContext expects the "db_name" > but how would I get it there?
public class AccountRepository : IAccountRepository {
private EFDBContext context = new EFDBContext("db_name");
}
And finally I can change the connection string inside of this class??
public class EFDBContext : DbContext {
public EFDBContext(string db_name) : base("EFDBContext") {
}
}
UPDATE AFTER #Hooman Bahreini ANSWER
NinjectDependencieResolver.cs
private void AddBindings() {
kernel.Bind<ICustomerRepository>().To<CustomerRepository>().WithConstructorArgument("http_current_context", HttpContext.Current);
}
CustomerRepository.cs
public class CustomerRepository : ICustomerRepository {
private CustomerDBContext context;
public CustomerRepository(HttpContext httpContext) {
string db_name = "";
var claimValue = ((ClaimsPrincipal)HttpContext.Current.User).Claims.FirstOrDefault(c => c.Type == "db_name");
if(claimValue != null) {
db_name = claimValue.Value.ToString();
}
context = new CustomerDBContext(db_name);
}
public IEnumerable<Test> Tests {
get { return context.Test; }
}
}
DB-Context-File
public class CustomerDBContext : DbContext {
public CustomerDBContext(string db_name) : base("CustomerDBContext") {
string temp_connection = Database.Connection.ConnectionString.Replace(";Initial Catalog=;", ";Initial Catalog=" + db_name + ";");
Database.Connection.ConnectionString = temp_connection;
}
public DbSet<Test> Test { get; set; }
}
You can access user claims from HttpContext:
var claimValue = ((ClaimsPrincipal)HttpContext.Current.User)
.Claims
.FirstOrDefault(c => c.Type == "db_name");
For your ninject code, you can create an extension method for HttpContext:
public static HttpcontextExtensions
{
public static string GetDbName(this HttpContext context)
{
return ((ClaimsPrincipal)context.Current.User)
.Claims
.FirstOrDefault(c => c.Type == "db_name");
}
}
And use the following ninject binding:
kernel.Bind<ICustomerRepository>()
.To<CustomerRepository>()
.WithConstructorArgument("db_name", HttpContext.GetDbName());
See this document for more info about accessing HttpContext in ninject.
In your example, CustomerRepository has a dependency on HttpContext, this is not a good design. CustomerRepository requires a db-name, and that's what should be passed in the constructor. Related to this is Nikola’s 4th law of IoC
Every constructor of a class being resolved should not have any
implementation other than accepting a set of its own dependencies.
To give you an example, you don't have any HttpContext in your test project, which makes unit testing CustomerRepository complicated.
P.S. I don't know your design, but maybe getting db-name from HttpContext is not an ideal solution... user may logout or clear their browser history and you will loose your db-name.

How are ASP.NET Roles used with Authorization?

I'm using ASP.NET Core and hosting what is basically the default template with Windows Authentication enabled. I'm hosting this on a dedicated IIS server, and have verified the app is receiving correct information from AD and it correctly authenticates my session.
I feel like I'm trying to do something very simple. If the user is in the security group (from AD) "Admin" they are able to access a specific function. If they aren't in that group they do not get access.
I slapped on the [Authorize] attribute to the service
(in ConfigureServices)
services.AddAuthentication(IISDefaults.AuthenticationScheme);
(in Configure)
app.UseAuthorization();
(in service)
[Authorize]
public class SiteService
{
private readonly string _route;
private readonly HttpClient _httpClient;
public SiteService(HttpClient httpClient)
{
_httpClient = httpClient;
_route = httpClient.BaseAddress.AbsoluteUri;
}
public async Task<IEnumerable<Site>> GetSites()
{
}
}
I can see in the logs that accessing the service gives me Domain/User. I then looked up the MS Docs here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-3.1
And slapped on [Authorize(Roles = "Admin"). That worked. I then switched "Admin" with "sldkfjslksdlfkj". Nothing changed...I can still access the service.
Why is the Roles="x" check not working? How can I enable a relatively simple check to AD for a Security Group?
You could write a custom Policy Authorization handlers to check all of the users' ADGroups and check if they contain the desired group name.
Refer to the following:
1.Create CheckADGroupRequirement(accept a parameter)
public class CheckADGroupRequirement : IAuthorizationRequirement
{
public string GroupName { get; private set; }
public CheckADGroupRequirement(string groupName)
{
GroupName = groupName;
}
}
2.Create CheckADGroupHandler
public class CheckADGroupHandler : AuthorizationHandler<CheckADGroupRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
CheckADGroupRequirement requirement)
{
//var isAuthorized = context.User.IsInRole(requirement.GroupName);
var groups = new List<string>();//save all your groups' name
var wi = (WindowsIdentity)context.User.Identity;
if (wi.Groups != null)
{
foreach (var group in wi.Groups)
{
try
{
groups.Add(group.Translate(typeof(NTAccount)).ToString());
}
catch (Exception e)
{
// ignored
}
}
if(groups.Contains(requirement.GroupName))//do the check
{
context.Succeed(requirement);
}
}
return Task.CompletedTask;
}
}
3.Register Handler in ConfigureServices
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
policy.Requirements.Add(new CheckADGroupRequirement("DOMAIN\\Domain Admin")));//set your desired group name
//other policies
});
services.AddSingleton<IAuthorizationHandler, CheckADGroupHandler>();
4.Use on controller/service
[Authorize(Policy = "AdminOnly")]
public class SiteService

How to create an object once and use it several times in Controller

I want to populate an object using methods in a Controller class. So I've created the object in the Controller class and then tried to populate it using methods in the class. This does not work though, because everytime a method in a controller is called, the entire Controller class is reinitiated. So I get a brand new object everytime I try to populate the object. However, I don't know how else I can create an object and populate it. I've added the code below. The object I'm talking about is ProcessModel. Ignore the other objects I created at the top of the class.
Controller:
public class HomeController : Controller
{
ProcessModel pm = new ProcessModel();
RetrievePatterns pt = new RetrievePatterns();
RetrieveModel rm = new RetrieveModel();
public IActionResult Index()
{
FindPatterns fp = new FindPatterns(rm.pm, pt.KpiPatterns);
ViewData["KPIs"] = fp.passdata;
return View();
}
[HttpPost]
public IActionResult AddEvent([FromBody] Event data)
{
data.ID = pm.EventObjects.Count + 1;
pm.EventObjects.Add(data);
return Json(pm.EventObjects.Count);
}
[HttpPost]
public IActionResult AddProcessName(string data)
{
pm.ID = 1;
pm.Name = data;
return Json(new { title = pm.Name });
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public ActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
Object:
public class ProcessModel
{
public List<Event> EventObjects = new List<Event>();
public List<Entity> EntityObjects = new List<Entity>();
public int ID { get; set; }
public string Name { get; set; }
}
You could create a Singleton class which is responsible to create only one instance from Process model;
public class ProcessModelSingleton
{
private static ProcessModel _processModel = new ProcessModel();
private ProcessModelSingleton()
{
}
public static ProcessModel Instance
{
get { return _processModel; }
}
}
Then assign it a global variable in the controller;
ProcessModel pm = ProcessModelSingleton.Instance;
EDIT
Created instance by singleton class shared by all users. So, if you want to make it user specific, using Session is the best option.
public ProcessModel pm {
get
{
if (Session["ProcessModel"] == null)
{
Session["ProcessModel"] = new ProcessModel();
}
return (ProcessModel)Session["ProcessModel"];
}
}
Keep in mind static variables are shared across all users for that web server. So data populated into a singleton class by one user's request can be read/overwritten by a different user's request. This may be what you are after, but if not you should look into Session State.
ASP.NET Session State Overview
As HTTP is stateless by nature, usage of sessions are discouraged my Microsoft for Asp.NET. By default they are only visible to the web server that creates them so if you are using a farm, you either need to look at server affinity (also called sticky sessions) with a load balancer or out of proc state (such as SQL Server or NCache).
Ideally your application design should avoid the need for sessions and carry only the necessary data between requests via cookies and/or query strings. For more complex applications however this is usually not possible and so Session State is used.

ASP.NET MVC - Alternative to Role Provider?

I'm trying to avoid the use of the Role Provider and Membership Provider since its way too clumsy in my opinion, and therefore I'm trying to making my own "version" which is less clumsy and more manageable/flexible. Now is my question.. is there an alternative to the Role Provider which is decent? (I know that I can do custom Role provier, membership provider etc.)
By more manageable/flexible I mean that I'm limited to use the Roles static class and not implement directly into my service layer which interact with the database context, instead I'm bound to use the Roles static class which has its own database context etc, also the table names is awful..
Thanks in advance.
I'm in the same boat as you - I've always hated the RoleProviders. Yeah, they're great if you want to get things up and running for a small website, but they're not very realistic. The major downside I've always found is that they tie you directly to ASP.NET.
The way I went for a recent project was defining a couple of interfaces that are part of the service layer (NOTE: I simplified these quite a bit - but you could easily add to them):
public interface IAuthenticationService
{
bool Login(string username, string password);
void Logout(User user);
}
public interface IAuthorizationService
{
bool Authorize(User user, Roles requiredRoles);
}
Then your users could have a Roles enum:
public enum Roles
{
Accounting = 1,
Scheduling = 2,
Prescriptions = 4
// What ever else you need to define here.
// Notice all powers of 2 so we can OR them to combine role permissions.
}
public class User
{
bool IsAdministrator { get; set; }
Roles Permissions { get; set; }
}
For your IAuthenticationService, you could have a base implementation that does standard password checking and then you could have a FormsAuthenticationService that does a little bit more such as setting the cookie etc. For your AuthorizationService, you'd need something like this:
public class AuthorizationService : IAuthorizationService
{
public bool Authorize(User userSession, Roles requiredRoles)
{
if (userSession.IsAdministrator)
{
return true;
}
else
{
// Check if the roles enum has the specific role bit set.
return (requiredRoles & user.Roles) == requiredRoles;
}
}
}
On top of these base services, you could easily add services to reset passwords etc.
Since you're using MVC, you could do authorization at the action level using an ActionFilter:
public class RequirePermissionFilter : IAuthorizationFilter
{
private readonly IAuthorizationService authorizationService;
private readonly Roles permissions;
public RequirePermissionFilter(IAuthorizationService authorizationService, Roles requiredRoles)
{
this.authorizationService = authorizationService;
this.permissions = requiredRoles;
this.isAdministrator = isAdministrator;
}
private IAuthorizationService CreateAuthorizationService(HttpContextBase httpContext)
{
return this.authorizationService ?? new FormsAuthorizationService(httpContext);
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var authSvc = this.CreateAuthorizationService(filterContext.HttpContext);
// Get the current user... you could store in session or the HttpContext if you want too. It would be set inside the FormsAuthenticationService.
var userSession = (User)filterContext.HttpContext.Session["CurrentUser"];
var success = authSvc.Authorize(userSession, this.permissions);
if (success)
{
// Since authorization is performed at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether or not a page should be served from the cache.
var cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0));
cache.AddValidationCallback((HttpContext context, object data, ref HttpValidationStatus validationStatus) =>
{
validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context));
}, null);
}
else
{
this.HandleUnauthorizedRequest(filterContext);
}
}
private void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Ajax requests will return status code 500 because we don't want to return the result of the
// redirect to the login page.
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new HttpStatusCodeResult(500);
}
else
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
public HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
{
var authSvc = this.CreateAuthorizationService(httpContext);
var userSession = (User)httpContext.Session["CurrentUser"];
var success = authSvc.Authorize(userSession, this.permissions);
if (success)
{
return HttpValidationStatus.Valid;
}
else
{
return HttpValidationStatus.IgnoreThisRequest;
}
}
}
Which you can then decorate on your controller actions:
[RequirePermission(Roles.Accounting)]
public ViewResult Index()
{
// ...
}
The advantage of this approach is you can also use dependency injection and an IoC container to wire things up. Also, you can use it across multiple applications (not just your ASP.NET one). You would use your ORM to define the appropriate schema.
If you need more details around the FormsAuthorization/Authentication services or where to go from here, let me know.
EDIT: To add "security trimming", you could do it with an HtmlHelper. This probably needs a little more... but you get the idea.
public static bool SecurityTrim<TModel>(this HtmlHelper<TModel> source, Roles requiredRoles)
{
var authorizationService = new FormsAuthorizationService();
var user = (User)HttpContext.Current.Session["CurrentUser"];
return authorizationService.Authorize(user, requiredRoles);
}
And then inside your view (using Razor syntax here):
#if(Html.SecurityTrim(Roles.Accounting))
{
<span>Only for accounting</span>
}
EDIT: The UserSession would look something like this:
public class UserSession
{
public int UserId { get; set; }
public string UserName { get; set; }
public bool IsAdministrator { get; set; }
public Roles GetRoles()
{
// make the call to the database or whatever here.
// or just turn this into a property.
}
}
This way, we don't expose the password hash and all other details inside the session of the current user since they're really not needed for the user's session lifetime.
I have implemented a role provider based on #TheCloudlessSky post here. There are few things that I thought I can add and share what I have done.
First if you want to use the RequirepPermission class for your action filters as an attribute you need to implement ActionFilterAttribute class for RequirepPermission class.
Interface classes IAuthenticationService and IAuthorizationService
public interface IAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public interface IAuthorizationService
{
bool Authorize(UserSession user, string[] requiredRoles);
}
FormsAuthenticationService class
/// <summary>
/// This class is for Form Authentication
/// </summary>
public class FormsAuthenticationService : IAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException(#"Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
UserSession calss
public class UserSession
{
public string UserName { get; set; }
public IEnumerable<string> UserRoles { get; set; }
}
Another point is FormsAuthorizationServiceclass and how we can assign a user to the httpContext.Session["CurrentUser"]. My Approach in this situation is to create a new instance of userSession class and directly assign the user from httpContext.User.Identity.Name to the userSession variable as you can see in FormsAuthorizationService class.
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
public class RequirePermissionAttribute : ActionFilterAttribute, IAuthorizationFilter
{
#region Fields
private readonly IAuthorizationService _authorizationService;
private readonly string[] _permissions;
#endregion
#region Constructors
public RequirePermissionAttribute(string requiredRoles)
{
_permissions = requiredRoles.Trim().Split(',').ToArray();
_authorizationService = null;
}
#endregion
#region Methods
private IAuthorizationService CreateAuthorizationService(HttpContextBase httpContext)
{
return _authorizationService ?? new FormsAuthorizationService(httpContext);
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var authSvc = CreateAuthorizationService(filterContext.HttpContext);
// Get the current user... you could store in session or the HttpContext if you want too. It would be set inside the FormsAuthenticationService.
if (filterContext.HttpContext.Session == null) return;
if (filterContext.HttpContext.Request == null) return;
var success = false;
if (filterContext.HttpContext.Session["__Roles"] != null)
{
var rolesSession = filterContext.HttpContext.Session["__Roles"];
var roles = rolesSession.ToString().Trim().Split(',').ToList();
var userSession = new UserSession
{
UserName = filterContext.HttpContext.User.Identity.Name,
UserRoles = roles
};
success = authSvc.Authorize(userSession, _permissions);
}
if (success)
{
// Since authorization is performed at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether or not a page should be served from the cache.
var cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0));
cache.AddValidationCallback((HttpContext context, object data, ref HttpValidationStatus validationStatus) =>
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}, null);
}
else
{
HandleUnauthorizedRequest(filterContext);
}
}
private static void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Ajax requests will return status code 500 because we don't want to return the result of the
// redirect to the login page.
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new HttpStatusCodeResult(500);
}
else
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
private HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
{
var authSvc = CreateAuthorizationService(httpContext);
if (httpContext.Session != null)
{
var success = false;
if (httpContext.Session["__Roles"] != null)
{
var rolesSession = httpContext.Session["__Roles"];
var roles = rolesSession.ToString().Trim().Split(',').ToList();
var userSession = new UserSession
{
UserName = httpContext.User.Identity.Name,
UserRoles = roles
};
success = authSvc.Authorize(userSession, _permissions);
}
return success ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest;
}
return 0;
}
#endregion
}
internal class FormsAuthorizationService : IAuthorizationService
{
private readonly HttpContextBase _httpContext;
public FormsAuthorizationService(HttpContextBase httpContext)
{
_httpContext = httpContext;
}
public bool Authorize(UserSession userSession, string[] requiredRoles)
{
return userSession.UserRoles.Any(role => requiredRoles.Any(item => item == role));
}
}
then in your controller after the user is authenticated you can get roles from the database and assign it to the roles session:
var roles = Repository.GetRolesByUserId(Id);
if (ControllerContext.HttpContext.Session != null)
ControllerContext.HttpContext.Session.Add("__Roles",roles);
FormsService.SignIn(collection.Name, true);
After the user is logged out of the system you can clear the session
FormsService.SignOut();
Session.Abandon();
return RedirectToAction("Index", "Account");
The caveat in this model is that, when the user is signed into the system, if a role is assigned to the user, authorization doesn't work unless he logs out and logs back in the system.
Another thing is that there is no need to have a separate class for roles, since we can get roles directly from database and set it into roles session in a controller.
After you are done with implementing all these codes one last step is to bind this attribute to your methods in your controller:
[RequirePermission("Admin,DM")]
public ActionResult Create()
{
return View();
}
If you use Castle Windsor Dependency Injection you can inject lists of RoleProviders that can be used to ascertain user rights from any source you choose to implement.
http://ivida.co.uk/2011/05/18/mvc-getting-user-roles-from-multiple-sources-register-and-resolve-arrays-of-dependencis-using-the-fluent-api/
You don't need to use a static class for roles. For instance, the SqlRoleProvider allows you to define the roles in a database.
Of course, if you want to retrieve roles from your own service layer, it's not that hard to create your own role provider - there really aren't that many methods to implement.
You can implement your own membership and role providers by overriding the appropriate interfaces.
If you want to start from scratch, typically these types of things are implemented as a custom http module which stores the users credentials either in the httpcontext or the session. Either way you'll probably want to set a cookie with some sort of authentication token.

ASP.NET Session Issue

I have a custom ASP.NET session manager class as follows:
public sealed class SessionManager : Page
{
private const string USER = "User";
private static readonly SessionManager _instance = new SessionManager();
private SessionManager()
{
}
public static SessionManager Instance
{
get { return _instance; }
}
public User User
{
get { return Session[USER] as User; }
set { Session[USER] = value; }
}
}
After a user successfully logs into the system his full name is displayed on the Home page. Below is the problem I am facing:
1) I first log into the system as John and John's full name is displayed on the homepage and the corresponding user object is kept in session.
2) Now from a different PC I login to the system as Mark. Now Mark's full name is displayed on the homepage and the corresponding user object is kept in session.
3) Now when I go to the PC from which John has logged in and refresh the homepage I see Marks name instead of Johns name.
What could be the reason for this strange behavior?
Your class inherits from System.Web.UI.Page, which sets its Session member to HttpContext.Current.Session on first access. Since you have a singleton, it will always refer to the first session in which the User property was accessed.
You probably should do something like this:
public sealed class SessionManager
{
private const string USER = "User";
private static readonly SessionManager _instance = new SessionManager();
private SessionManager()
{
}
public static SessionManager Instance
{
get { return _instance; }
}
public User User
{
get { return HttpContext.Current.Session[USER] as User; }
set { HttpContext.Current.Session[USER] = value; }
}
}

Resources