在身份3 MVC 6许可政策 [英] Authorisation Policy in Identity 3 MVC 6

查看:142
本文介绍了在身份3 MVC 6许可政策的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了很多的研究,但现在还不能确定,如果我正确地这样做。
我找到的最好的资源在这里



http://leastprivilege.com/2015/10/12/the-state-of-security-in- ASP-净-5-和-MVC -6-授权/



给定一个ApplicationUser类扩展为包括授权帐户号码的列表我想限制用户只能查看自己的授权帐户(基于和其他行动)语句)。我认为这是一个非常常见的设计但大多数在网络上的文章是指身份的早期版本。



(PS我的控制器构造函数注入的UserManager)



下面是我的行动

 公共IActionResult GetStatement(INT accountNo,日期时间的startDate,日期结束日期)
{
VAR用户= userManager.Users
.INCLUDE(U => u.AuthorisedAccounts)
。凡(U => u.Id == User.GetUserId())
.FirstOrDefault();
如果(user.AuthorisedAccounts!= NULL)
{
的foreach(VAR在user.AuthorisedAccounts账户)
{
如果(account.AccountNo == accountNo)
返回查看(statementService.GetStatement(accountNo,的startDate,结束日期,0));
}
}
返回HttpUnauthorized();
}



我情不自禁的感觉有一个更好的办法?
基本上我想根据操作参数来授权。accountNo



这是采取什么办法任何提示。


< DIV CLASS =h2_lin>解决方案

在这种情况下,你使用的资源,与该帐户是资源。这个文档是 https://docs.asp.net/en /latest/security/authorization/resourcebased.html



要开始与你定义一个读操作,

 公共静态类操作
{
公共静态OperationAuthorizationRequirement读=
新OperationAuthorizationRequirement {名称=读取};
}

现在你有AccountAccess政策

 公共类AccountAuthorizationHandler:AuthorizationHandler< 
OperationAuthorizationRequirement,帐户>
{
IUserManager _userManager;

公共AccountAuthorizationHandler(IUserManager的UserManager)
{
_userManager =的UserManager;
}

保护覆盖无效手柄(AuthorizationContext背景下,
OperationAuthorizationRequirement要求,
账户资源)
{
//拉动用户ID从context.User
VAR用户id = context.User .....
声称出//获取当前用户的账号。
VAR用户= userManager.Users
.INCLUDE(U => u.AuthorisedAccounts)
。凡(U => u.Id ==用户id)
.FirstOrDefault( ); $ B如果用户的账号相匹配的资源使用accountNumber $ B}

//现在检查和
//同时检查操作类型,您要根据创建改变的情况下,视图等
如果(user.AuthorisedAccounts.Contains(resource.AccountId&安培;&安培;
requirement.Name ==视图)
{
context.Succeed(要求) ;
}
}

在该注册策略中的DI容器,配置服务之内;

 公共无效ConfigureServices(IServiceCollection服务)
{
services.AddMvc();

services.AddAuthorization();

services.AddSingleton< IAuthorizationHandler,
AccountAuthorizationHandler>();
}

在你的控制器你注入AuthorizationService;

 公共类的AccountController:控制器
{
IAuthorizationService _authorizationService;

公众的AccountController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
}

您已经加载之后,你的控制器中,后帐户资源你会做这样的事情。

 公共异步任务< IActionResult>查看(INT帐户ID)
{
帐户的帐户= accountManager.Find(帐户);

如果(帐户== NULL)
{
返回新HttpNotFoundResult();
}

如果(等待_authorizationService.AuthorizeAsync(用户,账户,Operations.Read))
{
返回查看(账户);
}
,否则
{
返回新ChallengeResult();
}
}


I have done a lot of research but am still not sure if I am doing this correctly. The best resource I found was here

http://leastprivilege.com/2015/10/12/the-state-of-security-in-asp-net-5-and-mvc-6-authorization/

Given an ApplicationUser class extended to include a list of Authorized account numbers I want to restrict the user to only view statements (and other actions based) on their authorized accounts). I would think this is a very common design however most of the articles on the net refer to previous versions of identity.

(PS I am injecting UserManager in the Controller constructor)

Here is my action

public IActionResult GetStatement(int accountNo,DateTime startDate,DateTime endDate)
{
    var user = userManager.Users
        .Include(u => u.AuthorisedAccounts)
        .Where(u => u.Id == User.GetUserId())
        .FirstOrDefault();
    if (user.AuthorisedAccounts != null)
    {
        foreach (var account in user.AuthorisedAccounts)
        {
            if (account.AccountNo == accountNo)
                return View(statementService.GetStatement(accountNo, startDate, endDate, 0));
        }
    }
    return HttpUnauthorized();
}

I cant help feeling there is a better way? Basically I want to authorize based on the action parameter."accountNo"

Any hints on what approach to take.

解决方案

In this case you'd use resource based, with the account being the resource. The documentation for this is at https://docs.asp.net/en/latest/security/authorization/resourcebased.html

To start with you'd define an operation of Read,

public static class Operations
{
    public static OperationAuthorizationRequirement Read =
        new OperationAuthorizationRequirement   { Name = "Read" };
}

Now you'd have a policy for AccountAccess

public class AccountAuthorizationHandler : AuthorizationHandler<
    OperationAuthorizationRequirement, Account>
{
    IUserManager _userManager;

    public AccountAuthorizationHandler(IUserManager userManager)
    {
        _userManager = userManager;
    }

    protected override void Handle(AuthorizationContext context,
                                   OperationAuthorizationRequirement requirement,
                                   Account resource)
    {
        // Pull the user ID claim out from the context.User
        var userId = context.User.....
        // Get the current user's account numbers.       
        var user = userManager.Users
            .Include(u => u.AuthorisedAccounts)
            .Where(u => u.Id == userId)
            .FirstOrDefault();
    }

    // Now check if the user's account numbers match the resource accountNumber, and 
    // also check the operation type, in case you want to vary based on create, view etc.
    if (user.AuthorisedAccounts.Contains(resource.AccountId &&
        requirement.Name == "View")
   {
      context.Succeed(requirement);
   } 
}

After that register your policy in the DI container, within configure services;

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddAuthorization();

    services.AddSingleton<IAuthorizationHandler,
                          AccountAuthorizationHandler>();
}

In your controller you inject the AuthorizationService;

public class AccountController : Controller
{
    IAuthorizationService _authorizationService;

    public AccountController(IAuthorizationService authorizationService)
    {
        _authorizationService = authorizationService;
    }
}

Then, within your controller, after you've loaded the account resource you'd do something like

public async Task<IActionResult> View(int accountId)
{
    Account account = accountManager.Find(accountId);

    if (account == null)
    {
        return new HttpNotFoundResult();
    }

    if (await _authorizationService.AuthorizeAsync(User, account, Operations.Read))
    {
        return View(account);
    }
    else
    {
        return new ChallengeResult();
    }
}

这篇关于在身份3 MVC 6许可政策的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆