c# - 我们如何在 ASP.NET Web API 中记录身份验证 token 请求

标签 c# asp.net api authentication delegatinghandler

我们有一个 ASP.NET Web Api 应用程序,它使用 OAuth Bearer Tokens 进行身份验证,我们正在尝试为此实现请求/响应日志记录。

基本上它是这样工作的:
1. 用户向“/authenticate”发送请求并收到一个认证 token
2. 用户然后使用此身份验证 token 请求公开的 API 方法

为了将请求记录到公开的 API 方法,我们使用了一个可以正常工作的 DelegatingHandler

但是,DelegatingHandler 实现不会捕获对“/authenticate”的请求。

记录 token 请求是否需要不同的方法?

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);
}

使用 OAuth 代码编辑

[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")
            });
        }
    }
}

最佳答案

您正在安装 OWIN middleware在 WebAPI 中间件之前发布 token 。

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

DelegatingHandler您尝试用于记录请求是 Web API 中间件的一部分,并且永远不会到达,因为 token 发布中间件处理请求并且不会在管道中进一步调用中间件。

不使用 DelegatingHandler,而是使用以下中间件并将其安装在 token 中间件之前。

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;
    }
}

要安装中间件,只需在 Startup 中的 app.UseOAuthBearerTokens 语句之前插入语句:app.Use(typeof (RequestLoggerMiddleware));。 CS.

关于c# - 我们如何在 ASP.NET Web API 中记录身份验证 token 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37792685/

相关文章:

html - 根据条件隐藏 ascx 标记

android - 获取 Instagram 快拍 Json

angularjs - 将 angularjs 和 node.js 后端与 Cloudant DB 搜索 API 结合使用

c# 使用 ConsoleColor 作为 int

c# - Linq 到实体投影 : is this projection inefficient?

asp.net - 如何使用 Ajax 使 SO 标签自动完成

c# - 如何缓存 XmlTextWriter 数据?

javascript - Axios 和 Fetch 都会导致 CORS 错误,但 Postman 不会

c# - PDF 文件是否包含 iref 流?

c# - EF Core 2.x - IQueryable 扩展正在客户端而不是数据库进行评估