Пример #1
0
 public async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, Models.DeviceCode data)
 {
     if (deviceCode == null || userCode == null || data == null)
     {
         return;
     }
     using (var connection = new SqlConnection(_dapperStoreOptions.DbConnectionString))
     {
         var entity = new Entities.DeviceFlowCodes
         {
             DeviceCode   = deviceCode,
             UserCode     = userCode,
             ClientId     = data.ClientId,
             SubjectId    = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value,
             CreationTime = data.CreationTime,
             Expiration   = data.CreationTime.AddSeconds(data.Lifetime),
             Data         = _persistentGrantSerializer.Serialize(data)
         };
         var sql = $@"
         INSERT
         INTO DeviceFlowCodes(DeviceCode, UserCode, SubjectId, ClientId, CreationTime, Expiration, Data)
         VALUES(@DeviceCode, @UserCode, @SubjectId, @ClientId, @CreationTime, @Expiration, @Data);
         ";
         await connection.ExecuteAsync(sql, new { entity.DeviceCode, entity.UserCode, entity.SubjectId, entity.ClientId, entity.CreationTime, entity.Expiration, entity.Data });
     }
 }
Пример #2
0
        protected async Task <string> StoreAsync(TDto dto, DateTime?expiration)
        {
            dto = dto ?? throw new ArgumentNullException(nameof(dto));

            var clientId = GetClientId(dto);

            var subjectId = GetSubjectId(dto);

            var entity = await GetEntityBySubjectAndClient(subjectId, clientId)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                entity = CreateEntity(dto, clientId, subjectId, expiration);
                await _session.StoreAsync(entity, $"{typeof(TEntity).Name.ToLowerInvariant()}/{entity.Id}");
            }
            else
            {
                entity.Data       = _serializer.Serialize(dto);
                entity.Expiration = GetExpiration(dto);
            }

            await _session.SaveChangesAsync().ConfigureAwait(false);

            return(entity.Id);
        }
Пример #3
0
        protected async Task <string> StoreAsync(TDto dto, DateTime?expiration)
        {
            dto = dto ?? throw new ArgumentNullException(nameof(dto));

            var clientId = GetClientId(dto);

            var subjectId = GetSubjectId(dto);

            var entity = await GetEntityBySubjectAndClient(subjectId, clientId)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                entity = CreateEntity(dto, clientId, subjectId, expiration);
                await _context.AddAsync(entity);
            }
            else
            {
                entity.Data       = _serializer.Serialize(dto);
                entity.Expiration = GetExpiration(dto);
            }

            try
            {
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (DbUpdateException e) when(e.InnerException == null)
            {
                // store can already be done
            }
            return(entity.Id);
        }
Пример #4
0
        public void AssertDeviceCodesEqual(DeviceCode expected, DeviceCode actual)
        {
            Assert.IsNotNull(expected);
            Assert.IsNotNull(actual);

            Assert.AreEqual <string>(_persistentGrantSerializer.Serialize(expected),
                                     _persistentGrantSerializer.Serialize(actual));
        }
Пример #5
0
        private async Task <bool> SetAsyncInner(
            string key,
            T item,
            TimeSpan expiration)
        {
            try
            {
                var cacheKey = GetKey(key);
                await _handle.cache.InsertAsync(
                    cacheKey,
                    new CacheItem(_serializer.Serialize <T>(item))
                {
                    Expiration =
                        GetExpiration(expiration)
                });

                return(true);
            }
            catch (Exception ex)
            {
                if (_errorLoggingEnabled)
                {
                    _logger.LogError(
                        ex,
                        $"Something wrong with SetAsync for key {key}");
                }
                throw;
            }
        }
Пример #6
0
        public Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, Models.DeviceCode data)
        {
            deviceCode = deviceCode ?? throw new ArgumentNullException(nameof(deviceCode));
            userCode   = userCode ?? throw new ArgumentNullException(nameof(userCode));
            data       = data ?? throw new ArgumentNullException(nameof(data));

            var entity = new DeviceCode
            {
                Code       = deviceCode,
                UserCode   = userCode,
                Data       = _serializer.Serialize(data),
                ClientId   = data.ClientId,
                SubjectId  = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value,
                Expiration = data.CreationTime.AddSeconds(data.Lifetime),
            };

            return(_store.CreateAsync(entity));
        }
Пример #7
0
        public async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, Models.DeviceCode data)
        {
            deviceCode = deviceCode ?? throw new ArgumentNullException(nameof(deviceCode));
            userCode   = userCode ?? throw new ArgumentNullException(nameof(userCode));
            data       = data ?? throw new ArgumentNullException(nameof(data));

            var entity = new DeviceCode
            {
                Id         = Guid.NewGuid().ToString(),
                Code       = deviceCode,
                UserCode   = userCode,
                Data       = _serializer.Serialize(data),
                ClientId   = data.ClientId,
                SubjectId  = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value,
                Expiration = data.CreationTime.AddSeconds(data.Lifetime),
            };

            await _context.DeviceCodes.AddAsync(entity).ConfigureAwait(false);

            await _context.SaveChangesAsync().ConfigureAwait(false);
        }
        public async Task FindByUserCodeAsync_WhenUserCodeExists_ExpectDataRetrievedCorrectly()
        {
            var testDeviceCode = $"device_{Guid.NewGuid()}";
            var testUserCode   = $"user_{Guid.NewGuid()}";

            var expectedSubject        = $"sub_{Guid.NewGuid()}";
            var expectedDeviceCodeData = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29).AsUtc(),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                    new Claim(JwtClaimTypes.Subject, expectedSubject)
                }))
            };

            await _context.DeviceFlowCodes.AddAsync(new DeviceFlowCodes
            {
                DeviceCode   = testDeviceCode,
                UserCode     = testUserCode,
                ClientId     = expectedDeviceCodeData.ClientId,
                SubjectId    = expectedDeviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = expectedDeviceCodeData.CreationTime,
                Expiration   = expectedDeviceCodeData.CreationTime.AddSeconds(expectedDeviceCodeData.Lifetime),
                Data         = _serializer.Serialize(expectedDeviceCodeData)
            });

            DeviceCode code;
            var        store = new DeviceFlowStore(_context, new PersistentGrantSerializer(), FakeLogger <DeviceFlowStore> .Create());

            code = await store.FindByUserCodeAsync(testUserCode);

            code.Should().BeEquivalentTo(expectedDeviceCodeData,
                                         assertionOptions => assertionOptions.Excluding(x => x.Subject));

            code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull();
        }
Пример #9
0
        protected async Task <string> StoreAsync(TDto dto, DateTime?expiration)
        {
            dto = dto ?? throw new ArgumentNullException(nameof(dto));

            var clientId = GetClientId(dto);

            var subjectId = GetSubjectId(dto);

            var entity = await GetEntityBySubjectAndClient(subjectId, clientId)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                entity = CreateEntity(dto, clientId, subjectId, expiration);
                entity = await _store.CreateAsync(entity).ConfigureAwait(false);
            }
            else
            {
                entity.Data = _serializer.Serialize(dto);
                await _store.UpdateAsync(entity).ConfigureAwait(false);
            }

            return(entity.Id);
        }
Пример #10
0
        public async Task <string> StoreAuthorizationCodeAsync(AuthorizationCode code)
        {
            code = code ?? throw new ArgumentNullException(nameof(code));

            var newEntity = new Entity.AuthorizationCode
            {
                Id         = Guid.NewGuid().ToString(),
                ClientId   = code.ClientId,
                Data       = _serializer.Serialize(code),
                Expiration = code.CreationTime.AddSeconds(code.Lifetime)
            };

            var entity = await _store.CreateAsync(newEntity).ConfigureAwait(false);

            return(entity.Id);
        }
Пример #11
0
        /// <summary>
        /// Converts a model to an entity.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="xpoDeviceFlowCodes"></param>
        /// <param name="deviceCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        protected XpoDeviceFlowCodes ToEntity(DeviceCode model, XpoDeviceFlowCodes xpoDeviceFlowCodes, string deviceCode, string userCode)
        {
            if (model == null || xpoDeviceFlowCodes == null || deviceCode == null || userCode == null)
            {
                return(null);
            }

            xpoDeviceFlowCodes.DeviceCode   = deviceCode;
            xpoDeviceFlowCodes.UserCode     = userCode;
            xpoDeviceFlowCodes.ClientId     = model.ClientId;
            xpoDeviceFlowCodes.SubjectId    = model.Subject?.FindFirst(JwtClaimTypes.Subject).Value;
            xpoDeviceFlowCodes.CreationTime = model.CreationTime;
            xpoDeviceFlowCodes.Expiration   = model.CreationTime.AddSeconds(model.Lifetime);
            xpoDeviceFlowCodes.Data         = Serializer.Serialize(model);

            return(xpoDeviceFlowCodes);
        }
        private DeviceFlowCodes ToEntity(DeviceCode model, string deviceCode, string userCode)
        {
            if (model == null || deviceCode == null || userCode == null)
            {
                return(null);
            }

            return(new DeviceFlowCodes
            {
                DeviceCode = deviceCode,
                UserCode = userCode,
                ClientId = model.ClientId,
                SubjectId = model.Subject?.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = model.CreationTime,
                Expiration = model.CreationTime.AddSeconds(model.Lifetime),
                Data = _serializer.Serialize(model)
            });
        }
Пример #13
0
        /// <summary>
        /// Stores the item.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="item">The item.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="subjectId">The subject identifier.</param>
        /// <param name="created">The created.</param>
        /// <param name="expiration">The expiration.</param>
        /// <returns></returns>
        protected async Task StoreItemAsync(string key, T item, string clientId, string subjectId, DateTime created, DateTime?expiration)
        {
            key = GetHashedKey(key);

            var json = _serializer.Serialize(item);

            var grant = new PersistedGrant
            {
                Key          = key,
                Type         = _grantType,
                ClientId     = clientId,
                SubjectId    = subjectId,
                CreationTime = created,
                Expiration   = expiration,
                Data         = json
            };

            await _store.StoreAsync(grant);
        }
Пример #14
0
    /// <summary>
    /// Converts a model to an entity.
    /// </summary>
    /// <param name="model"></param>
    /// <param name="deviceCode"></param>
    /// <param name="userCode"></param>
    /// <returns></returns>
    protected DeviceFlowCodes ToEntity(DeviceCode model, string deviceCode, string userCode)
    {
        // TODO: consider removing this in v7.0 since it's not properly/fully used

        if (model == null || deviceCode == null || userCode == null)
        {
            return(null);
        }

        return(new DeviceFlowCodes
        {
            DeviceCode = deviceCode,
            UserCode = userCode,
            ClientId = model.ClientId,
            SubjectId = model.Subject?.FindFirst(JwtClaimTypes.Subject).Value,
            SessionId = model.SessionId,
            Description = model.Description,
            CreationTime = model.CreationTime,
            Expiration = model.CreationTime.AddSeconds(model.Lifetime),
            Data = Serializer.Serialize(model)
        });
    }
        public async Task StoreDeviceAuthorizationAsync_WhenUserCodeAlreadyExists_ExpectException()
        {
            using var ravenStore = GetDocumentStore();
            await new DeviceFlowCodeIndex().ExecuteAsync(ravenStore);

            var existingUserCode = $"user_{Guid.NewGuid().ToString()}";
            var deviceCodeData   = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(new ClaimsIdentity(
                                                          new List <Claim> {
                    new Claim(JwtClaimTypes.Subject, $"sub_{Guid.NewGuid().ToString()}")
                }))
            };

            using (var session = ravenStore.OpenSession())
            {
                session.Store(new DeviceFlowCode
                {
                    DeviceCode   = $"device_{Guid.NewGuid().ToString()}",
                    UserCode     = existingUserCode,
                    ClientId     = deviceCodeData.ClientId,
                    SubjectId    = deviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                    CreationTime = deviceCodeData.CreationTime,
                    Expiration   = deviceCodeData.CreationTime.AddSeconds(deviceCodeData.Lifetime),
                    Data         = serializer.Serialize(deviceCodeData)
                });
                session.SaveChanges();
            }

            WaitForIndexing(ravenStore);

            using (var session = ravenStore.OpenAsyncSession())
            {
                var store = new DeviceFlowStore(session, new PersistentGrantSerializer(),
                                                FakeLogger <DeviceFlowStore> .Create());

                await Assert.ThrowsAsync <Exception>(() =>
                                                     store.StoreDeviceAuthorizationAsync($"device_{Guid.NewGuid().ToString()}", existingUserCode,
                                                                                         deviceCodeData));
            }
        }
    public async Task StoreDeviceAuthorizationAsync_WhenUserCodeAlreadyExists_ExpectException(DbContextOptions <PersistedGrantDbContext> options)
    {
        var existingUserCode = $"user_{Guid.NewGuid().ToString()}";
        var deviceCodeData   = new DeviceCode
        {
            ClientId        = "device_flow",
            RequestedScopes = new[] { "openid", "api1" },
            CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
            Lifetime        = 300,
            IsOpenId        = true,
            Subject         = new ClaimsPrincipal(new ClaimsIdentity(
                                                      new List <Claim> {
                new Claim(JwtClaimTypes.Subject, $"sub_{Guid.NewGuid().ToString()}")
            }))
        };

        using (var context = new PersistedGrantDbContext(options))
        {
            context.DeviceFlowCodes.Add(new DeviceFlowCodes
            {
                DeviceCode   = $"device_{Guid.NewGuid().ToString()}",
                UserCode     = existingUserCode,
                ClientId     = deviceCodeData.ClientId,
                SubjectId    = deviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = deviceCodeData.CreationTime,
                Expiration   = deviceCodeData.CreationTime.AddSeconds(deviceCodeData.Lifetime),
                Data         = serializer.Serialize(deviceCodeData)
            });
            context.SaveChanges();
        }

        using (var context = new PersistedGrantDbContext(options))
        {
            var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), FakeLogger <DeviceFlowStore> .Create(), new NoneCancellationTokenProvider());

            // skip odd behaviour of in-memory provider
            if (options.Extensions.All(x => x.GetType() != typeof(InMemoryOptionsExtension)))
            {
                await Assert.ThrowsAsync <DbUpdateException>(() =>
                                                             store.StoreDeviceAuthorizationAsync($"device_{Guid.NewGuid().ToString()}", existingUserCode, deviceCodeData));
            }
        }
    }
Пример #17
0
        public async Task StoreDeviceAuthorizationAsync_WhenUserCodeAlreadyExists_ExpectException()
        {
            var existingUserCode = $"user_{Guid.NewGuid().ToString()}";
            var deviceCodeData   = new DeviceCode
            {
                ClientId        = "device_flow",
                RequestedScopes = new[] { "openid", "api1" },
                CreationTime    = new DateTime(2018, 10, 19, 16, 14, 29),
                Lifetime        = 300,
                IsOpenId        = true,
                Subject         = new ClaimsPrincipal(new ClaimsIdentity(
                                                          new List <Claim> {
                    new Claim(JwtClaimTypes.Subject, $"sub_{Guid.NewGuid().ToString()}")
                }))
            };


            var entity = new Storage.Entities.DeviceFlowCodes
            {
                DeviceCode   = $"device_{Guid.NewGuid().ToString()}",
                UserCode     = existingUserCode,
                ClientId     = deviceCodeData.ClientId,
                SubjectId    = deviceCodeData.Subject.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = deviceCodeData.CreationTime,
                Expiration   = deviceCodeData.CreationTime.AddSeconds(deviceCodeData.Lifetime),
                Data         = serializer.Serialize(deviceCodeData)
            };

            g.operationalDb.Insert(entity).ExecuteAffrows();


            var store = new DeviceFlowStore(g.operationalDb, new PersistentGrantSerializer(), FakeLogger <DeviceFlowStore> .Create());


            await Assert.ThrowsAsync <Exception>(() =>
                                                 store.StoreDeviceAuthorizationAsync($"device_{Guid.NewGuid().ToString()}", existingUserCode, deviceCodeData));
        }