【发布时间】:2016-06-13 14:42:37
【问题描述】:
我们有一个 ASP.NET Web Api 应用程序,它使用 OAuth Bearer Tokens 进行身份验证,我们正在尝试实现请求/响应日志记录。
基本上它是这样工作的:
1. 用户向“/authenticate”发送请求并收到一个认证令牌
2. 用户然后使用此身份验证令牌来请求公开的 API 方法
为了记录对公开 API 方法的请求,我们使用 DelegatingHandler,它工作得非常好。
但是,DelegatingHandler 实现不会捕获对“/authenticate”的请求。
记录令牌请求是否需要不同的方法?
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")
});
}
}
}
【问题讨论】:
-
或许你可以使用OnResponseSignIn?
-
感谢大卫的建议。我不确定这是否可行,因为我们使用的是 OAuthBearerTokens 而不是 cookie。
-
那么你的 OAuth 中间件是如何设置的,你能展示一下这段代码吗?
-
我已经用 OAuth 设置代码更新了问题。
标签: c# asp.net api authentication delegatinghandler