Readonly role c# mvc - c#

I have a customroleprovider.cs
I have a user table that has users and their roles. most users have role as user, there are only 3 admin, now i need to create 3 readonly users. these users can only view the whole website, and cannot edit any part of the website. in my views i have these:
#{
var simpleRoles = (RoleProvider)Roles.Provider;
}
#if (simpleRoles.IsUserInRole(User.Identity.Name, "admin"))
{
}
to restrict some areas only for admin, do i need something like this for readonly users?

Since you have admin and users, you may want to create an "admin" area and a "user" area. What I suggested below is only if you have a few views you want to hide from roles. In the admin area you can add the authorize attribute to a base controller for that area so that only admins can update content. Otherwise, you'll have to have if statements in the views if you wanted to hide the update buttons from different appearing for roles, and that could get messy.
UPDATE:
Below is a link for an overview of areas. Areas are nice because you can create an area called "Admin" and inside that area you will have controllers/views/viewmodels, etc... that are separate from a different area. Inside this area you can include the logic for updating content, whereas if you don't want a role to update content then don't include the logic inside their area. Hopefully the link will do a better job explaining it than I can.
When I use areas for my project, I'll create a base controller that all of my controllers inherit from. An example of what my base controller may look like is:
[Authorize(Roles="Admin")]
public class AdminBaseController : Controller
{
...
}
Then in all of my controllers in the area I'll inherit from the AdminBaseController so that only admins can access this section of the website.
public class HomeController : AdminBaseController
{
...
}
http://www.dotnet-tricks.com/Tutorial/mvc/a9P1010113-MVC-Areas-with-example.html
Adding an Authorize attribute on the view:
For example, if you only want admin's to view the view.cshtml file then you can do something like this on the controller action:
[Authorize(Roles="admin")]
public ActionResult View()
{
....
}
If user's aren't in that role then they will be be able to access that view.
For multiple roles, you can do:
[Authorize(Roles="admin, user")]
public ActionResult View()
{
...
}
This will allow anybody that is an admin OR user to view the page. (They don't have to be in both roles).

Elaborating on my comment above. Decorating your controller actions with the Authorization Attribute will lock down it to the specific role(s). This does not solve the issue of a read-only type role. You will need some logic in the controller action to evaluate the role then return a different view. I recommend placing this in a BaseController. Have your other controllers inherit it:
public abstract class BaseController : Controller
{
public bool IsReadOnly { get; set; }
public BaseController()
{
this.IsReadOnly = Roles.IsUserInRole("readonly");
}
}
public class HomeController : BaseController
{
[Authorize(Roles = "admin, user, readonly")]
public ActionResult Edit(int id)
{
if (!IsReadOnly)
{
return View("Details");
}
... other stuff
}
}

Try This in .cshtml
#if ( User.Identity.IsAuthenticated ){
if ( User.IsInRole("Admin") ){
#Html.ActionLink("Admin", "AdminController")
}
}

Related

Limit UmbracoAuthorizedController to Umbraco Admin Users Only

I have create a new controller, inherited from the Umbraco.Web.Mvc.UmbracoAuthorizedController and trying to limit it to only logged in Umbraco Administrators.
My current solution displays the view for only logged in umbraco users, but I cannot filter for only admins.
Code:
I have a Composer and I set up the route config:
public class ApplicationEventComposer : IComposer
{
public void Compose(Composition composition)
{
RouteTable.Routes.MapRoute(
name: "ITTest",
url: "umbraco/backoffice/ITTest/{action}/{id}",
defaults: new { controller = "ITTest", action = "Index", id = UrlParameter.Optional }
);
composition.Register<ITTestController>(Lifetime.Request);
}
}
I have a controller:
public class ITTestController : Umbraco.Web.Mvc.UmbracoAuthorizedController
{
public ActionResult Index()
{
return View("/Views/ITTest/Index.cshtml");
}
}
I have tried to add different attributes to filter for only adminsitrators like:
[UmbracoAuthorize(Roles = "admin")]
[UmbracoApplicationAuthorize(Roles = "admin")]
[AdminUsersAuthorize]
And tried different roles like "admin", "administrator", "administrators", "Administrators" etc. but nothing seems to work.
(Side note: At the moment I am thinking about a workaround and overwrite the OnAuthorization event, but that would be more of a hack than a proper solution.)
Questions:
How can I filter the users using Umbraco roles?
What are the role names exactly? Are they the user group names or something else?
Update:
(I tried to improve the answer below, but it was rejected, so I will add my findings here)
The [Authorize(Roles = "admin")] one is working!
I was playing around with it. To make it work it still needs to be under "umbraco/backoffice", but it does not have to be a UmbracoAuthorizedController it seems to be working fine when it is (only) RenderMvcController
The built in role names are:
"admin"
"sensitiveData"
"translator"
"writer"
"editor"
For more info: https://our.umbraco.com/forum/using-umbraco-and-getting-started/99651-limit-umbracoauthorizedcontroller-to-umbraco-admin-users-only#comment-313527
The UmbracoAuthorizedController controller effectively just adds the UmbracoAuthorize attribute to your controller, but it seems this attribute ignores any roles you pass in, and just checks the visitor is an authenticated back-office user.
You can see this in detail in the AuthorizeCore method in:
https://github.com/umbraco/Umbraco-CMS/blob/853087a75044b814df458457dc9a1f778cc89749/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs
and the ValidateRequestAttempt method in:
https://github.com/umbraco/Umbraco-CMS/blob/853087a75044b814df458457dc9a1f778cc89749/src/Umbraco.Web/Security/WebSecurity.cs
This isn't what I would have expected!
To achieve what you require you could inherit from the Umbraco.Web.Mvc.UmbracoController controller and decorate it with a standard MVC Authorize attribute.
I've successfully tested the following in Umbraco 8.2.0:
public class ITTestController : Umbraco.Web.Mvc.UmbracoController
{
[Authorize(Roles = "someGroup")]
public ActionResult Index()
{
return View("/Views/ITTest/Index.cshtml");
}
}
where someGroup is the Umbraco group you wish to allow.
Umbraco documentation:
https://our.umbraco.com/documentation/Implementation/Controllers/
suggests you should use the Umbraco.Web.Mvc.UmbracoAuthorizeAttribute attribute, which I think you've tried, so I would just update the Roles to be Roles = "Administrators", so you have something like:
[UmbracoAuthorize(Roles = "Administrators")]
public ActionResult Index()
{
return View("/Views/ITTest/Index.cshtml");
}

MVC C# preventing normal users from accessing admin control URL - No roles

Right now, my user table has a bool called Admin. As the code shows, if user.admin = true, the user is able to see the admin area button and access it.
#if (Common.UsuarioLogueado.Admin) {
<li>Admin control panel</li>
}
This is working as intended. However, non admin users can still go to the control panel by accessing it´s url http://localhost/appName/admin/ClientesAdmin/list
How do I prevent such thing? I was thinking about showing an error msg
Going along with the other answers about using Roles, and the AuthorizeAttribute.. which in my opinion is the better way to achieve what you're trying to do, there is another way.
You could just simply redirect the user to another page.. preferable an error page saying you don't have access to the requested page, or just a 401 page which the AuthorizeAttribute would do if you weren't authorized.
Alternate Solution
public class ClientesAdmin : Controller {
// [Authorize(Roles="Admin")] could do it this way
public ActionResult List() {
// or..
if(!Common.UsuarioLogueado.Admin)
{
return new HttpStatusCodeResult(401);
// or
// return View("Error") // usually there is an 'Error' view the Shared folder
}
return View();
}
}
This is not the best solution but I don't know how far along your project is, but simply an alternate solution.
This is how I do it. However your membership system needs to be using ASP.Net Roles for this to work properly.
In your controller you just add the data annotation Authorize. for the function to be accessed by the client, they must be logged in and have the roll specified in the function.
This solution may not be direct cut and paste, but you can see the basic usage then perhaps do a little more research on the Authorize functionality.
public class MyController : Controller {
[Authorize(Roles="Admin")]
public ActionResult AdminIndex() {
return View();
}
[Authorize(Roles = "basic")]
public ActionResult BasicUsersIndex() {
return View();
}
}
Ideally you should be using role based access control. By limiting access by the role, rather than a boolean value in a table you could decorate your CientesAdmin controller with an Authorize Attribute like below.
[Authorize(Roles = "Admin")]
public class CientesAdminController : Controller
{
}
You could also use razor helpers to check if a user IsInRole("Admin").
There is a lot of help on the net to guide you down this path, but if your app is already developed you probably want to stage your changes. Then the recommendation would be to create your own AuthoriseAttribue. Something like.
public class RestrictAccessToAdmins : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Do the default Authorise Logic (Check if user is loggedin)
base.AuthorizeCore(httpContext);
if (httpContext.User.IsInRole("Admin")) return true;
var id = httpContext.User.Identity.GetUserId();
using (ApplicationDbContext context = new ApplicationDbContext())
{
//Implement you own DB logic here returning a true or false.
return context.Common.First(u => u.userid == id).UsuarioLogueado.Admin;
}
}
}
To use the attribute you'd do the following.
[RestrictAccessToAdmins]
public class CientesAdminController : Controller
{
}
Then over time, with better understanding of the default authorise attribute and a bit of refactoring you could easily change the attribute to below :)
[RestrictAccessToAdmins(Roles = "Admin")]
public class CientesAdminController : Controller
{
}

Same code for each mvc actionresult in home controller

So I have some generic actionresults that link to various views for the time being. The layout page contains a call to adfs to populate a logged in user name that has to be for each page. Looks like this:
<div class="float-right">
<section id="login">
Hello, <span class="username">#ViewBag.GivenName #ViewBag.LastName</span>!
</section>
</div>
In the home controller, what makes this logged in name work is this code here:
public ActionResult Index()
{
ClaimsIdentity claimsIdentity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
Claim claimGivenName = claimsIdentity.FindFirst("http://sts.msft.net/user/FirstName");
Claim claimLastName = claimsIdentity.FindFirst("http://sts.msft.net/user/LastName");
if (claimGivenName == null || claimLastName == null)
{
ViewBag.GivenName = "#FAIL";
}
else
{
ViewBag.GivenName = claimGivenName.Value;
ViewBag.LastName = claimLastName.Value;
}
return View();
}
But as mentioned earlier, I need this to display when a user goes to each link (actionresult). Therefore, I am having to post all the code above into each actionresult in order to achieve this.
Is there some way I can have this apply to each actionresult as a whole rather than having to duplicate code from one action to another? I did try just to register into an actionresult for my _Layout.cshtml and make the call to that partialview, but that didn't give me favorable results. I am sure it is something simple that I am missing.
Hoping some of you can help. Thanks much.
We use an abstract controller and override its OnActionExecuting method to execute code before the actual action method gets invoked. With this abstract controller, all you have to do is make any other controllers inherit from it to gain it's functionality. We also use this base controller as a place to define other helper methods that other controllers which extend it can use, such as GetUsernameForAuthenticatedUser().
public abstract class AbstractAuthenticationController : Controller
{
private readonly IAuthenticationService _authService;
protected AbstractAuthenticationController()
{
_authService = AuthenticationServiceFactory.Create();
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
EnsureUserIsAuthenticated();
}
internal void EnsureUserIsAuthenticated()
{
if (!_authService.IsUserAuthenticated())
{
_authService.Login();
}
}
protected string GetUsernameForAuthenticatedUser()
{
var identityName = System.Web.HttpContext.Current.User.Identity.Name;
var username = _authService.GetUsername(identityName);
if (username == null) throw new UsernameNotFoundException("No Username for " + identityName);
return username;
}
}
This functionality could also be implemented in an Attribute class which allows you to decorate your controllers as opposed to using inheritance but the end result is the same. Here is an example of a custom controller attribute implementation.
You could create a base controller and make all the controllers inherit from it. Move the code that sets the given and last names into a separate, protected method and call it whenever you need. I think you could call the function in the Initialize method of the base controller. This way you won't need to call it directly into the actions.
You could also make a hierarchy of models and have GivenName and LastName as properties on the base model, instead of working with the ViewBag.
Another alternative to using OnActionExecuting as this is just for a set part of the template would be to give it its own action method that returns a partial and call #Html.Action()

Role Management in MVC3

I want to add a functionality to application such that only admin can create users and he can provide access to particular pages to user.
He can create roles and can provide users different roles.
I am using Visual Studio 2010 and building this application in MVC3.
Please give me suggestions to make over it.
Thanks in advance.
1.Decorate your user creation and permission setting actions with Authorize attribute
(Notify, that usage of Roles property of AuthorizeAttribute requires implementation of MembershipProvider (standart or custom) and registering it in web.config)
public class AccountController : Controller
{
[HttpGet, Authorize(Roles = "Admin")]
public ViewResult CreateUser()
{
return View();
}
[HttpPost, Authorize(Roles = "Admin")]
public ActionResult CreateUser()
{
//... call service method to create user
}
[HttpPost, Authorize(Roles = "Admin")]
public ActionResult AssignPageToUser(int userId, string controllerName, string ActionName)
{
//... insert record into table (UserPermissions) with attributes (userId, actionName, controllerName)
}
// other methods without decoration by authorize attribute
}
Next paragraphs are correct if you really want to have full control on action permissions separately for each user.
If you think, that your permissions can group in finite and small number on roles - you can decorate all actions/controllers by authorize attribute and specify roles, for which action/controller available: [Authorize("Customer, Manager, RegionalAdmin")] and give admin possibility to assign roles to users. But remember, that in is enough to be in only 1 of listed roles to get access, you can't require by this attribute, for example and Admin, and Manager roles.
If you want to require necessarily more than 1 role, use multiple attributes:
public class MyController:Controller
{
[Authorize(Roles = "Manager")]
[Authorize(Roles = "Admin")]
public ActionResult Action1()
{
//...
}
}
2.For your pages you can create your own filter attribute, inherited from authorize attribute, that will check, if action is available for user (i think you want to assign actions but not views to user).
public UserPermissionRequiredAttribute: AuthorizeAttribute
{
public OnAuthorization(AuthorizationContext filterContext)
{
var isAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
var userName = filterContext.HttpContext.User.Identity.Name;
var actionName = filterContext.ActionDescriptior.ActionName;
var controllerName = filterContext.ActionDescriptior.ControllerDescriptor.ControllerName;
if (isAuthenticated && myUserActionPermissionsService.UserCanAccessAction(userName, actionName, contollerName)
{
filterContext.Result = HttpUnauthorizedResult(); // aborts action executing
}
}
}
3.Decorate actions (controllers), that accessible for users granted by admin:
MySpecialController: Controller
{
[UserPermissionRequired]
Action1()
{
//...
}
[UserPermissionRequired]
Action2()
{
//...
}
Action3()
{
//...
}
}
I don't recommend to use base controller for that aim, because attribute usage is more flexible (you have control on action/controller level instead of only controller level), it is better way to implement separated responsibility. Base controller and filter attribute usage correlated as polymorphism and switch operator.
You're asking a very broad question, and it would take some time to review all your requirements. In any case, you could start by adding a user property to a controller from which all other controllers inherit. Then, you could interrogate that user instance to determine whether they have access to the current route. This solution should give you the foundation you need to add some administrative views for your business requirements.
public class MegaController
{
protected User CurrentUser { get; set; }
protected override void Initialize(RequestContext context)
{
if (requestContext.HttpContext.User.Identity.IsAuthenticated)
{
var userRepository = new UserRepository();
CurrentUser = userRepository.GetUser(
requestContext.HttpContext.User.Identity.Name);
}
}
}
The User and UserRepository types can be your own design. You could use LINQ To Entities to wrap a table named "User" and then within your controllers, you could have access to any fields in that table.
Then, subclass all controllers from MegaController
public class AdminController : MegaController
{
public ActionResult Action1()
{
return View();
}
}
public class SomeOtherController : MegaController
{
public ActionResult Action1()
{
return View();
}
}
Now, this doesn't completely solve your "admin" issue. To do so, you could include logic in MegaController.Initialize() to interrogate the request information. Once you have the requested route and user in context, your code could make a decision whether to allow the request, redirect it, etc.
protected override void Initialize(RequestContext context)
{
// ...
if(context.HttpContext != null)
{
if(context.HttpContext.Request.Path == "some/restricted/route"
&& CurrentUser.Role != "Admin")
{
// or similar error page
var url = Url.Action("UnAuthorized", "Error");
context.HttpContext.Response.Redirect(url);
}
}
}
One caveat with this method is that any new controllers added to your application would have to inherit from MegaController, an architecture that could be easily missed by future developers on the project.
Read about plain old forms authentication to add support for roles and user management.
Then use the [Authorize(Roles="RoleName1")] on controllers or actions to control access.
Check MvcMembership, also available on Nuget. You will have all the basics for User Management in an ASP.NET MVC 3 site.
You will need a user / role provider. Read this tutorial to learn how to setup a database that will hold your users and roles. Once it is setup, you will have all the stored procedures needed for first setup / manual testing created.

Protect entire website behind a login i.e. "Authorize" all Actions within all controllers

title pretty much says it all.
I have a website which will only run behind a login so I want to ensure that nothing can be accessed unless you're logged in. This includes ActionResults, JsonResults etc...
Currently, I have [Authorize] all over my controllers which is quite tedious and not very DRY :)
So can I protect the entire website with 1 magic line of code? (The login page will obviously need to be accessible)
Also, please note that I will still need to further protect some of the Actions to only be used by certain Users/Roles
If you have multiple controllers, then make a AuthorizeController from which you inherit your controllers that must be protected. Just set the [Authorize] attribute to the AuthorizeController:
[Authorize]
public class AuthorizeController: Controller
{
}
public class HomeController : AuthorizeController
{
...
}
// don't inherit AccountController from AuthorizeController
public class AccountController : Controller
{
public ActionResult Login()
{
...
}
}
If you are trying to secure an entire website, you could use a global filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
}
}
See here for more information http://visualstudiomagazine.com/blogs/tool-tracker/2013/06/authenticating-users-in-aspnet-mvc-4.aspx
Nevermind! I think I found it!
Placing [Authorize] above the Controller class seems to protect all actions, and is further customisable on a per-action basis. YES!
[Authorize]
public class SomeController : Controller
{
// All logged in users
public ActionResult Index()
{
...
}
[Authorize(Roles="Admin")] // Only Admins
public ActionResult Details()
{
...
}
}

Categories

Resources