Authentication & Authorization Role issue - asp.net-mvc

i'm having a controller name UserController in Admin Area (section). In which i can assign them Roles Admin (A) to User (U) or User (U) to Admin (A).
when I change role of any user it updated successfully in database also ,but when I login from application that user of which i had changed the role so user contains its old role.I have put the break point also the variable 'role' is returning the previous Role. i'm surprised that how can 'role' variable return its old role.
public override string[] GetRolesForUser(string username)
{
string[] role = { obj.GetAll().Where(x => x.EmailAddress == username).FirstOrDefault().Role };
return role;
}
User Controller AssignRole Action in this code i'm updating the Role
public ActionResult AssignRole(int id, string role)
{
try
{
BOL.tbl_Login user = (BOL.tbl_Login)obj.login.GetById(id);
if (role == "A")
{
user.Role = "U";
}
else if (role == "U")
{
user.Role = "A";
}
else
{
user.Role = "U";
}
obj.login.Update(user);
TempData["Msg"] = "Operation Successfully!";
}
catch (Exception ex)
{
TempData["Msg"] = "Error " + ex.Message;
}
return RedirectToAction("_Index");
}
and i'm also using
[Authorize(Roles = "A")]
I think Entity Framework not returning the newest data.
here is the Data access layer code
public override void Update(T data)
{
obj.Entry(data).State = EntityState.Modified;
obj.Configuration.ValidateOnSaveEnabled = false;
Save();
obj.Configuration.ValidateOnSaveEnabled = true;
}

Your problem is that role is saving both previous and current values. AsNoTracking function do not save previous values it only shows current value. Put my code there where you are getting roles or above your method 'getroles' so your problem will be solved
public override IEnumerable<T> GetAll()
{
return obj.Set<T>().AsNoTracking().ToList();
}

Related

How to Pass Value from a login Page

Hello I need help please
I am creating my first asp mvc Webpage.
I created a login and registration page connected with database.
I want to pass CustomerId from the customer that logged in to a Bookings table
So that it shows bookings related to that customer only.
Bookings table has CustomerId as a foreign key. This is what I have done so far.
public class BookingController : Controller
{
// GET: Booking
public ActionResult Index(int customerId)
{
TravelExpertsEntities bookingdb = new TravelExpertsEntities();
List<Booking> bookings = bookingdb.Bookings.Where(book =>
book.CustomerId == customerId).ToList();
return View(bookings);
}
}
}
//This is from login Controller
public ActionResult Login(Customer reg)
{
if (ModelState.IsValid)
{
var details = (from userlist in db.Customers
where userlist.UserName == reg.UserName &&
userlist.Password == reg.Password
select new
{
userlist.CustomerId,
userlist.UserName
}).ToList();
if (details.FirstOrDefault() != null)
{
Session["CustomerId"] =
details.FirstOrDefault().CustomerId;
Session["Username"] = details.FirstOrDefault().UserName;
return RedirectToAction("Index", "Booking");
}
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
return View(reg);
}
I was able to pull all bookings but I want to filter it with the Customer that logged in.
Replace your RedirectToAction as below, to pass customerId as parameter
var CustomerIdparam=details.FirstOrDefault().CustomerId;
RedirectToAction("Index", "Booking", new{customerId=CustomerIdparam});

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

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;
}

ASP.NET MVC Custom Authorization : AuthorizeAttribute

I'm following this tutorial link
I have a table users {iduser, user, pass, role}
I'm using this users : string[] users = db.users.Select(t => t.user).ToArray();
instead of : string[] users = Users.Split(','); Is it ok ?
My problem is with roles : SiteRoles role = (SiteRoles)httpContext.Session["role"];
Q: Where do I store the role for my user ?
My simplified account controller:
[HttpPost]
public ActionResult Login(LoginModel model)
{
HeliosEntities db = new HeliosEntities();
if (ModelState.IsValid)
{
bool userok = db.users.Any(t => t.user == model.UserName && t.pass == model.Password);
if (userok == true)
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
{
ModelState.AddModelError("", "Incorect password or user!");
}
}
return View();
}
A quick look at your link above shows that it is getting the user's role from session:
(SiteRoles)httpContext.Session["role"];
so you need to set the session value when the user logs in, for example:
var userRole = Roles.Admin | Roles.User;
httpContext.Session["role"] = role;
I don't know where you store the information about what role the user is in though.

Asp.net MVC Let user switch between roles

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.

Resources