-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Lev Khobotov
committed
Mar 20, 2024
1 parent
b9a333f
commit 6f4b0fa
Showing
2 changed files
with
46 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
using System; | ||
using System.Text.Json; | ||
using Microsoft.AspNetCore.WebUtilities; | ||
|
||
namespace Amphasis.Azure.WebPortal.Helpers; | ||
|
||
public static class JwtHelper | ||
{ | ||
public static DateTime GetValidTo(string encodedJsonWebToken) | ||
{ | ||
var destination = new Span<Range>(new Range[3]); | ||
var partsCount = encodedJsonWebToken.AsSpan().Split(destination, '.'); | ||
|
||
if (partsCount < 3) | ||
throw new JwtHelperException("Could not extract payload"); | ||
|
||
var payloadRange = destination[1]; | ||
var (offset, count) = payloadRange.GetOffsetAndLength(encodedJsonWebToken.Length); | ||
var bytes = WebEncoders.Base64UrlDecode(encodedJsonWebToken, offset, count); | ||
var payload = JsonSerializer.Deserialize<JwtPayload>(bytes, _jsonSerializerOptions); | ||
|
||
return DateTime.UnixEpoch.AddSeconds(payload.Exp); | ||
} | ||
|
||
static JwtHelper() | ||
{ | ||
_jsonSerializerOptions = new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; | ||
} | ||
|
||
private static readonly JsonSerializerOptions _jsonSerializerOptions; | ||
|
||
private sealed class JwtHelperException : Exception | ||
{ | ||
public JwtHelperException(string message) : base(message) | ||
{ | ||
} | ||
} | ||
|
||
private sealed record JwtPayload(int Exp); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters