我正在使用 c# 自托管 OWIN 服务器,并已将我的应用程序配置为使用 JWT 授权,如下所示.这可以正常工作,无效令牌会被 401 Unauthorized 拒绝并接受有效令牌.
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
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.
我知道现在已经很晚了,但是对于正在努力寻找答案的人来说很有用.
I know that it is quite late, but can be useful for one how is struggling to find an answer.
基本上 AuthenticationMiddleware 具有嵌入式日志记录.您只需要将 OWIN 日志重定向到您正在使用的记录器.NLog.Owin.Logging 适合我.log4net 也有类似的解决方案.
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.
有替代解决方案.扩展 JwtSecurityTokenHandler 并手动记录原因.
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;
}
}
}
并像这样使用它:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
TokenHandler = new LoggingJwtSecurityTokenHandler()
});
这篇关于使用 OWIN 和 JWT 时如何记录身份验证失败的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!