Auth endpoints are now functional

This commit is contained in:
2023-08-13 00:54:23 -04:00
parent a636309b5a
commit fdf286e22f
26 changed files with 705 additions and 159 deletions

View File

@ -1,4 +1,6 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
@ -7,6 +9,8 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
namespace IO.Swagger.Security
{
@ -15,6 +19,9 @@ namespace IO.Swagger.Security
/// </summary>
public class BearerAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly string secretKey;
private readonly byte[] secretBytes;
/// <summary>
/// scheme name for authentication handler.
/// </summary>
@ -22,6 +29,8 @@ namespace IO.Swagger.Security
public BearerAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
secretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY");
secretBytes = Encoding.UTF8.GetBytes(secretKey);
}
/// <summary>
@ -37,22 +46,44 @@ namespace IO.Swagger.Security
{
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
/// TODO handle token.
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(secretBytes),
ValidateIssuer = false,
ValidateAudience = false
};
try
{
var claimsPrincipal = tokenHandler.ValidateToken(authHeader.Parameter, validationParameters, out _);
var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
{
var claims = new[]{ new Claim(ClaimTypes.NameIdentifier, userId.ToString()) };
var identity = new ClaimsIdentity(claims, SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
catch (Exception)
{
return AuthenticateResult.Fail("Invalid Auth Token");
}
}
catch
{
return AuthenticateResult.Fail("Invalid Authorization Header");
}
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, "changeme"),
new Claim(ClaimTypes.Name, "changeme"),
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
return AuthenticateResult.Fail("Missing Authorization Header");
}
}
}