Accesing data from Roles into gridview - asp.net

Is it possible to retrieve the user details into grid view, from Roles assigned through Administrator website?
Is there any other way to do so?

You can also achieve same kind of thing by making the extra column of roles in the database and extracting the value of role during the time of login.
Now you can store this role in any kind of variables like cookies ,sessions etc and performing the following check in the masterpage
if(session[role]==null)
{
Response.Redirect("Home.aspx");
}
else if(session[role]!="User")
{
Response.Redirect("Home.aspx");
}

Related

Individual page authorization based on roles in ASP.NET MVC 5

I am pretty new to ASP.NET MVC, and I'm trying to build a web-site that uses MVC 5's built-in authorization methods.
Here's what I've done so far:
Created a number of users in the AspNetUsers table.
Created a number of roles in the AspNetRoles table.
Assigned roles to users via the AspNetUserRoles table by connecting RoleID and UserID.
Now, to set up a single page to only show certain content to users with the admin-role, and hide it otherwise, I've done this:
#if(User.IsInRole("Admin"))
{
<p>You are logged in as an admin.</p>
} else
{
<p>You are not logged in as an admin.</p>
};
Is this OK to do, or is this bad? I've played around with it for quite some time, and it works as expected (as far as I can tell).
I know I can create CustomAuthorizationAttributes and assign these to the ActionMethods in the Controller, but I'm not 100 % comfortable with the syntax on this.
If you are happy with the syntax, this is fine.
But you cannot forget to protect the view itself with the Authorize attribute. You can use the default as following
[Authorize(Roles = "Admin")]
public ActionResult Register()
{
...
return View();
}

Render different views for different roles just by one action in asp.net mvc

Suppose a web application which has three part or so-called three access level:
One for every visitor (just for seeing the content and no need for authentication)
One for Users (Authorized for users)
One for the Administrator (authorized for admin)
now, administrator has access for every content and every operation in the system and Users could do some operations. I don't wanna to create separate areas for Users and Administrator because I don't want to repeat the same code in every area. for example both admin and user can create product, see the list of products, create catalog and... and also every visitor can also sees the list of product, blog posts, ...
So it's not a good idea to separate and make the code duplicated just for separating the tasks. I haven't created any area and I want to control the authentication and authorization by defining the user role when he/she is in the system(ideas!?) but the main issue comes when I want to have separate user interface (views) for users and admin. as I want to use just one Controller for products, Catalog, ... and set authentication and authorization for them, how can I render different view for every request by admin and user? I also don't want to make my code dirty by putting bunch of if/else to define which view to render (I'd rather to duplicate the code in areas!), any solution?
Probably the easiest solution is to write your own RazorViewEngine(Assuming you are using razor).
Then when you want to retrieve a view for a user, you can check the user role and assign the view you want. This is a basic and crude example:
public override ViewEngineResult FindPartialView(
ControllerContext controllerContext,
string partialViewName,
bool useCache)
{
if (controllerContext.User.IsInRole("Admin"))
{
var adminViewLocations = new string[] {"~/AdminViews/" }
return new ViewEngineResult(adminViewLocations);
}
return base.FindPartialView(controllerContext, partialViewName, useCache);
}
Doing this means that all users use the same controllers and authentication, but the views change based on roles (or whatever you want).
You can read more about A Custom View Engine with Dynamic View Location.

asp.net mvc 3 reset password by admin and force user to change it

I'm using asp.net Membership, I develop an admin page who can regenerate a temp password to send to the user, then when the user log on for first time, the password must be changed, but I cant figure out who to know if the password was reseted.
I tried something like in a base controller:
if (user.LastPasswordChangedDate >= user.LastLoginDate)
{
filterContext.Result = RedirectToAction("ChangePassword", "Account");
}
But, I already have updated the LastLoginDate because the ChangePassword Action need to be with a autenticated user.
I was thinking when reseting the password to lock/unlock the user to get updated the "LastLockoutDate" and do:
if (user.LastPasswordChangedDate >= user.LastLockoutDate)
{
filterContext.Result = RedirectToAction("ChangePassword", "Account");
}
But, I can't find a method to do manual lockout
Thanks!!!
There's a lot of things you could do, some would depend on how your system works. For instance, you could store a specific piece of data in the Comment field, if you're not using comments.
Or, if you don't use the "Approved" bit (that is, when you create new users you do not require them to validate an email or something, but instead create them with IsApproved set to true) then you can set IsApproved to False and force a password change if it's false.
There is no method to access much of this data in the Membership API, you just have to access it from you database.
You could also store this in the Personalization provider.
Another option is to simply avoid storing this in the Membership database, and instead just add a table or a field in your apps data to deal with this.

Asp.net, where to store the username of logged in user?

When a user log into my asp.net site I use the following code:
FormsAuthentication.RedirectFromLoginPage(userid, false);
As I often need to use the userid I can then later get the userid by:
string userid = System.Web.HttpContext.Current.User.Identity.Name;
Now I also want to show the logged in username on each page and my questions is therefore where do I place the username best if I need to use it on every page. User.Identity.Name is already taken by the userid so I can't use that one. Another solution would be to get the username from the database on each page, but that seems like a bad solution.
So: Is the best way to use Sessions to store the username?
There are essentially 6 different ways to store information, each with it's own benefits and drawbacks.
Class member variables. These are only good for the life of one page refresh.
HttpContext variables. Like class member variables, only good for one page refresh.
ViewState, these are passed from page to page to keep state, but increase the size of the downloaded data. Also, not good for sensitive information as it can be decoded.
Cookies. Sent on each page request. Also not good for sensitive information, even encrypted.
Session. Not passed to the end user, so good for sensitive information, but it increases the resource usage of the page, so minimizing usage for busy sites is important.
Authentication Cookie User Data - This is like like cookies, but can be decoded with the authentication data and used to create a custom IIdentity provider that implements your desired Identity information, such as Name or other profile information. The size is limited, however.
You can store just about anything in SessionState in asp.net. Just be careful and store the right things in the right places (you can also use ViewState to store variables.
Check this out for how to use SessionState to store and retrieve variables across postbacks.
public string currentUser
{
get { return Session["currentUser"] as string; }
private set { Session["currentUser"] = value; }
}
Using sessions isn't a bad idea but make sure to check for NULL when retrieving the values for when the sessions time out.
Or you could pass the variable through in the URL e.g
/Set
Response.Redirect("Webform2.aspx?Username=" + this.txtUsername.Text);
/Read
this.txtBox1.Text = Request.QueryString["Username"];

asp.net Membership : Extending Role membership?

I am been taking a look at asp.net membership and it seems to provide everything that i need but i need some kind of custom Role functionality.
Currently i can add user to a role, great.
But i also need to be able to add Permissions to Roles..
i.e.
Role: Editor
Permissions: Can View Editor Menu, Can Write to Editors Table, Can Delete Entries in Editors Table.
Currently it doesn't support this, The idea behind this is to create a admin option in my program to create a role and then assign permissions to a role to say "allow the user to view a certain part of the application", "allow the user to open a menu item"
Any ideas how i would implement soemthing like this?
I presume a custom ROLE provider but i was wondering if some kind of framework extension existed already without rolling my own?
Or anybody knows a good tutorial of how to tackle this issue?
I am quite happy with what asp.net SQL provider has created in terms of tables etc... but i think i need to extend this by adding another table called RolesPermissions
and then I presume :-) adding some kind of enumeration into the table for each valid permission??
THanks in advance
You can programmatically permit or not permit to the user to see some pages, or do some actions using for example the function IsInRole, and check if you let or not a user to do some actions.
HttpContext.Current.User.IsInRole("rolename")
You can make a class/or table with your permissions, and depend from the role that a user belong, to open, close, permit etc a lot of thinks on the same page. I have programming an idea like that on my programs, is very simple.
Here is an idea...
public enum csPermissions
{
pActionDelete = 1,
pActionEdit = 2 ,
...more actions...
}
private int[] AdminPermission = {
(int)csPermissions.pActionEdit,
(int)csPermissions.pActionDelete,
....
};
private int[] BackOfficePermission = {
(int)csPermissions.pActionEdit,
....
};
public static bool IsThisAllowed(csPermissions AskPermitForThisAction)
{
... questions here for all users roles...
... here is only an example .....
if (HttpContext.Current.User.IsInRole("Administator")))
{
for (int i = 0; i < AdminPermission.Length; i++)
if (AdminPermission[i] == (int)AskPermitForThisAction)
return true;
}
...
return false;
}
Hope this help.
You can use the framework to restrict access to entire pages or directories based upon roles. This can be configured in the web.config's authorization element. http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx
Additionally, if you're using a SiteMap for your menu, and have configured authorization, you can use security trimming to restrict the menu. http://www.google.com/search?q=asp.net+security+trimming

Resources