Authorize and AllowAnonymous asp.net core - asp.net

Please explain what I'm doing wrong. I need the entire controller to be available only for a specific authorized role, but one method from the controller was open to everyone. But when using [AllowAnonymous], I have everything open to everyone. How do I do this correctly?
[Authorize(Roles = "admin")]
public class FilesDBController : Controller
{
[AllowAnonymous]
public FileResult DownloadFile(int id)
{
}
}

Related

how to add specific role to an action that has a global authorization on controller

I have Controller that has a Authorization for Specific Role.
[Authorize(Roles = "admin")]
public class PanelController : Controller
{
}
Now I want One my Actions have been also accessible for role user
but i doesnt work when I do this
[Authorize(Roles = "admin")]
public class PanelController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize(Roles = "admin,user")]
public ActionResult MyAction()
{
return View();
}
}
in MyAction Method the user with role user have no access.
I use asp.net mvc5 and identity 2.
I would be very pleased if someone would help me.
The effect of Authorization attributes when applied to both Controller and Action is to AND the roles. Hence in this case your User role will not work as your Controller attribute is going to invalidate the AND operation being carried out.
You could use User role on the Controller and apply Admin role to all other Actions. This will work provided your Admins have the User role assigned to them.

Need to restrict AD users - Windows Authentication in ASP.NET

I have a website which uses Windows Authentication. I need to restrict access to only a few users, who are present in a local database. How can I achieve it? Example DB has "domain\user1", only user1 should be allowed. "domain\user2" should not be allowed.
Thanks in advance
in your controller class, you can use the [Authorize] attribute to restrict access.
If you use it by itself, then you restrict the entire controller to only authenticated users.
If you want specific users to access a controller, you can add parameters to the Authorize attribute, such as:
[Authorize(Roles ="Administrators")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
In the example above, I'm restricting the use of the homecontroller to administrators only, I can also give access only to specific users:
[Authorize(Users = "user1")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
You can also apply this to specific methods in your controller

Whitelist Controller Action in asp.net mvc 5

I have a question about the [Authorization] annotation. I have a controller with the [Authorization(Roles ="admin") annotation. In the controller I have one action that doesn't need to be admin, but still logged in. How is this done? I have tried creating a custom AuthorizationAttribute class, and placing it on the action. This doesn't work, is there a way to override the [Authorization] annotation?
Cheers.
[Authorize(Roles = "admin")]
public class UserController : Controller
{
[OwnDataAuthorize]
public async Task<ActionResult> Details(string id)
{
//.....
}
//...
}
I found the answer to my question here. I was doing it correctly but because of a bug with mvc 5 I had to implement another interface as well in my custom class:
public class OwnDataAuthorize : AuthorizeAttribute, IOverrideFilter {
//....
/// <summary>
/// Only implemented because of a bug in MVC 5.
/// </summary>
public System.Type FiltersToOverride
{
get { return typeof (IAuthenticationFilter); }
}
}
There isn't a simple way to do this, except for moving the Authorize attribute into every controller method/action. So you would need to remove the [Authorize(Roles = "admin")] and add it to every method except for the one you want to authorize.
A work around would be to use the [AllowAnonymous] attribute with an if statement inside the controller action to check for IsAuthenticated:
[AllowAnonymous]
public async Task<ActionResult> Details(string id)
{
if(!User.Identity.IsAuthenticated)
//redirect to loging
//other logic here
...
}

How to allow the user can access his home page after longing in MVC4?

I am new one to asp.net mvc4. Now i am doing Login page. Login is working fine. Link for login is :59523/Login and //:59523/Admin/ListUsers , //:59523/Login/Changepassword these are the some other links.
If i use //:59523/Admin/ListUsers this link in address bar, it is directly redirecting into that page before logging in . How to restrict a user from it. Please help me. Thanks in advance.
This is my controller code for login:
[HttpGet]
public ActionResult Index()
{
return View();
}
//Verifying the User Name and Password using the Method
[HttpPost]
public ActionResult LogIn(Tbl_Users user, FormCollection remember)
You can add an Authorize attribute on your controller action level or the controller level to restrict access as follows:
Action
[Authorize]
public ActionResult ListUsers()
{
...
}
Controller
[Authorize]
public class AdminController : Controller
{
...
}
More info here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx

Securing ajax calls in a ASP.NET MVC application

I have an ASP.NET MVC based application that allows different levels of access depending on the user. The way it currently works is when a user accesses a page, a check is done against the database to determine the rights that user has. The view is then selected based on the level of access that user has. Some users see more data and have more functionality available to them than do others. Each page also makes a variety of ajax calls to display and update the data displayed on the page.
My question is what is the best way to ensure that a particular ajax call originated from the view and was not crafted manually to return or update data the user does not have access to? I would prefer not to have to go to the database to re-check every time an ajax call is made since that was already done when the user initially loaded the page.
Check out the Authorize Attribute, you can put it on an entire controller or just specific methods within your controller.
Examples:
[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
//your code here
}
or
public class AdminController : Controller
{
//Available to everyone
public ActionResult Index()
{
return View();
}
//Just available to users in the Administrator role.
[Authorize(Roles = "Administrator")]
public ActionResult AdminOnlyIndex()
{
return View();
}
}
Alternately, you can write a custom Authorize attribute to provide your own logic.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
IPrincipal user = httpContext.User;
var validRoles = Roles.Split(',');//Roles will be a parameter when you use the Attribute
List<String> userRoles = GetRolesFromDb(user);//This will be a call to your database to get the roles the user is in.
return validRoles.Intersect(userRoles).Any();
}
}
To use:
[CustomAuthorizeAttribute(Roles = "Admin,Superuser")]
public class AdminController : Controller {
}
If iyou are using a post use
[Authorize]
[ValidateAntiForgeryToken]
If iyou are using a get use
[Authorize]
You can also use this custom attribute
public class HttpAjaxRequestAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (!controllerContext.HttpContext.Request.IsAjaxRequest())
{
throw new Exception("This action " + methodInfo.Name + " can only be called via an Ajax request");
}
return true;
}
}
Then decorate your action as below
[Authorize]
[HttpAjaxRequest]
public ActionResult FillCity(int State)
{
//code here
}
Remember to "Mark/Tick" if this solve your problem.
It depends on what type of session mechanisam you are using . Are you using default membership provider ? If not than you can pass user's id and sessionid make sure that user session is valid and user has required permission to make that call .
Along with the Authorize attribute, you can also allow only Ajax requests using custom attributes as shown here.
Thanks

Resources