2017-10-14 237 views
1

对.NET Core 2.0进行更改后,我一直无法找到关于此特定问题的信息。如何在.net core 2.0中做简单的标题授权?

我有饼干授权这样的:

services.AddAuthentication("ExampleCookieAuthenticationScheme") 
    .AddCookie("ExampleCookieAuthenticationScheme", options => { 
     options.AccessDeniedPath = "/Account/Forbidden/"; 
      options.LoginPath = "/Account/Login/"; 
}); 

对于另一部分(我的控制器,我想基于一个简单的头部 在我发现的例子来简单地授权,无论是我不能。拿到头,或者他们已经做只为Facebook,谷歌,饼干等

如何添加,它进行的.Net核心简单的报头校验授权2.0?

回答

1

它可以执行简单的授权使用自定义中间件进行检查。但是,如果需要为所选控制器或操作方法应用自定义中间件,则可以使用中间件过滤器。

中间件和应用生成扩展名:

public class SimpleHeaderAuthorizationMiddleware 
    { 
     private readonly RequestDelegate _next; 

     public SimpleHeaderAuthorizationMiddleware(RequestDelegate next) 
     { 
      _next = next; 
     } 

     public async Task Invoke(HttpContext context){ 

      string authHeader = context.Request.Headers["Authorization"]; 
      if(!string.IsNullOrEmpty(authHeader)) 
      { 
       //TODO 
       //extract credentials from authHeader and do some sort or validation 
       bool isHeaderValid = ValidateCredentials(); 
       if(isHeaderValid){ 
        await _next.Invoke(context); 
        return; 
       } 

      } 

      //Reject request if there is no authorization header or if it is not valid 
      context.Response.StatusCode = 401; 
      await context.Response.WriteAsync("Unauthorized"); 

     } 

    } 

public static class SimpleHeaderAuthorizationMiddlewareExtension 
    { 
     public static IApplicationBuilder UseSimpleHeaderAuthorization(this IApplicationBuilder app) 
     { 
      if (app == null) 
      { 
       throw new ArgumentNullException(nameof(app)); 
      } 

      return app.UseMiddleware<SimpleHeaderAuthorizationMiddleware>(); 
     } 
    } 

为了使用中间件作为过滤器,你需要创建Configure方法,指定要使用的中间件管道中的类型。

public class SimpleHeaderAuthorizationPipeline 
    { 
     public void Configure(IApplicationBuilder applicationBuilder){ 
      applicationBuilder.UseSimpleHeaderAuthorization(); 
     } 
    } 

现在你可以使用在特定的控制器或动作方法的上述类型如下:

[MiddlewareFilter(typeof(SimpleHeaderAuthorizationPipeline))] 
public class ValuesController : Controller 
{ 
}