public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary["as:client_id"];
            if (string.IsNullOrWhiteSpace(clientId))
            {
                return;
            }

            var refreshTokenId = Guid.NewGuid().ToString("N");
            var refreshTokenLifetime = context.OwinContext.Get<string>("as:clientRefreshTokenLifetime");
            var token = new RefreshToken
            {
                Id = AuthorizationHelpers.GetHash(refreshTokenId),
                ClientApplicationId = clientId,
                Subject = context.Ticket.Identity.Name,
                IssuedAt = DateTime.UtcNow,
                ExpiresAt = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifetime))
            };

            context.Ticket.Properties.IssuedUtc = token.IssuedAt;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresAt;

            token.ProtectedTicket = context.SerializeTicket();

            if (await _userRepository.TryAddRefreshTokenAsync(token))
            {
                context.SetToken(refreshTokenId);
            }
        }
        public async Task<bool> TryAddRefreshTokenAsync(RefreshToken refreshToken)
        {
            var existingToken = _context.RefreshTokens.SingleOrDefault(x => x.Subject == refreshToken.Subject && x.ClientApplicationId == refreshToken.ClientApplicationId);

            if (existingToken != null)
            {
                await TryRemoveRefreshTokenAsync(existingToken);
            }

            _context.RefreshTokens.Add(refreshToken);
            return await _context.SaveChangesAsync() > 0;
        }
 public async Task<bool> TryRemoveRefreshTokenAsync(RefreshToken refreshToken)
 {
     _context.RefreshTokens.Remove(refreshToken);
     return await _context.SaveChangesAsync() > 0;
 }