简体   繁体   English

如何使用Azure AD和asp.net MVC保护控制器访问

[英]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. 如果我使用Azure AD进行身份验证,我想知道如何正确保护API。

As far as I can tell using [Authorize] on the controller will require the user to log. 据我所知,在控制器上使用[Authorize]将要求用户登录。 However once in, even if I separate the users into groups, eg: 但是一旦进入,即使我将用户分为几组,例如:

Members Moderators Administrators 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. 我怀疑使用PostMan的用户可以获取其令牌并从其他成员中查找数据。

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. 控制器将通过实体框架引用SQL Server。

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. 为了检索用户名,您需要[Authorize] (至少在您不希望像我的示例那样在整个控制器中使用的情况下,需要进行此操作),否则您将无法检索它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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