77 lines
2.5 KiB
C#
77 lines
2.5 KiB
C#
using AutoMapper;
|
|
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;
|
|
private readonly IConfigProvider _configProvider;
|
|
|
|
public TokenService(IMapper mapper, IConfigProvider configProvider)
|
|
{
|
|
_mapper = mapper;
|
|
_configProvider = configProvider;
|
|
}
|
|
|
|
public Token GenerateToken(AppUser user)
|
|
{
|
|
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;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|