tuitio/IdentityServer.Application/Services/TokenService.cs

77 lines
2.5 KiB
C#
Raw Normal View History

using AutoMapper;
2021-11-13 17:17:13 +02:00
using IdentityServer.Domain.Abstractions;
using IdentityServer.Domain.Entities;
using IdentityServer.Domain.Models;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace IdentityServer.Application.Services
{
internal class TokenService : ITokenService
{
private readonly IMapper _mapper;
2021-11-13 17:17:13 +02:00
private readonly IConfigProvider _configProvider;
2021-11-13 17:17:13 +02:00
public TokenService(IMapper mapper, IConfigProvider configProvider)
{
_mapper = mapper;
2021-11-13 17:17:13 +02:00
_configProvider = configProvider;
}
2021-11-13 17:17:13 +02:00
public Token GenerateToken(AppUser user)
{
2021-11-13 17:17:13 +02:00
var tokenRaw = GenerateTokenRaw(user);
var currentDate = DateTime.Now;
var token = new Token() { Raw = tokenRaw, ValidFrom = currentDate, ValidUntil = currentDate.AddMinutes(_configProvider.Token.ValidityInMinutes) };
return token;
}
private string GenerateTokenRaw(AppUser user)
{
var tokenCore = GenerateTokenCore(user);
var tokenCoreString = JsonConvert.SerializeObject(tokenCore);
var tokenCoreBytes = Encoding.UTF8.GetBytes(tokenCoreString);
var tokenRaw = Convert.ToBase64String(tokenCoreBytes);
return tokenRaw;
}
2021-11-13 17:17:13 +02:00
private TokenCore GenerateTokenCore(AppUser user)
{
var tokenCore = _mapper.Map<TokenCore>(user);
tokenCore.LockStamp = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "");
return tokenCore;
}
public TokenCore ExtractTokenCore(string tokenRaw)
{
var valid = ValidateTokenRaw(tokenRaw);
if (!valid)
return null;
var tokenCoreBytes = Convert.FromBase64String(tokenRaw);
var tokenCoreString = Encoding.UTF8.GetString(tokenCoreBytes);
var tokenCore = JsonConvert.DeserializeObject<TokenCore>(tokenCoreString);
return tokenCore;
}
private bool ValidateTokenRaw(string tokenRaw)
{
if (string.IsNullOrWhiteSpace(tokenRaw))
return false;
if (!StringIsBase64(tokenRaw))
return false;
return true;
}
private bool StringIsBase64(string str)
{
str = str.Trim();
return (str.Length % 4 == 0) && Regex.IsMatch(str, @"^[a-zA-Z0-9+/]*={0,3}$", RegexOptions.None);
}
}
}