2016-06-13 18 views
8

Chúng tôi có ứng dụng ASP.NET Web Api sử dụng OAuth Bearer Tokens để xác thực, mà chúng tôi đang cố gắng triển khai yêu cầu Đăng nhập/Trả lời.Làm cách nào để chúng tôi ghi lại yêu cầu mã thông báo xác thực trong ASP.NET Web API

Về cơ bản nó hoạt động như thế này:
1. Người dùng gửi yêu cầu đến "/ xác thực" và nhận được xác thực thẻ
2. User sau đó sử dụng xác thực thẻ này cho các yêu cầu các phương pháp API tiếp xúc

Đối với khai thác gỗ yêu cầu các phương pháp API được tiếp xúc, chúng tôi sử dụng DelegatingHandler hoạt động hoàn toàn tốt.

Tuy nhiên, các yêu cầu được thực hiện để "/ xác thực" không được thực hiện bởi việc thực hiện DelegatingHandler.

Có cách tiếp cận khác yêu cầu đối với yêu cầu ghi nhật ký cho mã thông báo không?

public abstract class MessageHandler : DelegatingHandler 
{ 
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     var correlationId = Guid.NewGuid(); 

     var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri); 

     var requestContent = await request.Content.ReadAsByteArrayAsync(); 

     var context = ((HttpContextBase)request.Properties["MS_HttpContext"]); 

     await IncomingMessageAsync(correlationId, request.Method, request.RequestUri, request.Headers, requestContent, 
      context.Request.UserHostAddress, context.Request.IsAuthenticated, context.User.Identity.Name); 

     var response = await base.SendAsync(request, cancellationToken); 

     byte[] responseMessage; 

     responseMessage = await response.Content.ReadAsByteArrayAsync(); 

     await OutgoingMessageAsync(correlationId, response.StatusCode, response.Headers, responseMessage); 

     return response; 
    } 

    protected abstract Task IncomingMessageAsync(Guid correlationId, HttpMethod requestMethod, Uri requestUri, HttpRequestHeaders requestHeaders, byte[] messageContent, string ipAddress, bool isAuthenticated, string requestMadeByUserName); 
    protected abstract Task OutgoingMessageAsync(Guid correlationId, HttpStatusCode statusCode, HttpResponseHeaders responseHeaders, byte[] messageContent); 
} 

EDIT w/OAuth Mã

[assembly: OwinStartup(typeof(MyApp.Infrastructure.IdentityConfig))] 
namespace MyApp.Infrastructure 
{ 
    public class IdentityConfig 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      app.CreatePerOwinContext<ApplicationIdentityDbContext>(() => ApplicationIdentityDbContext.Create(ConfigurationDataProvider.MYDBCONNSTRING)); 
      app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
      app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 

      app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions 
      { 
       Provider = new ApplicationAuthProvider(), 
       AllowInsecureHttp = true, 
       TokenEndpointPath = new PathString("/Authenticate") 
      }); 
     } 
    } 
} 
+0

Có lẽ bạn có thể sử dụng [OnResponseSignIn] (https://msdn.microsoft.com/en-us/library/microsoft.owin.security.cookies.cookieauthenticationprovider.onresponsesignin (v = vs.113) .aspx)? – DavidG

+0

Cảm ơn đề nghị David. Tôi không chắc chắn nếu điều này sẽ làm việc như chúng tôi đang sử dụng OAuthBearerTokens thay vì cookie. – thiag0

+0

Sau đó, thiết lập phần mềm trung gian OAuth của bạn được thiết lập như thế nào, bạn có thể hiển thị mã đó không? – DavidG

Trả lời

2

Bạn đang cài đặt OWIN middleware phát hành thẻ trước các WebAPI middleware.

app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions 
    { 
     Provider = new ApplicationAuthProvider(), 
     AllowInsecureHttp = true, 
     TokenEndpointPath = new PathString("/Authenticate") 
    }); 

Các DelegatingHandler bạn cố gắng sử dụng để đăng nhập theo yêu cầu là một phần của middeware Web API và không bao giờ đạt được vì phát hành middleware thẻ xử lý các yêu cầu và không gọi middleware hơn nữa trong các đường ống.

Thay vì sử dụng DelegatingHandler, hãy sử dụng phần mềm trung gian sau và cài đặt nó trước phần mềm trung gian mã thông báo.

public class RequestLoggerMiddleware 
{ 
    private readonly Func<IDictionary<string, object>, Task> _next; 
    private readonly ILogger _logger; 

    public RequestLoggerMiddleware(
     Func<IDictionary<string, object>, Task> next, 
     ILogger logger) 
    { 
     _next = next; 
     _logger = logger; 
    } 

    public Task Invoke(IDictionary<string, object> environment) 
    { 
     var context = new OwinContext(environment); 

     _logger.Write($"{context.Request.Method} {context.Request.Uri.AbsoluteUri}"); 
     var result = _next.Invoke(environment); 
     _logger.Write($"Status code: {context.Response.StatusCode}"); 

     return result; 
    } 
} 

Để cài đặt middleware, chỉ cần chèn tuyên bố: app.Use(typeof (RequestLoggerMiddleware)); trước app.UseOAuthBearerTokens tuyên bố trong Startup.cs của bạn.

+0

Làm cho tinh thần. Bạn có thể chỉ cho tôi một tài nguyên hướng dẫn cách đăng ký "RequestLoggerMiddleware" trước thành phần phần mềm trung gian OAuth không? – thiag0

+0

@ thiag0 Chỉ cần chèn câu lệnh: 'app.Use (typeof (RequestLoggerMiddleware));' trước câu lệnh 'app.UseOAuthBearerTokens'. – MvdD

+0

Khi sử dụng phương pháp này, cách thích hợp để đọc nội dung yêu cầu là gì và chờ phản hồi được xử lý để có thể được ghi nhật ký? – thiag0

Các vấn đề liên quan