I am currently using an async Task method to implement the IAuthenticationFilter interface. Upon successful login, I'll try to access an API that has this attribute and it will work fine. However once I go back and access the API again the exception will be thrown.
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var token = context.Request.Headers.Authorization.Parameter;
var principal = await AuthenticateToken(token)
// Other code here ...
}
protected Task<IPrincipal> AuthenticateToken(string token)
{
var secretKey = _authenticationBusiness.GetSecretKey(); // error triggers here.
if (principal == null)
context.ErrorResult = new AuthenticationFailureResult("Invalid token", request);
else
context.Principal = principal;
}
//AuthenticationBusiness.cs
public string GetSecretKey()
{
using (_unitOfWork)
{
var token = _unitOfWork.Tokens.GetToken();
return token.SecretKey ?? string.Empty;
}
}
//Dependency Injection using Unity
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
container.RegisterType<IContext, Context>(new HierarchicalLifetimeManager());
//UnitOfWork.cs
private readonly IContext _context;
public UnitOfWork(IContext context, IJWTRepository tokens)
{
_context = context;
Tokens = tokens;
}
public IJWTRepository Tokens { get; private set; }
public void Dispose()
{
_context.Dispose();
}
//Context.cs
public class Context : DbContext, IContext
{
public new void SaveChanges()
{
base.SaveChanges();
}
public new void Dispose()
{
base.Dispose();
}
}
//JWTRepository.cs
public class JWTRepository : Repository<JsonWebToken>, IJWTRepository
{
public JWTRepository(Context context) : base(context) { }
public JsonWebToken GetToken()
{
return Context.Tokens
.OrderBy(jwt => jwt.Id)
.Take(1)
.SingleOrDefault();
}
private Context Context => _context as Context;
}
If I try to remove this attribute and access the API multiple times nothing wrong happens so I am assuming that this has something to do with the fact that the attribute has asynchronous methods?