public AccessToken GetAccessToken(AccessRequest accessRequest)
        {
            OrganisationKeySerDes organisationKey = ExtractOrganisationKey(accessRequest.Key);

            if (organisationKey == null)
            {
                throw new ApplicationException("Extract Organisation-Key process returned a null key.");
            }
            CheckKeyIsValid(organisationKey.Name, organisationKey.OKey);

            AuthorisationEntity authorisation = GetAuthorisation(accessRequest.AuthenticationCode);

            if (authorisation == null)
            {
                throw new ApplicationException("Could not find Authorisation entry in the database.");
            }

            AccessEnity access = CreateAccess(authorisation.UserId, accessRequest.Scope,
                                              organisationKey.Name);

            PersistAccess(access);
            DeleteAuthorisation(authorisation);

            AccessToken accessToken = CreateAccessToken(access);

            return(accessToken);
        }
        /*
         * Oraganisation-key is the license key provide to the
         * client, which a encrypted json string containing the
         * username and OKey.
         */
        private OrganisationKeySerDes ExtractOrganisationKey(string encryptedKey)
        {
            string decryptedKey = SymmetricEncryption.Decrypt(encryptedKey);

            if (string.IsNullOrEmpty(decryptedKey))
            {
                throw new ApplicationException("Encrpyted organisation key return an empty value.");
            }

            OrganisationKeySerDes organisationKey = JsonConvert.DeserializeObject <OrganisationKeySerDes>(decryptedKey);

            return(organisationKey);
        }