MVC 6 [Authorize(Roles = "*")] 简单示例

MVC 6 [Authorize(Roles = "*")] Simple Example

我正在尝试使用最新版本的 asp.net 5 进行身份验证和授权。

是否有简单的示例说明需要添加到 Startup.cs 以连接此功能的内容?

This article 很好地掩盖了它。

本质上,[Authorize(Roles = "Blah")] 只是为了向后兼容,政策才是前进的方向。

我不会剪切和粘贴它,但本质上,对于此操作:

[Authorize("SalesOnly")]
public IActionResult DoSalesyStuff()
{ /* .. */ }

已连接 Startup.ConfigureServices:

// only allow authenticated users
var defaultPolicy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();

services.AddMvc(setup =>
{
    setup.Filters.Add(new AuthorizeFilter(defaultPolicy));
});

services.AddAuthorization(options =>
{
    // inline policies
    options.AddPolicy("SalesOnly", policy =>
    {
        policy.RequireClaim("department", "sales"); // Some policy
    });
});

作者已经把他们的 full example code on github and the source for the security middleware is here.