Esempio n. 1
0
        public async Task <string> GenerateAsync(string purpose, UserManager <TUser, long> manager, TUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            using (var ms = new MemoryStream())
            {
                using (var binaryWriter = ms.CreateWriter())
                {
                    binaryWriter.Write(DateTimeOffset.UtcNow);
                    binaryWriter.Write(Convert.ToString((object)user.Id, (IFormatProvider)CultureInfo.InvariantCulture));
                    binaryWriter.Write(purpose ?? "");

                    if (manager.SupportsUserSecurityStamp)
                    {
                        binaryWriter.Write(await manager.GetSecurityStampAsync(user.Id));
                    }
                    else
                    {
                        binaryWriter.Write("");
                    }
                }

                return(Convert.ToBase64String(Protector.Protect(ms.ToArray())));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Generates a protected token for the specified <paramref name="user"/> as an asynchronous operation.
        /// </summary>
        /// <param name="purpose">The purpose the token will be used for.</param>
        /// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve user properties from.</param>
        /// <param name="user">The <see cref="TUser"/> the token will be generated from.</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the generated token.</returns>
        public virtual async Task <string> GenerateAsync(string purpose, UserManager <TUser> manager, TUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            var ms     = new MemoryStream();
            var userId = await manager.GetUserIdAsync(user);

            using (var writer = ms.CreateWriter())
            {
                writer.Write(DateTimeOffset.UtcNow);
                writer.Write(userId);
                writer.Write(purpose ?? "");
                string stamp = null;
                if (manager.SupportsUserSecurityStamp)
                {
                    stamp = await manager.GetSecurityStampAsync(user);
                }
                writer.Write(stamp ?? "");
            }
            var protectedBytes = Protector.Protect(ms.ToArray());

            return(Convert.ToBase64String(protectedBytes));
        }
        /// <summary>
        /// Generates a protected token for the specified resourceId.
        /// </summary>
        /// <param name="purpose">The purpose for which the token will be used. A user-specified string that you can use to differentiate token use cases. </param>
        /// <param name="resourceId">The resource Id to which the token corresponds.</param>
        /// <param name="securityStamp">The security stamp to use in generating the token.</param>
        /// <returns></returns>
        public virtual string Generate(string purpose, string resourceId, string securityStamp)
        {
            if (purpose == null)
            {
                throw new ArgumentNullException(nameof(purpose));
            }
            if (resourceId == null)
            {
                throw new ArgumentNullException(nameof(resourceId));
            }
            if (securityStamp == null)
            {
                throw new ArgumentNullException(nameof(securityStamp));
            }

            var ms = new MemoryStream();

            using (var writer = ms.CreateWriter())
            {
                writer.Write(DateTimeOffset.UtcNow);
                writer.Write(resourceId);
                writer.Write(purpose);
                writer.Write(securityStamp);
            }
            var protectedBytes = Protector.Protect(ms.ToArray());

            return(Convert.ToBase64String(protectedBytes));
        }
Esempio n. 4
0
        /// <summary>
        /// Generates a protected token for the specified <paramref name="user"/> as an asynchronous operation.
        /// </summary>
        /// <param name="purpose">The purpose the token will be used for.</param>
        /// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve user properties from.</param>
        /// <param name="user">The <typeparamref name="TUser"/> the token will be generated from.</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the generated token.</returns>
        public virtual async Task <string> GenerateAsync(string purpose, UserManager <TUser> manager, TUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            var ms     = new MemoryStream();
            var userId = await manager.GetUserIdAsync(user);

            _logger.LogDebug(LoggingEvents.CustomDataProtectorTokenProviderCreate, "Generate token for [purpose:{purpose}] [userId:{userId}] ", purpose, userId);

            using (var writer = ms.CreateWriter())
            {
                writer.Write(DateTimeOffset.UtcNow);
                writer.Write(userId);
                writer.Write(purpose ?? "");
                string stamp = null;
                if (manager.SupportsUserSecurityStamp)
                {
                    stamp = await manager.GetSecurityStampAsync(user);

                    if (stamp == null)
                    {
                        await manager.UpdateSecurityStampAsync(user);

                        stamp = await manager.GetSecurityStampAsync(user);
                    }
                }
                writer.Write(stamp ?? "");
            }
            var protectedBytes = Protector.Protect(ms.ToArray());

            return(Convert.ToBase64String(protectedBytes));
        }
Esempio n. 5
0
        /// <summary>
        ///     Generate a protected string for a user
        /// </summary>
        /// <param name="purpose"></param>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <string> GenerateAsync(string purpose, UserManager <TUser, TKey> manager, TUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            var ms = new MemoryStream();

            using (var writer = ms.CreateWriter())
            {
                writer.Write(DateTimeOffset.UtcNow);
                writer.Write(Convert.ToString(user.Id));
                writer.Write(purpose ?? "");
                string stamp = null;
                if (manager.SupportsUserSecurityStamp)
                {
                    stamp = await manager.GetSecurityStampAsync(user.Id);
                }
                writer.Write(stamp ?? "");
            }
            var protectedBytes = Protector.Protect(ms.ToArray());
            var token          = Convert.ToBase64String(protectedBytes, Base64FormattingOptions.None);

            return(Base64ToNormalString(token));
        }
        public byte[] Protect(byte[] plaintext)
        {
            // Validate the parameters before attempting to use them.
            Guard.Instance().ThrowIfNull(plaintext, nameof(plaintext));

            // Defer to the local protector.
            return(Protector.Protect(plaintext));
        }
Esempio n. 7
0
        public async Task <string> GenerateAsync(string purpose, UserManager <AppUser> manager, AppUser user)
        {
            var token = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new RefreshToken {
                Expiry        = DateTime.UtcNow.AddMinutes(Options.RefreshExpiryHours),
                SecurityStamp = await manager.GetSecurityStampAsync(user)
            }));

            return(Convert.ToBase64String(Protector.Protect(token)));
        }
Esempio n. 8
0
        protected override async Task SaveItem(PostBuildData item)
        {
            Post post = item.Raw;

            if (item.Key != null && Protector != null)
            {
                post = await Protector.Protect(item.Raw, item.Key);
            }
            await BaseRepositoryBuilder.SaveToFile(Path.Join(Dist.FullName, $"{item.Raw.Id}.json"), post);
        }
Esempio n. 9
0
        /// <summary>
        /// store <paramref name="sets"/> in AppData as protected json
        /// </summary>
        public void Write()
        {
            var s          = JsonConvert.SerializeObject(this);
            var sProtected = Protector.Protect(s);

            if (!Directory.Exists(AppDataDir))
            {
                Directory.CreateDirectory(AppDataDir);
            }

            File.WriteAllText(ProtectedFileFullPath, sProtected);
        }
Esempio n. 10
0
        public async Task <LinkResult> CreateLink(string email)
        {
            var user = await Db.Users.FirstOrDefaultAsync(x => x.Email == email.ToString());

            if (user != null)
            {
                var result = new LinkResult(user.Id, guid => Protector.Protect($"{user.Id},{guid}"));
                Cache.Set(result.Unique, result.UserId, DateTimeOffset.Now.AddMinutes(2));

                return(result);
            }
            else
            {
                throw new ArgumentException($"Argument: ${nameof(email)} is not valid");
            }
        }
Esempio n. 11
0
        public ProtectionTester()
        {
            var serverEndpoint = new IPEndPoint(IPAddress.Loopback, 12000);

            using var server = new SocketServer(serverEndpoint);

            var connected = SocketMessenger.CreateAndConnect(serverEndpoint);

            var socket1 = server.Accept().Result.Value;
            var socket2 = connected.Result;

            var a = Protector.Protect(socket1, false);
            var b = Protector.Protect(socket2, true);

            protected1 = a.Result;
            protected2 = b.Result;
        }
Esempio n. 12
0
        public override async Task <Post?> Get(string id, CancellationToken cancellationToken = default)
        {
            using var fs = await(await FileProvider.GetFileInfo(GetPath(id))).CreateReadStream();
            using var sr = new StreamReader(fs);
            var src = await sr.ReadToEndAsync();

            var(metadata, content) = ObjectTextual.Parse <PostMetadata>(src);

            if (string.IsNullOrEmpty(metadata.id))
            {
                metadata.id = id;
            }
            if (string.IsNullOrEmpty(metadata.creationTime))
            {
                metadata.creationTime = File.GetCreationTime(GetAbsolutePath(id)).ToString();
            }
            if (string.IsNullOrEmpty(metadata.modificationTime))
            {
                metadata.modificationTime = File.GetLastWriteTime(GetAbsolutePath(id)).ToString();
            }
            if (metadata.category.Length == 0)
            {
                var path  = Path.GetDirectoryName(id)?.Replace("\\", "/");
                var items = path?.Split("/", StringSplitOptions.RemoveEmptyEntries);
                metadata.category = items ?? Array.Empty <string>();
            }

            Post result = new Post();

            metadata.ApplyTo(result);
            result.Content = new Document
            {
                Raw = content
            };

            if (!string.IsNullOrEmpty(metadata.password))
            {
                result.Content = await Protector.Protect(result.Content, new ProtectionKey
                {
                    Password = metadata.password
                });
            }

            return(result);
        }
        public string Generate(string purpose, int userId)
        {
            var ms = new MemoryStream();

            using (var writer = new BinaryWriter(ms, DefaultEncoding, true))
            {
                writer.Write(DateTimeOffset.UtcNow.UtcTicks);
                writer.Write(Convert.ToString(userId, CultureInfo.InvariantCulture));
                writer.Write(purpose ?? "");
                string stamp = null;
                //TODO
                //if (manager.SupportsUserSecurityStamp)
                //{
                //    stamp = await manager.GetSecurityStampAsync(user.Id).WithCurrentCulture();
                //}
                writer.Write(stamp ?? "");
            }
            var protectedBytes = Protector.Protect(ms.ToArray());

            return(Convert.ToBase64String(protectedBytes));
        }
Esempio n. 14
0
        public async Task <IActionResult> MagicLink(string email)
        {
            if (await Db.Users.AnyAsync(x => x.Email == email))
            {
                var data  = Protector.Protect(email);
                var magic = $"{Program.URL}login/{data}";

                Cache.Remove(email);
                Cache.GetOrCreate(email, entry => data);

                return(Ok(new
                {
                    MagicLink = magic
                }));
            }
            else
            {
                return(NotFound(new
                {
                    Message = "Email not found"
                }));
            }
        }
        public static async Task LoadAsync(IRESTClient client, string url)
        {
            string response = await client.Request(url);

            ProtectedJson = await Protector.Protect(response);
        }