简体   繁体   中英

How to secure controller access using Azure AD and asp.net MVC

I would like to know how to properly secure API if I am using Azure AD for authentication.

As far as I can tell using [Authorize] on the controller will require the user to log. However once in, even if I separate the users into groups, eg:

Members Moderators Administrators

How do I ensure that members are only able to access their account information?

I understand I can separate roles with

[Authorize(Roles="Member")]

however that would allow all members to access the controller. I suspect that using PostMan a user can take their token and seek data from other members.

How can I secure the controller so that it only returns the data of a specific user's account? The controller will be referring to a SQL server via Entity Framework.

The only way I know is manually creating the queries to match the authenticated user, since this is specific for the kind of data each action in your controllers retrieve.

To retrieve the authenticated user name, for example, you can do like this:

[Authorize]
public class MyApiController : ApiController
{

    [HttpGet]
    public IHttpActionResult GetDataForLoggedUser()
    {
        var userName = HttpContext.Current.User.Identity.Name;
        // retrieve data for specific user...
        return Ok();
    }

}

In order to retrive the user name, you need that [Authorize] (at least in the actions you need it in case you don't want to use in the whole controller like my example), otherwise you won't be able to retrieve it.

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