Add JWT auth, token service & Neutrino endpoint
This commit is contained in:
@@ -4,13 +4,16 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>cfcf35c1-8c26-473a-a8e9-44ba009adea8</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\RecNet.Application\RecNet.Application.csproj" />
|
||||
<ProjectReference Include="..\RecNet.Infrastructure\RecNet.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\RecNet.ServiceDefaults\RecNet.ServiceDefaults.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace API.Configurations;
|
||||
|
||||
public class RecNetConfiguration
|
||||
public class RecNetOptions
|
||||
{
|
||||
public bool UseForwardedHeaders { get; set; } = true;
|
||||
}
|
||||
25
API/Contracts/Neutrino/Enums/AuthenticationResultCode.cs
Normal file
25
API/Contracts/Neutrino/Enums/AuthenticationResultCode.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace API.Contracts.Neutrino.Enums;
|
||||
|
||||
public enum AuthenticationResultCode
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates that authentication is incomplete and only the associated data is returned.
|
||||
/// </summary>
|
||||
/// <remarks>This value is typically used when launching the game with no account, in which data to authenticate is not provided.</remarks>
|
||||
AuthenticationIncomplete,
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that authentication was successful.
|
||||
/// </summary>
|
||||
AuthenticationSuccessful,
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that authentication failed due to incorrect credentials.
|
||||
/// </summary>
|
||||
AuthenticationFailedWrongCredentials,
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the parameters provided to the operation are invalid.
|
||||
/// </summary>
|
||||
InvalidParameters
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace API.Contracts.Neutrino.Requests;
|
||||
|
||||
public class NeutrinoAuthenticateRequest
|
||||
{
|
||||
[JsonPropertyName("profileId")]
|
||||
public Guid ProfileId;
|
||||
|
||||
[JsonPropertyName("accessToken")]
|
||||
public required string AccessToken;
|
||||
|
||||
[JsonPropertyName("appVersion")]
|
||||
public required string AppVersion;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using API.Contracts.Neutrino.Enums;
|
||||
|
||||
namespace API.Contracts.Neutrino.Responses;
|
||||
|
||||
// {"ResultCode":1,"UserId":"their user id","Nickname":"splotybean"}
|
||||
public class NeutrinoAuthenticateResponse : NeutrinoResultCodeResponse
|
||||
{
|
||||
public static NeutrinoAuthenticateResponse Success(string userId, string nickname) => new()
|
||||
{
|
||||
ResultCode = (byte)AuthenticationResultCode.AuthenticationSuccessful,
|
||||
UserId = userId,
|
||||
Nickname = nickname
|
||||
};
|
||||
|
||||
public static NeutrinoAuthenticateResponse Failure(AuthenticationResultCode error) => new()
|
||||
{
|
||||
ResultCode = (byte)error
|
||||
};
|
||||
|
||||
[JsonPropertyName(name: "UserId")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? UserId { get; set; }
|
||||
|
||||
[JsonPropertyName(name: "Nickname")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? Nickname { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace API.Contracts.Neutrino.Responses;
|
||||
|
||||
public class NeutrinoResultCodeResponse
|
||||
{
|
||||
public static NeutrinoResultCodeResponse Success() => new NeutrinoResultCodeResponse
|
||||
{
|
||||
ResultCode = 0
|
||||
};
|
||||
|
||||
public static NeutrinoResultCodeResponse Failure(byte resultCode, string? message = null)
|
||||
{
|
||||
return new NeutrinoResultCodeResponse
|
||||
{
|
||||
Message = message,
|
||||
ResultCode = resultCode
|
||||
};
|
||||
}
|
||||
|
||||
[JsonPropertyName(name: "Data")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? Data { get; set; }
|
||||
|
||||
[JsonPropertyName(name: "Message")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? Message { get; set; }
|
||||
|
||||
[JsonPropertyName(name: "ResultCode")]
|
||||
public byte ResultCode { get; set; }
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
using RecNet.Application.Profiles;
|
||||
using System.Text.Json.Serialization;
|
||||
using RecNet.Application.Profiles;
|
||||
|
||||
namespace API.Contracts.Profiles.Responses;
|
||||
|
||||
public class LoginResponse
|
||||
{
|
||||
[JsonPropertyName("Profile")]
|
||||
public required ProfileDTO Profile { get; set; }
|
||||
|
||||
[JsonPropertyName("AccessToken")]
|
||||
public required string AccessToken { get; set; }
|
||||
|
||||
[JsonPropertyName("ExpiresIn")]
|
||||
public required int ExpiresIn { get; set; }
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using RecNet.Application.Services.Configuration;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using RecNet.Domain.Services.Configuration;
|
||||
|
||||
namespace API.Controllers.Config.V1;
|
||||
|
||||
@@ -11,7 +11,7 @@ public class ConfigController(IConfigService configService) : ControllerBase
|
||||
public async Task<ActionResult<string>> GetMotd(CancellationToken ct = default)
|
||||
{
|
||||
var motd = await configService.GetAsync("Config:MOTD", "Ten Whole Years!", ct);
|
||||
|
||||
|
||||
return Ok(motd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
82
API/Controllers/Neutrino/NeutrinoController.cs
Normal file
82
API/Controllers/Neutrino/NeutrinoController.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using API.Contracts.Neutrino.Enums;
|
||||
using API.Contracts.Neutrino.Requests;
|
||||
using API.Contracts.Neutrino.Responses;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using RecNet.Domain.Repositories;
|
||||
using RecNet.Domain.Services.Tokens;
|
||||
|
||||
namespace API.Controllers.Neutrino;
|
||||
|
||||
[Route("[controller]")]
|
||||
[ApiController]
|
||||
public class NeutrinoController(
|
||||
IProfileRepository profileRepository,
|
||||
ITokenService tokenService) : ControllerBase
|
||||
{
|
||||
// This route will be kind of abysmal so bare with it.
|
||||
[Route("authorize")]
|
||||
public async Task<ActionResult<NeutrinoAuthenticateResponse>> AuthorizeNeutrinoAsync()
|
||||
{
|
||||
// Photon sends the request with Content-Type: text/plain instead of application/json
|
||||
// This is a really janky workaround since we can't use [FromBody] to automatically parse the data.
|
||||
using var reader = new StreamReader(Request.Body);
|
||||
string rawText = await reader.ReadToEndAsync();
|
||||
|
||||
NeutrinoAuthenticateRequest? request;
|
||||
|
||||
try
|
||||
{
|
||||
request = JsonSerializer.Deserialize<NeutrinoAuthenticateRequest>(rawText, new JsonSerializerOptions
|
||||
{
|
||||
IncludeFields = true,
|
||||
PropertyNameCaseInsensitive = true
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Ok(
|
||||
NeutrinoAuthenticateResponse.Failure(
|
||||
AuthenticationResultCode.InvalidParameters));
|
||||
}
|
||||
|
||||
// 1. Check if request parameters aren't empty
|
||||
if (request is null ||
|
||||
request.ProfileId == Guid.Empty ||
|
||||
string.IsNullOrWhiteSpace(request.AccessToken))
|
||||
return Ok(
|
||||
NeutrinoAuthenticateResponse.Failure(
|
||||
AuthenticationResultCode.InvalidParameters));
|
||||
|
||||
// 2. Verify accessToken is valid
|
||||
var tokenVerifyResult = tokenService.VerifyToken(request.AccessToken);
|
||||
if (tokenVerifyResult.IsError || !TryGetProfileId(tokenVerifyResult.Claims, out var tokenAccountId))
|
||||
return Ok(
|
||||
NeutrinoAuthenticateResponse.Failure(
|
||||
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
|
||||
|
||||
// 3. Verify that the accountId from the request matches the one from the token
|
||||
if (tokenAccountId != request.ProfileId)
|
||||
return Ok(
|
||||
NeutrinoAuthenticateResponse.Failure(
|
||||
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
|
||||
|
||||
// 4. Get the profile to check if it exists, and for the name
|
||||
var profile = await profileRepository.GetByIdAsync(request.ProfileId);
|
||||
if (profile is null)
|
||||
return Ok(
|
||||
NeutrinoAuthenticateResponse.Failure(
|
||||
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
|
||||
|
||||
return Ok(
|
||||
NeutrinoAuthenticateResponse.Success(
|
||||
userId: request.ProfileId.ToString(),
|
||||
nickname: profile.Name
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private static bool TryGetProfileId(IEnumerable<Claim> claims, out Guid accountId)
|
||||
=> Guid.TryParse(claims.FirstOrDefault(c => c.Type == "sub")?.Value, out accountId);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using API.Contracts.Profiles.Responses;
|
||||
using API.Contracts.Profiles.Responses;
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using RecNet.Application.Profiles;
|
||||
using RecNet.Domain.Repositories;
|
||||
using RecNet.Domain.Services.Tokens;
|
||||
using LoginRequest = API.Contracts.Profiles.Requests.LoginRequest;
|
||||
using Profile = RecNet.Domain.Entities.Profiles.Profile;
|
||||
|
||||
@@ -10,9 +12,11 @@ namespace API.Controllers.Profiles.V1;
|
||||
|
||||
[Route("api/[controller]/v1")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ProfilesController(
|
||||
IProfileRepository profileRepository,
|
||||
IMapper mapper) : ControllerBase
|
||||
IProfileRepository profileRepository,
|
||||
IMapper mapper,
|
||||
ITokenService tokenService) : ControllerBase
|
||||
{
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<ProfileDTO>> GetProfile(
|
||||
@@ -22,7 +26,7 @@ public class ProfilesController(
|
||||
var profile = await profileRepository.GetByIdAsync(id, ct);
|
||||
if (profile == null)
|
||||
return NotFound();
|
||||
|
||||
|
||||
return mapper.Map<ProfileDTO>(profile);
|
||||
}
|
||||
|
||||
@@ -32,33 +36,44 @@ public class ProfilesController(
|
||||
CancellationToken ct)
|
||||
{
|
||||
var profiles = await profileRepository.GetByIdsAsync(ids, ct);
|
||||
|
||||
|
||||
return mapper.Map<List<ProfileDTO>>(profiles);
|
||||
}
|
||||
|
||||
// TODO: Implement
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult<LoginResponse>> Login(
|
||||
[FromBody] LoginRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var name = GenerateRandomName();
|
||||
|
||||
var profile = await profileRepository.GetByPlatform(request.PlatformType, request.PlatformId, ct);
|
||||
if (profile is null)
|
||||
{
|
||||
profile = Profile.Create(request.Username, request.PlatformType, request.PlatformId);
|
||||
profile = Profile.Create(name, request.PlatformType, request.PlatformId);
|
||||
await profileRepository.AddAsync(profile, ct);
|
||||
}
|
||||
|
||||
|
||||
profile.AddDeviceId(request.DeviceId);
|
||||
|
||||
if (request.Username != profile.Name)
|
||||
profile.SetName(request.Username);
|
||||
|
||||
|
||||
await profileRepository.SaveChangesAsync(ct);
|
||||
|
||||
if (profile.IsBanned)
|
||||
return BadRequest();
|
||||
|
||||
var token = tokenService.GenerateProfileToken(profile);
|
||||
|
||||
return new LoginResponse
|
||||
{
|
||||
Profile = mapper.Map<ProfileDTO>(profile)
|
||||
Profile = mapper.Map<ProfileDTO>(profile),
|
||||
AccessToken = token.AccessToken,
|
||||
ExpiresIn = token.ExpiresIn
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: REPLACE WITH BETTER GENERATOR, THIS IS TEMP.
|
||||
private static string GenerateRandomName()
|
||||
=> string.Concat("rr", Guid.NewGuid().ToString("N").AsSpan(0, 18));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
using System.Text;
|
||||
using API.Configurations;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using RecNet.Application;
|
||||
using RecNet.Infrastructure;
|
||||
using RecNet.Infrastructure.Services.Tokens;
|
||||
using RecNet.ServiceDefaults;
|
||||
|
||||
namespace API;
|
||||
@@ -11,12 +15,15 @@ public class Program
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
var recNetOptions = builder.Configuration.GetSection("RecNet").Get<RecNetOptions>()
|
||||
?? new RecNetOptions();
|
||||
|
||||
var recNetOptions = builder.Configuration.GetSection("RecNet").Get<RecNetConfiguration>()
|
||||
?? new RecNetConfiguration();
|
||||
var jwtOptions = builder.Configuration.GetSection("Jwt").Get<JwtOptions>()
|
||||
?? new JwtOptions();
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders =
|
||||
@@ -26,18 +33,37 @@ public class Program
|
||||
options.KnownIPNetworks.Clear();
|
||||
options.KnownProxies.Clear();
|
||||
});
|
||||
|
||||
|
||||
builder.Services.AddApplication();
|
||||
builder.AddInfrastructure();
|
||||
|
||||
builder.Services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Secret)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtOptions.Issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
|
||||
if (recNetOptions.UseForwardedHeaders)
|
||||
app.UseForwardedHeaders();
|
||||
|
||||
// app.UseAuthentication();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
Reference in New Issue
Block a user