Invalidate JWTs on profile changes
This commit is contained in:
@@ -6,11 +6,28 @@ namespace API.Contracts.Profiles.Responses;
|
||||
public class LoginResponse
|
||||
{
|
||||
[JsonPropertyName("Profile")]
|
||||
public required ProfileDTO Profile { get; set; }
|
||||
public ProfileDTO? Profile { get; set; }
|
||||
|
||||
[JsonPropertyName("AccessToken")]
|
||||
public required string AccessToken { get; set; }
|
||||
public string AccessToken { get; set; } = string.Empty;
|
||||
|
||||
[JsonPropertyName("ExpiresIn")]
|
||||
public required int ExpiresIn { get; set; }
|
||||
}
|
||||
public int ExpiresIn { get; set; }
|
||||
|
||||
[JsonPropertyName("Error")]
|
||||
public string Error { get; set; } = string.Empty;
|
||||
|
||||
public static LoginResponse Success(ProfileDTO profile, string accessToken, int expiresIn)
|
||||
=> new()
|
||||
{
|
||||
Profile = profile,
|
||||
AccessToken = accessToken,
|
||||
ExpiresIn = expiresIn,
|
||||
};
|
||||
|
||||
public static LoginResponse Fail(string? error)
|
||||
=> new()
|
||||
{
|
||||
Error = error ?? "An unexpected error occured"
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using API.Contracts.Profiles.Responses;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using RecNet.Application.Profiles;
|
||||
using RecNet.Application.Profiles.Login;
|
||||
@@ -6,8 +7,9 @@ using LoginRequest = API.Contracts.Profiles.Requests.LoginRequest;
|
||||
|
||||
namespace API.Controllers.Profiles.V1;
|
||||
|
||||
[Route("api/[controller]/v1")]
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[Route("api/[controller]/v1")]
|
||||
public class ProfilesController(IProfileService profileService) : ControllerBase
|
||||
{
|
||||
[HttpGet("{id:guid}")]
|
||||
@@ -28,6 +30,7 @@ public class ProfilesController(IProfileService profileService) : ControllerBase
|
||||
CancellationToken ct)
|
||||
=> await profileService.GetProfilesAsync(ids, ct);
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult<LoginResponse>> Login(
|
||||
[FromBody] LoginRequest request,
|
||||
@@ -42,13 +45,8 @@ public class ProfilesController(IProfileService profileService) : ControllerBase
|
||||
request.PlatformAuthentication
|
||||
), ct);
|
||||
if (!result.Succeeded)
|
||||
return BadRequest(result.Message);
|
||||
return LoginResponse.Fail(result.Message);
|
||||
|
||||
return new LoginResponse
|
||||
{
|
||||
Profile = result.Profile!,
|
||||
AccessToken = result.AccessToken!,
|
||||
ExpiresIn = result.ExpiresIn
|
||||
};
|
||||
return LoginResponse.Success(result.Profile!, result.AccessToken!, result.ExpiresIn);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using RecNet.Application;
|
||||
using RecNet.Application.Common.Security;
|
||||
using RecNet.Domain.Profiles;
|
||||
using RecNet.Infrastructure;
|
||||
using RecNet.Infrastructure.Services.Tokens;
|
||||
using RecNet.ServiceDefaults;
|
||||
@@ -15,17 +17,17 @@ public class Program
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
|
||||
builder.Services
|
||||
.AddOptions<NeutrinoOptions>()
|
||||
.Bind(builder.Configuration.GetSection("Neutrino"))
|
||||
.ValidateOnStart();
|
||||
|
||||
var recNetOptions = builder.Configuration.GetSection("RecNet").Get<RecNetOptions>()
|
||||
?? new RecNetOptions();
|
||||
|
||||
?? new RecNetOptions();
|
||||
|
||||
var jwtOptions = builder.Configuration.GetSection("Jwt").Get<JwtOptions>()
|
||||
?? new JwtOptions();
|
||||
?? new JwtOptions();
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
@@ -57,8 +59,28 @@ public class Program
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async context =>
|
||||
{
|
||||
var profileRepository = context.HttpContext.RequestServices
|
||||
.GetRequiredService<IProfileRepository>();
|
||||
|
||||
var userId = context.Principal?.GetProfileId();
|
||||
var tokenVersion = context.Principal?.GetTokenVersion();
|
||||
|
||||
if (userId.HasValue)
|
||||
{
|
||||
var profileTokenVersion = await profileRepository.GetProfileTokenVersion(userId.Value);
|
||||
|
||||
if (profileTokenVersion != tokenVersion)
|
||||
context.Fail("Unauthorized");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
@@ -76,4 +98,4 @@ public class Program
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,4 +16,15 @@ public static class ClaimsPrincipalExtensions
|
||||
|
||||
return profileId;
|
||||
}
|
||||
|
||||
public static Guid GetTokenVersion(this ClaimsPrincipal user)
|
||||
{
|
||||
var value = user.FindFirst("token_version")?.Value;
|
||||
|
||||
if (!Guid.TryParse(value, out var tokenVersion))
|
||||
throw new UnauthorizedAccessException(
|
||||
"Token version claim is missing or invalid.");
|
||||
|
||||
return tokenVersion;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@ namespace RecNet.Application.Common.Tokens;
|
||||
|
||||
public sealed record TokenVerifyResult(
|
||||
bool Succeeded,
|
||||
Guid? ProfileId)
|
||||
Guid? ProfileId,
|
||||
Guid? TokenVersion)
|
||||
{
|
||||
public static TokenVerifyResult Success(Guid profileId)
|
||||
=> new(true, profileId);
|
||||
public static TokenVerifyResult Success(Guid profileId, Guid tokenVersion)
|
||||
=> new(true, profileId, tokenVersion);
|
||||
|
||||
public static TokenVerifyResult Failure()
|
||||
=> new(false, null);
|
||||
=> new(false, null, null);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public class NeutrinoAuthorizationService(
|
||||
return NeutrinoAuthorizationResult.InvalidParameters();
|
||||
|
||||
var tokenVerifyResult = tokenService.VerifyToken(command.AccessToken);
|
||||
if (!tokenVerifyResult.Succeeded || tokenVerifyResult.ProfileId is null)
|
||||
if (!tokenVerifyResult.Succeeded || tokenVerifyResult.ProfileId is null || tokenVerifyResult.TokenVersion is null)
|
||||
return NeutrinoAuthorizationResult.AuthenticationFailed();
|
||||
|
||||
if (tokenVerifyResult.ProfileId.Value != command.ProfileId)
|
||||
@@ -25,6 +25,9 @@ public class NeutrinoAuthorizationService(
|
||||
if (profile is null || profile.IsBanned)
|
||||
return NeutrinoAuthorizationResult.AuthenticationFailed();
|
||||
|
||||
if (tokenVerifyResult.TokenVersion.Value != profile.TokenVersion)
|
||||
return NeutrinoAuthorizationResult.AuthenticationFailed();
|
||||
|
||||
return NeutrinoAuthorizationResult.Success(profile.ProfileId, profile.Name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,19 @@ namespace RecNet.Application.Profiles;
|
||||
|
||||
public interface IProfileService
|
||||
{
|
||||
// Profiles
|
||||
Task<ProfileDTO?> GetProfileAsync(Guid profileId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<ProfileDTO>> GetProfilesAsync(List<Guid> profileIds, CancellationToken ct = default);
|
||||
|
||||
// Avatar
|
||||
Task<AvatarDTO?> GetAvatarAsync(Guid profileId, CancellationToken ct = default);
|
||||
Task<AvatarDTO?> UpdateAvatarAsync(Guid profileId, UpdateAvatarCommand command, CancellationToken ct = default);
|
||||
|
||||
// PlayerSettings
|
||||
Task<IReadOnlyList<PlayerSettingDTO>> GetPlayerSettingsAsync(Guid profileId, CancellationToken ct = default);
|
||||
Task<bool> UpdatePlayerSettingAsync(Guid profileId, UpdatePlayerSettingCommand command, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<ProfileDTO>> GetProfilesAsync(List<Guid> profileIds, CancellationToken ct = default);
|
||||
|
||||
Task IncrementTokenVersion(Guid profileId, CancellationToken ct = default);
|
||||
|
||||
Task<LoginProfileResult> LoginAsync(LoginProfileCommand command, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
@@ -30,6 +30,15 @@ public class ProfileService(
|
||||
: mapper.Map<ProfileDTO>(profile);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<ProfileDTO>> GetProfilesAsync(
|
||||
List<Guid> profileIds,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var profiles = await profileRepository.GetByIdsAsync(profileIds, ct);
|
||||
|
||||
return mapper.Map<List<ProfileDTO>>(profiles);
|
||||
}
|
||||
|
||||
public async Task<AvatarDTO?> GetAvatarAsync(Guid profileId, CancellationToken ct = default)
|
||||
{
|
||||
var avatar = await profileRepository.GetAvatarByProfileIdAsync(profileId, ct);
|
||||
@@ -86,13 +95,15 @@ public class ProfileService(
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<ProfileDTO>> GetProfilesAsync(
|
||||
List<Guid> profileIds,
|
||||
CancellationToken ct = default)
|
||||
public async Task IncrementTokenVersion(Guid profileId, CancellationToken ct = default)
|
||||
{
|
||||
var profiles = await profileRepository.GetByIdsAsync(profileIds, ct);
|
||||
|
||||
return mapper.Map<List<ProfileDTO>>(profiles);
|
||||
var profile = await profileRepository.GetByIdWithSettingsAsync(profileId, ct);
|
||||
if (profile is null)
|
||||
return;
|
||||
|
||||
profile.IncrementTokenVersion();
|
||||
|
||||
await profileRepository.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<LoginProfileResult> LoginAsync(
|
||||
@@ -146,7 +157,7 @@ public class ProfileService(
|
||||
return LoginProfileResult.Fail("Platform Auth Failed: Invalid authentication");
|
||||
|
||||
if (profile.IsBanned)
|
||||
return LoginProfileResult.Fail("Profile is banned");
|
||||
return LoginProfileResult.Fail("TenWholeYears requires you to take a shower in order to continue playing.");
|
||||
|
||||
profile.RecordSuccessfulLogin(command.DeviceId, auth.Name);
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ public interface IProfileRepository
|
||||
Task<IReadOnlyList<Profile>> GetByIdsAsync(List<Guid> profileIds, CancellationToken ct = default);
|
||||
|
||||
Task<Profile?> GetByPlatform(PlatformType platform, string platformId, CancellationToken ct = default);
|
||||
|
||||
Task<Guid> GetProfileTokenVersion(Guid profileId, CancellationToken ct = default);
|
||||
|
||||
Task AddAsync(Profile profile, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@ public class Profile
|
||||
public bool IsModerator { get; private set; }
|
||||
public bool IsDeveloper { get; private set; }
|
||||
|
||||
public Guid TokenVersion { get; private set; } = Guid.NewGuid();
|
||||
|
||||
public DateTimeOffset CreatedAt { get; private set; }
|
||||
|
||||
public Avatar Avatar { get; private set; } = Avatar.Empty;
|
||||
@@ -111,6 +113,9 @@ public class Profile
|
||||
|
||||
existing.UpdateValue(value);
|
||||
}
|
||||
|
||||
public void IncrementTokenVersion()
|
||||
=> TokenVersion = Guid.NewGuid();
|
||||
|
||||
private static string RequireValue(string value, string parameterName)
|
||||
=> !string.IsNullOrWhiteSpace(value) ? value : throw new DomainException($"{parameterName} is required.");
|
||||
|
||||
233
src/RecNet.Infrastructure/Persistence/Migrations/20260628172910_TokenVersion.Designer.cs
generated
Normal file
233
src/RecNet.Infrastructure/Persistence/Migrations/20260628172910_TokenVersion.Designer.cs
generated
Normal file
@@ -0,0 +1,233 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using RecNet.Infrastructure.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace RecNet.Infrastructure.Persistence.Migrations
|
||||
{
|
||||
[DbContext(typeof(DatabaseContext))]
|
||||
[Migration("20260628172910_TokenVersion")]
|
||||
partial class TokenVersion
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Configuration.ServerConfig", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("ServerConfigs");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.GameVersions.GameVersion", b =>
|
||||
{
|
||||
b.Property<string>("Version")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("IsValid")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("Version");
|
||||
|
||||
b.ToTable("GameVersions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.PatchNotes.PatchNote", b =>
|
||||
{
|
||||
b.Property<string>("Version")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.PrimitiveCollection<List<string>>("Changes")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.Property<string>("Date")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)");
|
||||
|
||||
b.HasKey("Version");
|
||||
|
||||
b.ToTable("PatchNotes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.PlayerSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("UserId", "Key");
|
||||
|
||||
b.ToTable("PlayerSettings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.Profile", b =>
|
||||
{
|
||||
b.Property<Guid>("ProfileId")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.PrimitiveCollection<string>("DeviceIds")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<bool>("IsBanned")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsDeveloper")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsModerator")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<byte[]>("MetaAuthenticationSecret")
|
||||
.IsRequired()
|
||||
.HasColumnType("bytea");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("Platform")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)");
|
||||
|
||||
b.Property<string>("PlatformId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)");
|
||||
|
||||
b.Property<Guid>("TokenVersion")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("ProfileId");
|
||||
|
||||
b.HasIndex("Platform", "PlatformId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Profiles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.Relationship", b =>
|
||||
{
|
||||
b.Property<Guid>("OwnerProfileId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("ProfileId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("Ignored")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("Muted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("OwnerProfileId", "ProfileId");
|
||||
|
||||
b.HasIndex("ProfileId");
|
||||
|
||||
b.ToTable("Relationships");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.PlayerSetting", b =>
|
||||
{
|
||||
b.HasOne("RecNet.Domain.Profiles.Profile", null)
|
||||
.WithMany("Settings")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.Profile", b =>
|
||||
{
|
||||
b.OwnsOne("RecNet.Domain.Profiles.Avatar", "Avatar", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("ProfileId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("HairColor")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.Property<string>("OutfitSelections")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.Property<string>("SkinColor")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.HasKey("ProfileId");
|
||||
|
||||
b1.ToTable("Profiles");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("ProfileId");
|
||||
});
|
||||
|
||||
b.Navigation("Avatar")
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.Relationship", b =>
|
||||
{
|
||||
b.HasOne("RecNet.Domain.Profiles.Profile", null)
|
||||
.WithMany("Relationships")
|
||||
.HasForeignKey("OwnerProfileId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("RecNet.Domain.Profiles.Profile", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("ProfileId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("RecNet.Domain.Profiles.Profile", b =>
|
||||
{
|
||||
b.Navigation("Relationships");
|
||||
|
||||
b.Navigation("Settings");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace RecNet.Infrastructure.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class TokenVersion : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "TokenVersion",
|
||||
table: "Profiles",
|
||||
type: "uuid",
|
||||
nullable: false,
|
||||
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "TokenVersion",
|
||||
table: "Profiles");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,9 @@ namespace RecNet.Infrastructure.Persistence.Migrations
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("character varying(50)");
|
||||
|
||||
b.Property<Guid>("TokenVersion")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("ProfileId");
|
||||
|
||||
b.HasIndex("Platform", "PlatformId")
|
||||
|
||||
@@ -53,6 +53,15 @@ public class ProfileRepository(DatabaseContext dbContext) : IProfileRepository
|
||||
x.PlatformId == platformId,
|
||||
ct);
|
||||
|
||||
public Task<Guid> GetProfileTokenVersion(
|
||||
Guid profileId,
|
||||
CancellationToken ct = default)
|
||||
=> dbContext.Profiles
|
||||
.AsNoTracking()
|
||||
.Where(x => x.ProfileId == profileId)
|
||||
.Select(x => x.TokenVersion)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
public async Task AddAsync(
|
||||
Profile profile,
|
||||
CancellationToken ct = default)
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using RecNet.Application.Common.Interfaces;
|
||||
using RecNet.Application.Common.Security;
|
||||
using RecNet.Application.Common.Tokens;
|
||||
using RecNet.Domain.Profiles;
|
||||
|
||||
@@ -25,10 +26,11 @@ public class TokenService(IOptions<JwtOptions> options) : ITokenService
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(JwtRegisteredClaimNames.Sub, profile.ProfileId.ToString()),
|
||||
new("token_version", profile.TokenVersion.ToString()),
|
||||
new("rn.plat", ((int)profile.Platform).ToString()),
|
||||
new("rn.platid", profile.PlatformId)
|
||||
};
|
||||
|
||||
|
||||
if (profile.IsModerator)
|
||||
claims.Add(new Claim("role", "moderator"));
|
||||
|
||||
@@ -52,11 +54,11 @@ public class TokenService(IOptions<JwtOptions> options) : ITokenService
|
||||
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
return TokenVerifyResult.Failure();
|
||||
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
if (!tokenHandler.CanReadToken(token))
|
||||
return TokenVerifyResult.Failure();
|
||||
|
||||
|
||||
var validationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
@@ -72,20 +74,13 @@ public class TokenService(IOptions<JwtOptions> options) : ITokenService
|
||||
try
|
||||
{
|
||||
var principal = tokenHandler.ValidateToken(token, validationParameters, out _);
|
||||
|
||||
var profileIdClaim =
|
||||
principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ??
|
||||
principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
return Guid.TryParse(profileIdClaim, out var profileId)
|
||||
? TokenVerifyResult.Success(profileId)
|
||||
: TokenVerifyResult.Failure();
|
||||
var profileId = principal.GetProfileId();
|
||||
var tokenVersion = principal.GetTokenVersion();
|
||||
|
||||
return TokenVerifyResult.Success(profileId, tokenVersion);
|
||||
}
|
||||
catch (SecurityTokenException)
|
||||
{
|
||||
return TokenVerifyResult.Failure();
|
||||
}
|
||||
catch (ArgumentException)
|
||||
catch
|
||||
{
|
||||
return TokenVerifyResult.Failure();
|
||||
}
|
||||
@@ -93,4 +88,4 @@ public class TokenService(IOptions<JwtOptions> options) : ITokenService
|
||||
|
||||
private static SymmetricSecurityKey CreateSecurityKey(JwtOptions jwtOptions)
|
||||
=> new(Encoding.UTF8.GetBytes(jwtOptions.Secret));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user