namespace OpenGMAO.Handlers
{
public class AuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public AuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
{
return AuthenticateResult.Fail("Unauthorized");
}
string authorizationHeader = Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authorizationHeader))
{
return AuthenticateResult.Fail("Unauthorized");
}
if (!authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.Fail("Unauthorized");
}
var token = authorizationHeader.Substring(7);
try
{
var handler = new JwtSecurityTokenHandler();
var tokenS = handler.ReadToken(token) as JwtSecurityToken;
if (tokenS == null)
{
return AuthenticateResult.Fail("Invalid token");
}
var claims = tokenS.Claims.ToList();
var claimsIdentity = new ClaimsIdentity(claims, Scheme.Name);
var ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), Scheme.Name);
return AuthenticateResult.Success(ticket);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error during token validation");
return AuthenticateResult.Fail("Unauthorized");
}
}
}
}