問題描述
我正在使用 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模板網!