ProjectLighthouse/ProjectLighthouse.Servers.GameServer/Startup/TokenAuthHandler.cs
sudokoko 01e6fa191a
Update to .NET 8 and C# 12 (#952)
* Initial SDK and dependency bumps

* Bump Pomelo.EntityFrameworkCore.MySql to 8.0.0-beta.2

Should fix the MissingMethodException error in unit tests

* Update CI workflow to use .NET 8

* Apply suggested change from compile time warnings

* Fix digest tests

* Bump dependencies once more

* Update xunit

* Remove obsolete ISystemClock from TokenAuthHandler

* Update dependencies

* Add digest debug preprocessors back

* Maybe don't break #966

* Bump EF Driver and update various NET7 references

* Fix warnings in digest middleware tests

---------

Co-authored-by: Slendy <josh@slendy.pw>
2024-02-26 20:08:48 +00:00

48 lines
No EOL
1.7 KiB
C#

using System.Security.Claims;
using System.Text.Encodings.Web;
using LBPUnion.ProjectLighthouse.Database;
using LBPUnion.ProjectLighthouse.Types.Entities.Token;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
namespace LBPUnion.ProjectLighthouse.Servers.GameServer.Startup;
public class TokenAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly DatabaseContext database;
private const string cookie = "MM_AUTH";
public TokenAuthHandler
(
IOptionsMonitor<AuthenticationSchemeOptions> options,
UrlEncoder encoder,
DatabaseContext database
) : base(options, new NullLoggerFactory(), encoder)
{
this.database = database;
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
this.Context.Response.StatusCode = 403;
return Task.CompletedTask;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!this.Context.Request.Cookies.ContainsKey(cookie)) return AuthenticateResult.Fail("No auth cookie");
GameTokenEntity? gameToken = await this.database.GameTokenFromRequest(this.Request);
if (gameToken == null) return AuthenticateResult.Fail("No game token");
this.Context.Items["Token"] = gameToken;
Claim[] claims = {
new("userId", gameToken.UserId.ToString()),
};
ClaimsIdentity identity = new(claims, this.Scheme.Name);
ClaimsPrincipal principal = new(identity);
AuthenticationTicket ticket = new(principal, this.Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}