问题
I am using a c# self hosted OWIN server and have configured my application to use authorise with JWT as below. This works properly, and invalid tokens are rejected with a 401 Unauthorized and valid tokens are accepted.
My question is how can I write a log of why requests are rejected. Was it expired? Was it the wrong audience? Was no token present? I want all failed requests to be logged, but I can't seem to find any example of how.
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Enable
config.Filters.Add(new AuthorizeAttribute());
appBuilder.UseJwtBearerAuthentication(new JwtOptions());
appBuilder.UseWebApi(config);
}
}
JwtOptions.cs
public class JwtOptions : JwtBearerAuthenticationOptions
{
public JwtOptions()
{
var issuer = WebConfigurationManager.AppSettings["CertificateIssuer"];
var audience = WebConfigurationManager.AppSettings["CertificateAudience"];
var x590Certificate = Ap21X509Certificate.Get(WebConfigurationManager.AppSettings["CertificateThumbprint"]);
AllowedAudiences = new[] { audience };
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2(x590Certificate.RawData))
};
}
}
I am guessing I will need to implement my own validation to do this, but not sure how to implement that either.
回答1:
I know that it is quite late, but can be useful for one how is struggling to find an answer.
Basically AuthenticationMiddleware has embedded logging. You just need to redirect OWIN logs to logger you are using. NLog.Owin.Logging works well for me. There is similar solution for log4net.
There is alternative solution. Extend JwtSecurityTokenHandler and log the reason manually.
public class LoggingJwtSecurityTokenHandler : JwtSecurityTokenHandler
{
public override ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
try
{
return base.ValidateToken(securityToken, validationParameters, out validatedToken);
}
catch (Exception ex)
{
//log the error
throw;
}
}
}
And use it like this:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
TokenHandler = new LoggingJwtSecurityTokenHandler()
});
来源:https://stackoverflow.com/questions/33578498/how-to-log-authentication-failure-reasons-when-using-owin-and-jwt