定义两个策略:一个用于 API (apipolicy),另一个用于在 Startup.cs 中的正常 MVC 调用 (defaultpolicy) ConfigureServices 方法:
services.AddAuthorization(options =>
{
// define several authorization policies if needed
options.AddPolicy("defaultpolicy", b =>
{
b.RequireAuthenticatedUser();
});
options.AddPolicy("apipolicy", b =>
{
b.RequireAuthenticatedUser();
// define which authentication is used for this policy
b.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
});
});
要应用每个策略,您需要使用所需的 [Authorize ("policy")] 属性来装饰控制器,例如:
SampleDataApiController.cs - 应用了 apipolicy
[Authorize ("apipolicy")]
[Route("api/[controller]")]
public class SampleDataApiController : Controller
{
}
AccountController.cs - 应用默认策略
[Authorize("defaultpolicy")]
[Route("[controller]/[action]")]
public class AccountController : Controller
{
}
这里的示例是我完整的 ConfigureServices 方法,可以给你一个想法:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("defaultpolicy", b =>
{
b.RequireAuthenticatedUser();
});
options.AddPolicy("apipolicy", b =>
{
b.RequireAuthenticatedUser();
b.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
});
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "CustomScheme";
})
.AddCookie()
.AddJwtBearer(options =>
{
// Bearer Logic
})
.AddOAuth("CustomScheme", options =>
{
// Oauth Logic
});
}
为简单起见,我只是添加了以下 nuget。 Microsoft.AspNetCore.All