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");
}
Related
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
{
}
I have a controller with many actions. All should be accessible to certain users only except one action:
[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
[Authorize]
public ActionResult Index()
{
return View(...);
}
...
}
Even [Authorize (Roles = null)] doesn't work. The method attribute will be ignored! How could I get the exception for just one action? Like AllowAnonymous allows it but visible to logged in users?
You can use OverrideAuthorization attribute like I do in the code below :
[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
[OverrideAuthorization]
[Authorize()]
public ActionResult Index()
{
return View(...);
}
...
}
With [OverrideAuthorization] which came with ASP.Net MVC5 you tell your Index action to override/ignore the authorization rules defined at the controller level.
By doing this, all your actions defined in SecretsController are visible only to Admin role except Index action which will be visible only to authenticated user even if they are not in Admin role.
use the attribute AllowAnonymous
[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
return View(...);
}
...
}
Edit
Since the question was edited right after my answer to precisely mention not wanting the anonymous option
Like AllowAnonymous allows it but visible to logged in users?
The best answer is now CodeNotFound's answer
Let's say I have WebApi Controller
[Authorize]
public class SomeApiController : ApiController
Controller action methods itself does not have any [Authorize] or [AllowAnonymous] attributes.
I want Authorize attribute to return 401 (Unauthorized) error if user has no roles - seems logical (if user had role and now doesn't have ANY - he shouldn't be allowed to perform action even though user is authenticated). I have looked to asp.net mvc webstack I have found the following code in Authorize attribute:
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
{
return false;
}
So looks like if we didn't passed roles authorize attribute just checks if user is authenticated. Setting each role in Roles list is not an option for me ( I mean [Authorize(Roles="role1,role2,...")]).
Therefore question - can I somehow achieve setting Authorize attribute to check if user has ANY role. Or it's better to write custom attribute inherited from above?
Create custom attribute like below:
public override void OnAuthorization(AuthorizationContext filterContext)
{
string[] userRoles = System.Web.Security.Roles.GetRolesForUser(filterContext.HttpContext.User.Identity.Name);
if (!userRoles.Any())
{
throw new HttpException(401, "Unauthorized");
}
base.HandleUnauthorizedRequest(filterContext);
}
}
Hope it helps
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")
}
}
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.