Use [Authenticate] attribute in MVC controller using sessions to authorize users? - c#

I have been searching for similar solutions online but everything seems overcomplicating, currently, I have a UserController that I only want users that are logged in to access, my current solution involves using if statements however I was wondering if it's possible to use the [Authorize] attribute and apply it to methods or the entire controller perhaps?
public class UserController : ASessionController {
public UserController (IAmazonDynamoDB dynamoDbClient, DynamoDBContext dynamoDbContext) : base(dynamoDbClient, dynamoDbContext) {
}
// [Authorize]
public IActionResult Index () {
// check session variable
if(!UserIsLoggedIn()){ /*redirect to sign in*/ }
return View();
}
}
Perhaps I am not understanding if this is the purpose of the Authorize attribute? Thank you in advance.

You can use the Authorize attribute on endpoints and / or the Controller itself
It will force the User to be authenticated to again access to the decorated item.
In addition you can also restrict it to authenticated users with a given or multiple roles like in the example
[Authorize(Roles = "Administrator")]
public IActionResult Index()
{
...
}
[Authorize(Roles = "Administrator,Guest")]
public IActionResult NotAnIIndex()
{
...
}
But you should read the Microsoft Documentation tuturial

Related

Check if user is logged on in ASP.NET Core

I'm new to ASP.NET Core and I'm still very uncomfortable. Anyways, I would like to know if this way is correct or if exists better solutions.
I'm checking on every page if a user is logged on. If not, I will redirect page to login page:
public IActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
return View();
}
else
{
return Redirect("Identity/Account/Login");
}
}
I'm adding this in every single page.
Instead of adding User.Identity.IsAuthenticated (very un-DRY) you should check out DataAnnotations - [AllowAnonymous] and [Authorize]. You can decorate whole controllers or specific methods with these annotations to allow authentication for specific functionality.
[AllowAnonymous]
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult OnlyAuthenticatedUsers()
{
return View();
}
Then you can add, in your Startup.cs, redirection rules if the user is not authenticated.
Check this out:
https://www.aspsnippets.com/Articles/Using-Authorize-and-AllowAnonymous-Data-Annotation-attributes-in-ASPNet-MVC.aspx
https://forums.asp.net/t/2146773.aspx?Multiple+AuthenticationSchemes+Not+redirecting+to+login+page+when+adding+AuthenticationSchemes
Use the Authorize action filter
Action filter executes before and after an action method executes.
Action filter attributes can be applied to an individual action method
or to a controller. When action filter applied to the controller then it
will be applied to all the action methods in that controller.
For your case
[Authorize]
public IActionResult Index()
{
return View();
}

Authorize attribute Roles from Database

I want to get the below roles(Admin,IT,..) from the database without hard coding on top of the action result. Please provide any help.
[Authorize(Roles = "Admin,IT")]
public ActionResult Index()
{
}
There aren't any super-easy ways to do this. You can apply the [Authorize] attribute to a controller instead of an action, but it is still "hard-coding" it.
You could create a custom Authorization attribute ([link])1, but you would have to store the Routing values in the database, as well as the Roles that were allowed to access the route. However this just shifts the burden of making manual changes into the database from the code.
I don't really think that this should really be considered "Hard Coding" as you have to declare your authorization somewhere, and you can still have different users with different permissions in different environments. Who else but the developer should know best which routes require which authorization? Would you want to break your access control because you changed the routing somewhere?
create an Action finter
public class ValidationPermission : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(System.Web.HttpContext.Current.Session["UserName"] == null)
System.Web.HttpContext.Current.Response.RedirectToRoute("Login");
else{
// code check CheckPermission
}
}
}
Action controller
[ValidationPermission(Action = ActionEnum.Read, Module = CModule)]
public ActionResult Index()
{
// something code
}
You can try with this way
public static Role {
public static string Admin ="Admin";
public static string IT ="IT";
}
[Authorize(Roles = Role.Admin,Role.IT)]
public ActionResult Index()
{
}

MVC - dynamic role management

I have users that have one of those roles:
RoleA (Attribute: AuthorizeRoleA)
RoleB (Attribute: AuthorizeRoleB)
In my controller I want to say this:
Everyone that has role of type RoleA
can access all the methods in this controller
[AuthorizeRoleA]
public class HomeController : Controller
{
public ActionResult MethodOne()
{
return View();
}
public ActionResult MethodTwo()
{
return View();
}
//****** Make an exception ********
//So in this case, let RoleA here, but let RoleB too.
[AuthorizeRoleB]
public ActionResult MethodThree()
{
return View();
}
}
And I have another controller:
Everyone that has role of type RoleB
can access all the methods in this controller
Just RoleB! No one else.
[AuthorizeRoleB]
public class AnotherController : Controller
{
public ActionResult Index()
{
return View();
}
}
So, this should be similar with the Authorize attribute when is used to decorate the controller, and the AllowAnonymous when is used inside the same controller, but I don't know how to achieve this behavior with custom attributes(filters).
My goal is to create custom attributes, where I can say:
In AuthorizeRoleA will be included n-roles
and in AuthorizeRoleB will be included n-other roles.
But AuthorizeRoleA will have highest priority than the other attributes.
Note: Maybe this is a duplicate, but I didn't find anything similar to this question.

Facebook ASP.NET MVC App with multiple controllers

I am using the Facebook C# SDK to develop an iframe Facebook application.
I looked at the example and find this piece of code to do authorization in a controller:
namespace Auth_And_Allow.Controllers
{
[HandleError]
public class HomeController : Controller
{
[CanvasAuthorize(Perms = "user_about_me")]
public ActionResult Index()
{
FacebookApp fbApp = new FacebookApp();
if (fbApp.Session != null)
{
dynamic result = fbApp.Get("me");
ViewData["Firstname"] = result.first_name;
ViewData["Lastname"] = result.last_name;
}
return View();
}
}
}
But what should i do if my app is using a lot more then one controller?
Should i use the same authorization code in all controllers or is there another way? (I know it will work that way but right now i am searching for best practices to build facebook apps)
The CanvasAuthorize attribute will ensure that your user is logged in and has the appropriate permissions. You dont need to check this again by checking if the Session is null. Additionally, the CanvasAuthorize attribute (like the regular Authorize attribute) can be applied to you controllers as well as your actions. I would just do something like this:
[CanvasAuthorize(Perms = "user_about_me")]
public class FirstController : Controller {
}
[CanvasAuthorize(Perms = "user_about_me")]
public class SecondController : Controller {
}
Make sure you use the Controller extensions named CanvasRedirect accessed by this.CanvasRedirect inside a controller with the Facebook.Web.Mvc namespace referenced. These redirect helpers will ensure that you redirect correctly and dont "lose" the user's session.

How to make pages automatically use https when using asp.net mvc 2.0

I am wondering how do I make pages automatically use https? Like if a user types in
http://www.mysite.com
It should take them right to the login page. However I have SSL required on this page(when they try to login).
So how could I make it so it would change it to
https://www.mysite.com even if they don't type it in themselfs?
You can use the RequireHttpsAttribute on the appropriate controllers and/or actions:
[RequireHttps]
public class SecureController : Controller
{
public ActionResult YourAction()
{
// ...
}
}
// ...
public class YourController : Controller
{
[RequireHttps]
public ActionResult SecureAction()
{
// ...
}
}
i believe you are looking for
[RequireSsl(Redirect = true)]
there is a discussion you can find here
SSL pages under ASP.NET MVC
Edited:
found this link might be useful
http://blog.stevensanderson.com/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/

Categories