2016-10-05 4 views
1

asp에서 사용자 정의 인증 미들웨어를 만들었습니다.조건부로 사용자 정의 미들웨어 사용

public class MyAuthenticationMidleware 
{ 
    private readonly RequestDelegate _next; 

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

    public async Task Invoke(HttpContext context) 
    { 
     if (!UserIsAuthenticated()) 
     { 
      context.Response.StatusCode = 401; 
      return; 
     } 
     ... 
     await _next.Invoke(context); 
    } 
} 

public static class MyAuthenticationMidlewareExtensions 
{ 
    public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder builder) 
    { 
     return builder.UseMiddleware<MyAuthenticationMidleware>(); 
    } 
} 

시작으로 : - 인증 미들웨어는 각 요청에 대해 실행이 제대로 작동

public void Configure(...) 
    { 
     app.UseStaticFiles(); 
     app.UseMyAuthentication(); 
     app.UseMvc(); 
    } 

아래 그림과 같이 순 핵심 프로젝트, 그리고 등록. 사용자가 인증되지 않으면 401이 리턴됩니다. 그렇지 않으면 특정 mvc 조치가 호출됩니다.

내가 시도한 것은 인증 미들웨어가 특정 작업을 수행하는 것을 막는 것이 었습니다. 나는 또 다른 확장 메서드를 만들 MapWhen 방법을 사용하고 다음과 같이 사용 : 예상대로

public static class MyAuthenticationMidlewareExtensions 
{ 
    public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder builder) 
    { 
     return builder.UseMiddleware<MyAuthenticationMidleware>(); 
    } 

    public static IApplicationBuilder UseMyAuthenticationWhen(this IApplicationBuilder builder, Func<HttpContext, bool> predicate) 
    { 
     return builder.MapWhen(predicate, applicationBuilder => applicationBuilder.UseMyAuthentication()); 
    } 
} 

public void Configure(...) 
{ 
    app.UseStaticFiles(); 
    app.UseMyAuthenticationWhen(context => context.Request.Path != "xyz"); 
    app.UseMvc(); 
} 

불행하게도,이 작동하지 않습니다. 미들웨어는 경로가 "xyz"와 다른 경우에만 호출되지만 전체 체인을 짧게 순환시키는 것으로 보이며 특정 작업이나 필터는 호출되지 않습니다.

아마 MapWhen에 대한 나의 이해가 잘못되었습니다. 원하는 결과를 얻을 수있는 방법이 있습니까?

답변

0

MapWhen은 미들웨어 파이프 라인을 분리하는 데 사용됩니다. 분기 파이프 라인에 mvc를 사용하려면 separetely를 추가해야합니다. 그래서 당신은 다음과 같은 확장 방법에 .UseMvc();을 사용해야합니다

public static IApplicationBuilder UseMyAuthenticationWhen(this IApplicationBuilder builder, Func<HttpContext, bool> predicate) 
{ 
    return builder.MapWhen(predicate, applicationBuilder => 
    { 
     applicationBuilder.UseMyAuthentication(); 
     applicationBuilder.UseMvc(); 
    }); 
} 

그러나 내가 당신의 방법으로 갈 것입니다. 인증 미들웨어의 경우 Simple token based authentication/authorization in asp.net core for Mongodb datastore과 같은 내 자신의 미들웨어를 구현하고 인증 mvc 작업에 Authorize 속성을 사용합니다. 공급 조건에 해당하는 경우

3

MapWhen 새로운 파이프 라인 분기를 생성하고, 해당 분기가 하지 당신이 UseMvc()을 주요 지점에 다시 가입한다.

MapWhen 대신 UseWhen을 사용하도록 확장 방법을 변경할 수 있습니다. 이 여전히 호출 될 수 있도록 UseWhenrejoins with the main pipeline

참고 : 위의 링크 참조-있는 contrib을 ASPNET 동안, UseWhen 확장 방법은 지금 Microsoft.AspNetCore.Http.Abstractions의 일부입니다.

이것은 당신이 당신 Configure 방법에 명시 UseMvc()을 유지하는 대신 정말 어떤 비즈니스 존재가없는 사용자의 인증 확장 방법에 숨겨져 있습니다.

관련 문제