简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM