Skip to content

Instantly share code, notes, and snippets.

@Hobart2967
Created October 31, 2021 13:56
Show Gist options
  • Select an option

  • Save Hobart2967/708a30eaa4f604cc0f9ce22032b7df3c to your computer and use it in GitHub Desktop.

Select an option

Save Hobart2967/708a30eaa4f604cc0f9ce22032b7df3c to your computer and use it in GitHub Desktop.
JwtGeneration .NET
using Avsn.Core.Accounting.Api.Contracts;
using Microsoft.Extensions.Options;
using Wyrekit.Core.Api.Composition.Abstraction;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace Avsn.Core.Accounting.Api.Services
{
[ServiceDescriptor(typeof(IJwtFactory))]
public class JwtFactory : IJwtFactory
{
private readonly JwtIssuerOptions _jwtOptions;
public const string Rol = "rol", Id = "id";
public const string ApiAccess = "api_access";
public JwtFactory(IOptions<JwtIssuerOptions> jwtOptions)
{
_jwtOptions = jwtOptions.Value;
ThrowIfInvalidOptions(_jwtOptions);
}
public string GenerateEncodedToken(string userName, ClaimsIdentity identity)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userName),
new Claim(JwtRegisteredClaimNames.Jti, _jwtOptions.JtiGenerator().Result),
new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
identity.FindFirst(Rol),
identity.FindFirst(Id)
};
// Create the JWT security token and encode it.
var jwt = new JwtSecurityToken(
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
claims: claims,
notBefore: _jwtOptions.NotBefore,
expires: _jwtOptions.Expiration,
signingCredentials: _jwtOptions.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
return encodedJwt;
}
public ClaimsIdentity GenerateClaimsIdentity(string userName, string id)
{
return new ClaimsIdentity(new GenericIdentity(userName, "Token"), new[]
{
new Claim(Id, id),
new Claim(Rol, ApiAccess)
});
}
/// <returns>Date converted to seconds since Unix epoch (Jan 1, 1970, midnight UTC).</returns>
private static long ToUnixEpochDate(DateTime date)
=> (long)Math.Round((date.ToUniversalTime() -
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero))
.TotalSeconds);
private static void ThrowIfInvalidOptions(JwtIssuerOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (options.ValidFor <= TimeSpan.Zero)
{
throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(JwtIssuerOptions.ValidFor));
}
if (options.SigningCredentials == null)
{
throw new ArgumentNullException(nameof(JwtIssuerOptions.SigningCredentials));
}
if (options.JtiGenerator == null)
{
throw new ArgumentNullException(nameof(JwtIssuerOptions.JtiGenerator));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment