Metadata >> aspnetwebstacknightly >> Microsoft.AspNet.Identity.Owin >> 2.0.0-beta1-140128 >> Release Default >> Microsoft.AspNet.Identity.Owin

Microsoft.AspNet.Identity.Owin/DataProtectorTokenProvider.cs

using Microsoft.Owin.Security.DataProtection;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.AspNet.Identity.Owin {
    /// <summary>
    /// Token provider that uses a DataProtector to generate encrypted tokens based off of the security stamp
    /// </summary>
    public class DataProtectorTokenProvider<TUser> : DataProtectorTokenProvider<TUser, string> where TUser : IUser<string> {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="protector"></param>
        public DataProtectorTokenProvider(IDataProtector protector) : base(protector) { }

    }
 
    /// <summary>
    /// Token provider that uses a DataProtector to generate encrypted tokens based off of the security stamp
    /// </summary>
    public class DataProtectorTokenProvider<TUser, TKey> : IUserTokenProvider<TUser, TKey> where TUser : IUser<TKey> where TKey : IEquatable<TKey> {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="protector"></param>
        public DataProtectorTokenProvider(IDataProtector protector) {
            if (protector == null) {
                throw new ArgumentNullException("protector");
            }
            Protector = protector;
            TokenLifespan = TimeSpan.FromDays(1);
        }

        /// <summary>
        /// DataProtector for the token
        /// </summary>
        public IDataProtector Protector { get; private set; }

        /// <summary>
        /// Lifespan after which the token is considered expired
        /// </summary>
        public TimeSpan TokenLifespan { get; set; }

        /// <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");
            }
            MemoryStream ms = new MemoryStream();
            using (var writer = ms.CreateWriter()) {
                writer.Write(DateTimeOffset.UtcNow);
                writer.Write(Convert.ToString(user.Id, CultureInfo.InvariantCulture));
                writer.Write(purpose ?? "");
                string stamp = null;
                if (manager.SupportsUserSecurityStamp)
                {
                    stamp = await manager.GetSecurityStampAsync(user.Id);
                }
                writer.Write(stamp ?? "");
            }
            byte[] protectedBytes = Protector.Protect(ms.ToArray());
            return Convert.ToBase64String(protectedBytes);
        }

        /// <summary>
        /// Return false if the token is not valid
        /// </summary>
        /// <param name="purpose"></param>
        /// <param name="token"></param>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser, TKey> manager, TUser user)
        {
            try {
                byte[] unprotectedData = Protector.Unprotect(Convert.FromBase64String(token));
                MemoryStream ms = new MemoryStream(unprotectedData);
                using (var reader = ms.CreateReader()) {
                    DateTimeOffset creationTime = reader.ReadDateTimeOffset();
                    DateTimeOffset expirationTime = creationTime + TokenLifespan;
                    if (expirationTime < DateTimeOffset.UtcNow) {
                        return false;
                    }

                    string userId = reader.ReadString();
                    if (!userId.Equals(user.Id))
                    {
                        return false;
                    }
                    string purp = reader.ReadString();
                    if (!String.Equals(purp, purpose)) {
                        return false;
                    }
                    string stamp = reader.ReadString();
                    if (reader.PeekChar() != -1)
                    {
                        return false;
                    }

                    if (manager.SupportsUserSecurityStamp)
                    {
                        var expectedStamp = await manager.GetSecurityStampAsync(user.Id).ConfigureAwait(false);
                        return stamp == expectedStamp;
                    }
                    else
                    {
                        return stamp == "";
                    }
                }
            }
            catch { // Do not leak exception
            }
            return false;
        }

        /// <summary>
        /// Returns true if the provider can be used to generate tokens for this user
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<bool> IsValidProviderForUserAsync(UserManager<TUser, TKey> manager, TUser user) {
            return Task.FromResult(true);
        }
    }

    // Based on Levi's authentication sample
    internal static class StreamExtensions {
        internal static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true);

        public static BinaryReader CreateReader(this Stream stream) {
            return new BinaryReader(stream, DefaultEncoding, leaveOpen: true);
        }

        public static BinaryWriter CreateWriter(this Stream stream) {
            return new BinaryWriter(stream, DefaultEncoding, leaveOpen: true);
        }

        public static DateTimeOffset ReadDateTimeOffset(this BinaryReader reader) {
            return new DateTimeOffset(reader.ReadInt64(), TimeSpan.Zero);
        }

        public static void Write(this BinaryWriter writer, DateTimeOffset value) {
            writer.Write(value.UtcTicks);
        }
    }
}

Microsoft.AspNet.Identity.Owin

Depedencies

Name AssemblyVersion Culture PublicKeyToken Type
Microsoft.AspNet.Identity.Core 1.0.0.0 neutral 31bf3856ad364e35 Required
Microsoft.Owin 2.0.2.0 neutral 31bf3856ad364e35 Required
Microsoft.Owin.Security 2.0.2.0 neutral 31bf3856ad364e35 Required
Microsoft.Owin.Security.Cookies 2.0.2.0 neutral 31bf3856ad364e35 Required
Microsoft.Owin.Security.OAuth 2.0.2.0 neutral 31bf3856ad364e35 Required
mscorlib 4.0.0.0 neutral b77a5c561934e089 Required
Owin 1.0.0.0 neutral f0ebd12fd5e55cc5 Required
System.Core 4.0.0.0 neutral b77a5c561934e089 Required

Sources

Path Related
Microsoft.AspNet.Identity.Owin/DataProtectorTokenProvider.cs Source
Microsoft.AspNet.Identity.Owin/Extensions/AppBuilderExtensions.cs Source
Microsoft.AspNet.Identity.Owin/Extensions/AuthenticationManagerExtensions.cs Source
Microsoft.AspNet.Identity.Owin/Extensions/OwinContextExtensions.cs Source
Microsoft.AspNet.Identity.Owin/IdentityFactoryMiddleware.cs Source
Microsoft.AspNet.Identity.Owin/IdentityFactoryProvider.cs Source
Microsoft.AspNet.Identity.Owin/SecurityStampValidator.cs Source