Skip to content

Commit

Permalink
More clean up and comments
Browse files Browse the repository at this point in the history
  • Loading branch information
davidfowl committed Jul 14, 2023
1 parent 7c18bec commit 182c354
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 15 deletions.
2 changes: 1 addition & 1 deletion TodoApi.Tests/TodoApplication.cs
Expand Up @@ -55,7 +55,7 @@ protected override IHost CreateHost(IHostBuilder builder)
// we use an ephemeral key provider and repository to avoid filesystem contention issues
services.AddSingleton<IDataProtectionProvider, EphemeralDataProtectionProvider>();
services.AddTokenService();
services.AddScoped<TokenService>();
});

return base.CreateHost(builder);
Expand Down
20 changes: 6 additions & 14 deletions TodoApi.Tests/TokenService.cs
Expand Up @@ -5,15 +5,6 @@

namespace TodoApi;

public static class AuthenticationServiceExtensions
{
public static IServiceCollection AddTokenService(this IServiceCollection services)
{
// Wire up the token service
return services.AddScoped<TokenService>();
}
}

public sealed class TokenService(SignInManager<TodoUser> signInManager, IOptionsMonitor<BearerTokenOptions> options)
{
private readonly BearerTokenOptions _options = options.Get(IdentityConstants.BearerScheme);
Expand All @@ -27,17 +18,18 @@ public async Task<string> GenerateTokenAsync(string username, bool isAdmin = fal
((ClaimsIdentity?)claimsPrincipal.Identity)?.AddClaim(new(ClaimTypes.Role, "admin"));
}

var utcNow = (_options.TimeProvider ?? TimeProvider.System).GetUtcNow();
// This is copied from https://github.com/dotnet/aspnetcore/blob/238dabc8bf7a6d9485d420db01d7942044b218ee/src/Security/Authentication/BearerToken/src/BearerTokenHandler.cs#L66
var timeProvider = _options.TimeProvider ?? TimeProvider.System;

var utcNow = timeProvider.GetUtcNow();

var properties = new AuthenticationProperties
{
ExpiresUtc = utcNow + _options.BearerTokenExpiration
};

var ticket = CreateBearerTicket(claimsPrincipal, properties);

static AuthenticationTicket CreateBearerTicket(ClaimsPrincipal user, AuthenticationProperties properties)
=> new(user, properties, $"{IdentityConstants.BearerScheme}:AccessToken");
var ticket = new AuthenticationTicket(
claimsPrincipal, properties, $"{IdentityConstants.BearerScheme}:AccessToken");

return _options.BearerTokenProtector.Protect(ticket);
}
Expand Down

0 comments on commit 182c354

Please sign in to comment.