2018年12月10日 星期一

ASP.NET Core 2.0 - JwtBearerEvents


想在 .Net Core 2.0 裡接 jwt 驗證的事件,
比如拿到 token 驗證失敗的 exception,
該怎麼做呢?

建立 CustomJwtBearerEvents 類別,實作 JwtBearerEvents
public class CustomJwtBearerEvents : JwtBearerEvents
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    public CustomJwtBearerEvents() : base()
    {}

    public override Task AuthenticationFailed
            (AuthenticationFailedContext context)
    {
        _logger.Error(context.Exception.Message);
        return this.OnAuthenticationFailed.Invoke(context);
    }

    public override Task TokenValidated(TokenValidatedContext context)
    {
        _logger.Trace("OnTokenValidated: " + context.SecurityToken);

        if (something)
        {
            var failMsg = $"Invalid API Token : {jwtToken.RawData}";
            context.Fail(failMsg);
            _logger.Error(failMsg);
                    
        }
        return this.OnTokenValidated.Invoke(context);
    }

    public override Task Challenge(JwtBearerChallengeContext context)
    {
        return this.OnChallenge.Invoke(context);
    }

    public override Task MessageReceived(MessageReceivedContext context)
    {
        return this.OnMessageReceived.Invoke(context);
    }
}

reference: https://www.codeproject.com/Articles/1205160/ASP-NET-Core-Bearer-Authentication

沒有留言:

張貼留言