ASP.NET Core 中基于资源的授权Resource-based authorization in ASP.NET Core
本文内容
授权策略取决于要访问的资源。假设有一个具有 author 属性的文档。仅允许作者更新文档。因此,在进行授权评估之前,必须从数据存储中检索文档。
在数据绑定之前和在执行加载文档的页面处理程序或操作之前,会发生属性评估。由于这些原因,具有 [Authorize]
特性的声明性授权无法满足要求。相反,你可以调用自定义授权方法—称为命令式授权的样式。
使用由授权保护的用户数据创建 ASP.NET Core 应用包含使用基于资源的授权的示例应用。
使用命令性授权Use imperative authorization
授权作为IAuthorizationService服务实现,并在 Startup
类中的服务集合中进行注册。通过依赖关系注入到页面处理程序或操作使该服务可用。
public class DocumentController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IDocumentRepository _documentRepository;
public DocumentController(IAuthorizationService authorizationService,
IDocumentRepository documentRepository)
{
_authorizationService = authorizationService;
_documentRepository = documentRepository;
}
IAuthorizationService
有两个 AuthorizeAsync
方法重载:一个接受资源和策略名称,另一个接受资源并提供要评估的要求的列表。
Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user,
object resource,
IEnumerable<IAuthorizationRequirement> requirements);
Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user,
object resource,
string policyName);
Task<bool> AuthorizeAsync(ClaimsPrincipal user,
object resource,
IEnumerable<IAuthorizationRequirement> requirements);
Task<bool> AuthorizeAsync(ClaimsPrincipal user,
object resource,
string policyName);
在下面的示例中,要保护的资源将加载到自定义的 Document
对象。调用 AuthorizeAsync
重载来确定是否允许当前用户编辑提供的文档。将自定义 "EditPolicy" 授权策略分解为决定。有关创建授权策略的详细信息,请参阅基于策略的自定义授权。
备注
下面的代码示例假定已运行身份验证,并设置 User
属性。
public async Task<IActionResult> OnGetAsync(Guid documentId)
{
Document = _documentRepository.Find(documentId);
if (Document == null)
{
return new NotFoundResult();
}
var authorizationResult = await _authorizationService
.AuthorizeAsync(User, Document, "EditPolicy");
if (authorizationResult.Succeeded)
{
return Page();
}
else if (User.Identity.IsAuthenticated)
{
return new ForbidResult();
}
else
{
return new ChallengeResult();
}
}
[HttpGet]
public async Task<IActionResult> Edit(Guid documentId)
{
Document document = _documentRepository.Find(documentId);
if (document == null)
{
return new NotFoundResult();
}
if (await _authorizationService
.AuthorizeAsync(User, document, "EditPolicy"))
{
return View(document);
}
else
{
return new ChallengeResult();
}
}
编写基于资源的处理程序Write a resource-based handler
为基于资源的授权编写处理程序与编写简单的要求处理程序并无差别。创建自定义要求类,并实现需求处理程序类。有关创建要求类的详细信息,请参阅要求。
处理程序类同时指定要求和资源类型。例如,使用 SameAuthorRequirement
和 Document
资源的处理程序如下所示:
public class DocumentAuthorizationHandler :
AuthorizationHandler<SameAuthorRequirement, Document>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
SameAuthorRequirement requirement,
Document resource)
{
if (context.User.Identity?.Name == resource.Author)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public class SameAuthorRequirement : IAuthorizationRequirement { }
public class DocumentAuthorizationHandler :
AuthorizationHandler<SameAuthorRequirement, Document>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
SameAuthorRequirement requirement,
Document resource)
{
if (context.User.Identity?.Name == resource.Author)
{
context.Succeed(requirement);
}
//TODO: Use the following if targeting a version of
//.NET Framework older than 4.6:
// return Task.FromResult(0);
return Task.CompletedTask;
}
}
public class SameAuthorRequirement : IAuthorizationRequirement { }
在前面的示例中,假设 SameAuthorRequirement
是更通用 SpecificAuthorRequirement
类的特例。SpecificAuthorRequirement
类(未显示)包含表示作者姓名的 Name
属性。Name
属性可以设置为当前用户。
在 Startup.ConfigureServices
中注册要求和处理程序:
services.AddControllersWithViews();
services.AddRazorPages();
services.AddAuthorization(options =>
{
options.AddPolicy("EditPolicy", policy =>
policy.Requirements.Add(new SameAuthorRequirement()));
});
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationCrudHandler>();
services.AddScoped<IDocumentRepository, DocumentRepository>();
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("EditPolicy", policy =>
policy.Requirements.Add(new SameAuthorRequirement()));
});
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationCrudHandler>();
services.AddScoped<IDocumentRepository, DocumentRepository>();
services.AddAuthorization(options =>
{
options.AddPolicy("EditPolicy", policy =>
policy.Requirements.Add(new SameAuthorRequirement()));
});
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationCrudHandler>();
services.AddScoped<IDocumentRepository, DocumentRepository>();
操作要求Operational requirements
如果要根据 CRUD (创建、读取、更新、删除)操作的结果做出决策,请使用OperationAuthorizationRequirement帮助器类。此类使你能够为每个操作类型编写单一处理程序而不是单个类。若要使用它,请提供一些操作名称:
public static class Operations
{
public static OperationAuthorizationRequirement Create =
new OperationAuthorizationRequirement { Name = nameof(Create) };
public static OperationAuthorizationRequirement Read =
new OperationAuthorizationRequirement { Name = nameof(Read) };
public static OperationAuthorizationRequirement Update =
new OperationAuthorizationRequirement { Name = nameof(Update) };
public static OperationAuthorizationRequirement Delete =
new OperationAuthorizationRequirement { Name = nameof(Delete) };
}
处理程序的实现方式如下:使用 OperationAuthorizationRequirement
要求和 Document
资源:
public class DocumentAuthorizationCrudHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
OperationAuthorizationRequirement requirement,
Document resource)
{
if (context.User.Identity?.Name == resource.Author &&
requirement.Name == Operations.Read.Name)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public class DocumentAuthorizationCrudHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
OperationAuthorizationRequirement requirement,
Document resource)
{
if (context.User.Identity?.Name == resource.Author &&
requirement.Name == Operations.Read.Name)
{
context.Succeed(requirement);
}
//TODO: Use the following if targeting a version of
//.NET Framework older than 4.6:
// return Task.FromResult(0);
return Task.CompletedTask;
}
}
前面的处理程序使用资源、用户的标识和要求的 Name
属性验证操作。
操作资源处理程序的挑战和禁止Challenge and forbid with an operational resource handler
本部分说明如何处理质询和禁止操作结果,以及质询和禁止的不同之处。
若要调用操作资源处理程序,请在调用页面处理程序或操作中的 AuthorizeAsync
时指定操作。下面的示例确定是否允许经过身份验证的用户查看所提供的文档。
备注
下面的代码示例假定已运行身份验证,并设置 User
属性。
public async Task<IActionResult> OnGetAsync(Guid documentId)
{
Document = _documentRepository.Find(documentId);
if (Document == null)
{
return new NotFoundResult();
}
var authorizationResult = await _authorizationService
.AuthorizeAsync(User, Document, Operations.Read);
if (authorizationResult.Succeeded)
{
return Page();
}
else if (User.Identity.IsAuthenticated)
{
return new ForbidResult();
}
else
{
return new ChallengeResult();
}
}
如果授权成功,则返回用于查看文档的页面。如果授权失败但用户已通过身份验证,则返回 ForbidResult
通知任何身份验证中间件身份验证失败。当必须执行身份验证时,将返回 ChallengeResult
。对于交互式浏览器客户端,可能需要将用户重定向到登录页。
[HttpGet]
public async Task<IActionResult> View(Guid documentId)
{
Document document = _documentRepository.Find(documentId);
if (document == null)
{
return new NotFoundResult();
}
if (await _authorizationService
.AuthorizeAsync(User, document, Operations.Read))
{
return View(document);
}
else
{
return new ChallengeResult();
}
}
如果授权成功,则返回文档的视图。如果授权失败,则返回 ChallengeResult
会通知任何授权失败的身份验证中间件,中间件可以进行适当的响应。适当的响应可能返回401或403状态代码。对于交互式浏览器客户端,这可能意味着将用户重定向到登录页。