Search code examples
c#.netasp.net-mvcauthenticationauthorization

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


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.


Solution

  • 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