Asp.Net核心自定义身份验证中间件方案

时间:2016-05-28 02:46:20

标签: c# asp.net-core asp.net-core-1.0

我的项目在同一个解决方案中有一个前端和一个API,所以我正在构建一个自定义身份验证中间件,它只用于授权API控制器,因为前端控制器使用Identity。

我正在为Startup.cs上的Identity设置AutomaticAuthenticate选项false,如此

services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {                
            config.User.RequireUniqueEmail = true;
            config.Password.RequiredLength = 4;
            config.Cookies.ApplicationCookie.AuthenticationScheme = "Cookie";
            config.Cookies.ApplicationCookie.AutomaticAuthenticate = false;                           
        }).AddEntityFrameworkStores<DbContext>()
        .AddDefaultTokenProviders();

对于我的自定义中间件,我实现了自定义选项,我已经完成了这个

app.UseApiAuthorizationMiddleware(new ApiAuthenticationOptions
        {
            AuthenticationScheme = "Api",
            AutomaticAuthenticate = false
        });

现在我尝试使用

[Authorize(AuthenticationSchemes = "Api")]

在我的控制器中Visul Studio告诉我无法找到AuthenticationSchemes,我缺少并组装或引用。快速操作工具告诉我添加

"System.Net.Primitives": "4.0.11-rc2-24027"

但是我最终得到的是版本4.0.10并且它没有编译......我不确定到目前为止我做的是好还是确实存在问题。

我希望它很清楚。

感谢

1 个答案:

答案 0 :(得分:0)

为了正确实现自定义身份验证中间件,我不仅要实现继承自AuthenticationMiddleware的中间件,还要实现从AuthenticationHandler扩展的身份验证处理程序,并且所有逻辑都在HandleAuthenticateAsync()

方法上进行。