Asp.net MVC Let user switch between roles - asp.net-mvc

I'm developing a complex website with users having multiple roles. The users are also coupled on other items in the DB which, together with their roles, will define what they can see and do on the website.
Now, some users have more than 1 role, but the website can only handle 1 role at a time because of the complex structure.
the idea is that a user logs in and has a dropdown in the corner of the website where he can select one of his roles. if he has only 1 role there is no dropdown.
Now I store the last-selected role value in the DB with the user his other settings. When he returns, this way the role is still remembered.
The value of the dropdown should be accessible throughout the whole website.
I want to do 2 things:
Store the current role in a Session.
Override the IsInRole method or write a IsCurrentlyInRole method to check all access to the currently selected Role, and not all roles, as does the original IsInRole method
For the Storing in session part I thought it'd be good to do that in Global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
if (User != null && User.Identity.IsAuthenticated) {
//check for roles session.
if (Session["CurrentRole"] == null) {
NASDataContext _db = new NASDataContext();
var userparams = _db.aspnet_Users.First(q => q.LoweredUserName == User.Identity.Name).UserParam;
if (userparams.US_HuidigeRol.HasValue) {
var role = userparams.aspnet_Role;
if (User.IsInRole(role.LoweredRoleName)) {
//safe
Session["CurrentRole"] = role.LoweredRoleName;
} else {
userparams.US_HuidigeRol = null;
_db.SubmitChanges();
}
} else {
//no value
//check amount of roles
string[] roles = Roles.GetRolesForUser(userparams.aspnet_User.UserName);
if (roles.Length > 0) {
var role = _db.aspnet_Roles.First(q => q.LoweredRoleName == roles[0].ToLower());
userparams.US_HuidigeRol = role.RoleId;
Session["CurrentRole"] = role.LoweredRoleName;
}
}
}
}
}
but apparently this gives runtime errors. Session state is not available in this context.
How do I fix this, and is this
really the best place to put this
code?
How do I extend the user (IPrincipal?) with IsCurrentlyInRole without losing all other functionality
Maybe i'm doing this all wrong and there is a better way to do this?
Any help is greatly appreciated.

Yes, you can't access session in Application_AuthenticateRequest.
I've created my own CustomPrincipal. I'll show you an example of what I've done recently:
public class CustomPrincipal: IPrincipal
{
public CustomPrincipal(IIdentity identity, string[] roles, string ActiveRole)
{
this.Identity = identity;
this.Roles = roles;
this.Code = code;
}
public IIdentity Identity
{
get;
private set;
}
public string ActiveRole
{
get;
private set;
}
public string[] Roles
{
get;
private set;
}
public string ExtendedName { get; set; }
// you can add your IsCurrentlyInRole
public bool IsInRole(string role)
{
return (Array.BinarySearch(this.Roles, role) >= 0 ? true : false);
}
}
My Application_AuthenticateRequest reads the cookie if there's an authentication ticket (user has logged in):
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[My.Application.FORMS_COOKIE_NAME];
if ((authCookie != null) && (authCookie.Value != null))
{
Context.User = Cookie.GetPrincipal(authCookie);
}
}
public class Cookie
{
public static IPrincipal GetPrincipal(HttpCookie authCookie)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null)
{
string ActiveRole = "";
string[] Roles = { "" };
if ((authTicket.UserData != null) && (!String.IsNullOrEmpty(authTicket.UserData)))
{
// you have to parse the string and get the ActiveRole and Roles.
ActiveRole = authTicket.UserData.ToString();
Roles = authTicket.UserData.ToString();
}
var identity = new GenericIdentity(authTicket.Name, "FormAuthentication");
var principal = new CustomPrincipal(identity, Roles, ActiveRole );
principal.ExtendedName = ExtendedName;
return (principal);
}
return (null);
}
}
I've extended my cookie adding the UserData of the Authentication Ticket. I've put extra-info here:
This is the function which creates the cookie after the loging:
public static bool Create(string Username, bool Persistent, HttpContext currentContext, string ActiveRole , string[] Groups)
{
string userData = "";
// You can store your infos
userData = ActiveRole + "#" string.Join("|", Groups);
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(
1, // version
Username,
DateTime.Now, // creation
DateTime.Now.AddMinutes(My.Application.COOKIE_PERSISTENCE), // Expiration
Persistent, // Persistent
userData); // Additional informations
string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(My.Application.FORMS_COOKIE_NAME, encryptedTicket);
if (Persistent)
{
authCookie.Expires = authTicket.Expiration;
authCookie.Path = FormsAuthentication.FormsCookiePath;
}
currentContext.Response.Cookies.Add(authCookie);
return (true);
}
now you can access your infos everywhere in your app:
CustomPrincipal currentPrincipal = (CustomPrincipal)HttpContext.User;
so you can access your custom principal members: currentPrincipal.ActiveRole
When the user Changes it's role (active role) you can rewrite the cookie.
I've forgot to say that I store in the authTicket.UserData a JSON-serialized class, so it's easy to deserialize and parse.
You can find more infos here

If you truly want the user to only have 1 active role at a time (as implied by wanting to override IsInRole), maybe it would be easiest to store all of a user's "potential" roles in a separate place, but only actually allow them to be in 1 ASP.NET authentication role at a time. When they select a new role use the built-in methods to remove them from their current role and add them to the new one.

Related

What's the return value of DBSet.Add(object o)

Consider the situation.
I have a userlogin table. the userlogin has the following fields.
userid(identity(1,1)), username(unique), password(string)
I have another table, userRole with following fields.
userid(fk referencing userlogin), role(string)
Now suppose I want to add an admin user to my empty application database.
What I am currently doing is:
// Check Userlogin if it contains adminuser1 as username, if not, add adminuser1 with password xyz.
UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
context.UserLogins.Add(login);
context.SaveChanges();
// query again from database to get the userid
Userlogin user = context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password == "xyz"));
int userid = user.userid;
UserRole admin = new UserRole();
admin.userid = userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
I want to make it a less troublesome, if we can get the userid of userRecently Added, without making another request.
I mean I want to do this if it is possible.
UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
UserLogin user = context.UserLogins.Add(login);
UserRole admin = new UserRole();
admin.userid = user.userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
Update
I also wanted to know if there is some way to do
context.UserLogins.Single(l => l == login);
instead of
context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));
because I use the same method in large classes in many fields.
It can be different based on your needs but you can have something like:
public class UserRole
{
public int Id { get; set; }
public string role { get; set; }
}
public class UserLogin
{
public int Id { get; set; }
public string username { get; set; }
public string password { get; set; }
public UserRole Role { get; set; }
}
and then use them like:
var login = new UserLogin
{
username = "adminuser1",
password = "xyz"
};
var admin = context.UserRoles.Single(_=> _.role == "admin");
if (admin == null)
{
admin = new UserRole
{
role = "admin"
};
}
login.Role = admin;
context.UserLogins.Add(login);
context.SaveChanges();
Your models' relationship seems wrong but based on your information you can have this:
var login = context.UserLogins.Single(_ => _.username == "adminuser1");
if (login == null)
{
login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
context.UserLogins.Add(login);
context.SaveChanges();
}
else
{
// this user already exists.
}
var admin = context.UserRoles.Single(_ => _.role == "admin");
if (admin == null)
{
admin.userid = login.userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
}
else
{
// the role already exists.
}
context.UserLogins.Single(l => l == login); would not work for you! you have to query DB based on your model key, not whole model data!
For the question
What's the return value of DBSet.Add(object o)
The answer is: it will return the same object o(i.e. without the userid). Simply because userid is an identity column and relies on the database, its value is only available after context.SaveChanges() is called. Since Add() method only registers that a change will take place after SaveChanges() is called.
For the answer to update,
Instead of using
context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));
For classes that have many fields, I can check if there are any unique columns. For example. I could use, simply
context.UserLogins.Single(l => l.username == "adminuser1");
Just because, username(unique) is specified in the question.
I would rather recommend people use a single Stored Procedure. The calling of context.SaveChanges() and the context.xyz.Single() require opening database connection multiple times. For optimising performance you can use Stored Procedures, as they require only one connection per task. For more information.
Understang Performance Considerations
As I am using database first approach, I found this link also helpful.
Use Stored Procedure in Entity Framework
Thanks :)

Authorize an Action using URL parameters

I have a MVC 5 application that has controllers dressed with the [Authorize] attribute. However, requirements state that clients may not be able to login to the web application (as this web app will be deployed on signage players -- not web browsers -- that accepts URLs as input to access specific actions in the web app).
In response, I was thinking about using a URL that a client could use that would authorize their actions, in place of logging in...in the format of:
http://{website}/Action?token={/* randomly generated key for this user */}
How would I go about implementing this without changing my current code dressed with the [Authorize] attribute?
I did change my code slightly. Instead of dressing my controllers with [Authorize], I created a custom authorize attribute called [TokenAuthorize].
I created a SecurityManager class to generate and validate a token. This was adapted from Primary Objects, although I chose not to use any of their client-side code or hash using ip or userAgent. Also, I created a TokenIdentity class to create an Identity for authorizing an action. This was adapted from Steve's Coding Blog. Jelle's link also helped in authorizing a user by token using GenericPrincipal: HttpContext.Current.User = new GenericPrincipal(new TokenIdentity(username), roles.ToArray());
After implementing this, I was able to authorize an action using a url parameter called token: http://{website}/Action?token={/* randomly generated key for this user */}
TokenAuthorize.cs
public class TokenAuthorize : AuthorizeAttribute
{
private const string SecurityToken = "token";
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (Authorize(filterContext))
{
return;
}
HandleUnauthorizedRequest(filterContext);
}
private bool Authorize(AuthorizationContext actionContext)
{
try
{
HttpContextBase context = actionContext.RequestContext.HttpContext;
string token = context.Request.Params[SecurityToken];
// check if the token is valid. if so, authorize action.
bool isTokenAuthorized = SecurityManager.IsTokenValid(token);
if (isTokenAuthorized) return true;
// if the token is not valid, check if the user is authorized by default.
bool isDefaultAuthorized = AuthorizeCore(context);
return isDefaultAuthorized;
}
catch (Exception)
{
return false;
}
}
}
SecurityManager.cs (adapted from Primary Objects)
public class SecurityManager
{
private const string Alg = "HmacSHA256";
private const string Salt = "rz8LuOtFBXphj9WQfvFh";
// Generates a token to be used in API calls.
// The token is generated by hashing a message with a key, using HMAC SHA256.
// The message is: username
// The key is: password:salt
public static string GenerateToken(string username, string password)
{
string hash = string.Join(":", new string[] { username });
string hashLeft;
string hashRight;
using (HMAC hmac = HMAC.Create(Alg))
{
hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
hashLeft = Convert.ToBase64String(hmac.Hash);
hashRight = string.Join(":", username);
}
return Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight)));
}
// used in generating a token
private static string GetHashedPassword(string password)
{
string key = string.Join(":", new string[] { password, Salt });
using (HMAC hmac = HMAC.Create(Alg))
{
// Hash the key.
hmac.Key = Encoding.UTF8.GetBytes(Salt);
hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
return Convert.ToBase64String(hmac.Hash);
}
}
// Checks if a token is valid.
public static bool IsTokenValid(string token)
{
var context = new ApplicationDbContext();
try
{
// Base64 decode the string, obtaining the token:username.
string key = Encoding.UTF8.GetString(Convert.FromBase64String(token));
// Split the parts.
string[] parts = key.Split(':');
if (parts.Length != 2) return false;
// Get the username.
string username = parts[1];
// Get the token for said user
// var computedToken = ...
// Compare the computed token with the one supplied and ensure they match.
var result = (token == computedToken);
if (!result) return false;
// get roles for user (ASP.NET Identity 2.0)
var user = context.Users.Single(u => u.UserName == username);
var rolesPerUser = context.UserRoles.Where(x => x.UserId == user.Id).ToList();
var roles = rolesPerUser.Select(role => context.Roles.Single(r => r.Id == role.RoleId).Name);
// NOTE: define public DbSet<IdentityUserRole> UserRoles { get; set; } ...
// ... in your DbContext in IdentityModels.cs
HttpContext.Current.User = new GenericPrincipal(new TokenIdentity(username), roles.ToArray());
return true;
}
catch
{
return false;
}
}
}
TokenIdentity.cs (adapted from Steve's Coding Blog)
public class TokenIdentity : IIdentity
{
public string User { get; private set; }
public TokenIdentity(string user)
{
this.User = user;
}
public string Name => User;
public string AuthenticationType => "ApplicationToken";
public bool IsAuthenticated => true;
}

Remove User from Roles in ASP.NET Identity 2.x

How can I remove User from Roles in ASP.NET Identity 2.x ?
about adding role to user there is no problem but when I want to remove a role from a user I cannot.It should be mentioned that there is no exception or error!
//POST: Admin/User/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Prefix = "")]UserViewModel userViewModel, List<int> availableRoles)
{
if (ModelState.IsValid)
{
List<int> newListOfRolesIDs = availableRoles;
List<int> oldListOfRolesIDs = UserBLL.Instance.GetRolesIDs(userViewModel.Id);
List<int> deletedList;
List<int> addedList;
var haschanged = oldListOfRolesIDs.ChangeTracking(newListOfRolesIDs, out deletedList, out addedList);
using (new EFUnitOfWorkFactory().Create())
{
if (haschanged)
{
UserBLL.Instance.InsertRoles(addedList, userViewModel.Id);
UserBLL.Instance.DeleteRoles(deletedList, userViewModel.Id);
}
await UserBLL.Instance.UpdateAsync(userViewModel);
}
//ArticleBLL.Instance.UpdatePartial(articleViewModel, m => m.Title);
return RedirectToAction("Edit");
}
return View(userViewModel);
}
Delete Role method:
public void DeleteRoles(List<int> deleteList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in deleteList)
{
user.Roles.Remove(new UserRole { RoleId = i, UserId = user.Id }); // What's the problem?!
}
}
}
Insert Role method:
public void InsertRoles(List<int> insertList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in insertList)
{
user.Roles.Add(new UserRole { RoleId = i, UserId = user.Id });
}
}
}
What you are looking for is the RemoveFromRoleAsync method. An example would look similar to the following:
public async Task DeleteRolesAsync(List<string> deleteList, int? userId)
{
if (userId != null)
{
foreach (var roleName in deleteList)
{
IdentityResult deletionResult = await UserManager.RemoveFromRoleAsync(userId, roleName);
}
}
}
If you already have the ID of the user, there's no need to get the user again (only if you want to make sure that the user really exists; then you have to wrap your foreach with an if-statement). The deletion methods needs the name of the role, instead of the ID, to delete the user from the role. You can use the result of the operation (in my example stored in deletionResult) to make sure that the operation was successful. Remember that the name of the user manager (in my example UserManager) can vary depending on your implementation.
I had the same issue and what I ended up using was the
RemoveFromRolesAsync(string userId, params string[] roles) Method
from the UserManager.
Using the role names in an array works.
But has an issue that is if the user is not in one of the roles in the array the user will not be removed from any roles in the array.
All or nothing.
var usr = UserManager.FindById(usrV.ID.ToString());
string[] deleteList;
deleteList= new string[1];
deleteList[0] = "Engineer";
var rresult1 = UserManager.RemoveFromRolesAsync(usr.Id, deleteList);
Hope it helps
You might want to check out this blog post. The ASP.NET team has a sample that includes adding and removing roles from a user.
ASP.NET Identity 2.0: Customizing Users and Roles

ASP.NET External Authentication Services Integration

My ASP.NET webapp will be protected by third party agent(SM). SM will intercept every call to the webapp, authenticate the user as valid system user, add some header info ex username and redirect it to my webapp. I then need to validate that the user is an active user of my website.
Currently I am authenticating the user by implementing the Application_AuthenticateRequest method in the Global.asax.cs file. I have a custom membership provider whose ValidateUser method, checks if the user exists in the users table of my database.
Just wanted to get comments if this was a good approach or not.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
//if user is not already authenticated
if (HttpContext.Current.User == null)
{
var smcred = ParseAuthorizationHeader(Request);
//validate that this user is a active user in the database via Custom Membership
if (Membership.ValidateUser(smcred.SMUser, null))
{
//set cookie so the user is not re-validated on every call.
FormsAuthentication.SetAuthCookie(smcred.SMUser, false);
var identity = new GenericIdentity(smcred.SMUser);
string[] roles = null;//todo-implement role provider Roles.Provider.GetRolesForUser(smcred.SMUser);
var principal = new GenericPrincipal(identity, roles);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
}
}
protected virtual SMCredentials ParseAuthorizationHeader(HttpRequest request)
{
string authHeader = null;
var smcredential = new SMCredentials();
//here is where I will parse the request header for relevant tokens ex username
//return smcredential;
//mockup below for username henry
return new SMCredentials() { SMUser = "henry", FirstName = "", LastName = "", EmailAddr = "" };
}
I would go with the Attribute approach to keep it more MVC like. It would also allow you more flexibility, you could potentially have different Membership Providers for different controllers/actions.

How to properly map entities to domain models in n-tier architecture?

I created a mid-size project following Project Silk's structure. However, I have trouble mapping the entities I retrieve from my repositories into domain model objects for use in the Web project. I have posted a similar question here with all the code and haven't received the help I'm looking for.
My application's architecture follows Project Silk's very closely. The data tier holds the repositories and model POCOs. The Business Logic layer holds the services. Inside these services, we map objects from the Data Tier to the Model objects in the business layer.
internal static Model.User ToDataModelUser(User userToConvert)
{
if (userToConvert == null)
{
return null;
}
Model.User modelUser = new Model.User()
{
UserId = userToConvert.UserId,
AuthorizationId = userToConvert.AuthorizationId,
DisplayName = userToConvert.DisplayName,
Country = userToConvert.Country,
PostalCode = userToConvert.PostalCode,
HasRegistered = userToConvert.HasRegistered,
};
return modelUser;
}
internal static User ToServiceUser(Model.User dataUser)
{
if (dataUser == null)
{
return null;
}
User user = new User()
{
UserId = dataUser.UserId,
AuthorizationId = dataUser.AuthorizationId,
DisplayName = dataUser.DisplayName,
Country = dataUser.Country,
PostalCode = dataUser.PostalCode,
HasRegistered = dataUser.HasRegistered,
};
return user;
}
My question is how do I map objects like this when they have many-to-many relationships? For example, lets say a User has an ICollection Roles. That means my Role has an ICollection Users. When I'm mapping a users via ToDataModelUser or ToServiceUser, I now have a Roles property to populate. Thus the code from above will look like this:
internal static Model.User ToDataModelUser(User userToConvert)
{
if (userToConvert == null)
{
return null;
}
Model.User modelUser = new Model.User()
{
UserId = userToConvert.UserId,
AuthorizationId = userToConvert.AuthorizationId,
DisplayName = userToConvert.DisplayName,
Country = userToConvert.Country,
PostalCode = userToConvert.PostalCode,
HasRegistered = userToConvert.HasRegistered,
Roles = new Collection<Role>()
};
foreach (Role role in userToConvert.Roles)
modelUser.Roles.Add(RoleServies.ToDataModelRole(role));
return modelUser;
}
Now here comes the problem, if you look at RoleServices.ToDataModelRole(Role role) this is what you get:
internal static Model.Role ToDataModelRole(Role roleToConvert)
{
if (roleToConvert == null) return null;
Model.Role role = new Model.Role()
{
Description = roleToConvert.Description,
RoleId = roleToConvert.RoleId,
RoleName = roleToConvert.RoleName,
Users = new Collection<User>()
};
foreach (User user in roleToConvert.Users)
roleToConvert.Users.Add(UserServices.ToDataModelUser(user));
return role;
}
As you can easily see, if you run this you will get a stack overflow error b/c we will be going from User >> Role >> User >> Role >> etc.. when trying to do the mapping. If I don't map the navigation properties, I don't have access to them in the web project. I have a feeling I am totally missing something here.
You could create an overload for the ToDataModelX methods. Pass a Boolean to de/activate the loading of the subordinate object. Instead of always loading the a Role's Users, only load them when directed to do so.
internal static Model.User ToDataModelUser(User userToConvert)
{
return ToDataModelUser(userToConvert, true);
}
internal static Model.User ToDataModelUser(User userToConvert, Boolean loadRoles)
{
if (userToConvert == null)
{
return null;
}
Model.User modelUser = new Model.User()
{
....
Roles = new Collection<Role>()
};
if (loadRoles)
{
foreach (Role role in userToConvert.Roles)
modelUser.Roles.Add(RoleServies.ToDataModelRole(role, false));
}
return modelUser;
}
internal static Model.Role ToDataModelRole(Role roleToConvert)
{
return ToDataModelRole(roleToConvert, true);
}
internal static Model.Role ToDataModelRole(Role roleToConvert, Boolean loadUsers)
{
if (roleToConvert == null) return null;
Model.Role role = new Model.Role()
{
....
Users = new Collection<User>()
};
if (loadUsers)
{
foreach (User user in roleToConvert.Users)
roleToConvert.Users.Add(UserServices.ToDataModelUser(user, false));
}
return role;
}

Resources