Пример #1
0
        private async Task <TicketResult> RemoveAsync(AuthenticationTokenReceiveContext context)
        {
            TicketResult result = new TicketResult();

            StoreKeyFunc = StoreKeyFunc ?? ((ctx, token) => token);
            string key = StoreKeyFunc(context.Ticket, context.Token);


            IDatabase database = _redis.GetDatabase(_configuration.Db);

            byte[] ticket = await database.StringGetAsync(key);

            if (ticket != null)
            {
                TicketSerializer serializer = new TicketSerializer();
                result.Ticket  = serializer.Deserialize(ticket);
                result.Deleted = await database.KeyDeleteAsync(key);
            }
            else
            {
                await database.KeyDeleteAsync(context.Token);
            }

            return(result);
        }
Пример #2
0
        public void NewSerializerCanReadInteropTicket()
        {
            var identity = new ClaimsIdentity("scheme");
            identity.AddClaim(new Claim("Test", "Value"));

            var expires = DateTime.Today;
            var issued = new DateTime(1979, 11, 11);
            var properties = new Owin.Security.AuthenticationProperties();
            properties.IsPersistent = true;
            properties.RedirectUri = "/redirect";
            properties.Dictionary["key"] = "value";
            properties.ExpiresUtc = expires;
            properties.IssuedUtc = issued;

            var interopTicket = new Owin.Security.AuthenticationTicket(identity, properties);
            var interopSerializer = new AspNetTicketSerializer();

            var bytes = interopSerializer.Serialize(interopTicket);

            var newSerializer = new TicketSerializer();
            var newTicket = newSerializer.Deserialize(bytes);

            Assert.NotNull(newTicket);
            Assert.Equal(1, newTicket.Principal.Identities.Count());
            var newIdentity = newTicket.Principal.Identity as ClaimsIdentity;
            Assert.NotNull(newIdentity);
            Assert.Equal("scheme", newIdentity.AuthenticationType);
            Assert.True(newIdentity.HasClaim(c => c.Type == "Test" && c.Value == "Value"));
            Assert.NotNull(newTicket.Properties);
            Assert.True(newTicket.Properties.IsPersistent);
            Assert.Equal("/redirect", newTicket.Properties.RedirectUri);
            Assert.Equal("value", newTicket.Properties.Items["key"]);
            Assert.Equal(expires, newTicket.Properties.ExpiresUtc);
            Assert.Equal(issued, newTicket.Properties.IssuedUtc);
        }
        public AuthenticationTicket Unprotect(string text)
        {
            var protectedData = Encoding.UTF8.GetBytes(text);
            var ticket        = serializer.Deserialize(protectedData);

            return(ticket);
        }
        public AuthenticateResult Authenticate(HttpContextBase contextBase)
        {
            if (!contextBase.Request.Browser.Cookies)
            {
                logger.LogWarning("This browser doesnot support cookies, so cookie based authentication is disabled");
                return(AuthenticateResult.NoResult());
            }

            var authCookie = contextBase.Request.Cookies.Get(AuthConstants.AUTH_COOKIE_NM);

            if (authCookie != null)
            {
                try
                {
                    var unprotectedCookieBytes = dataProtector.UnProtect(Convert.FromBase64String(authCookie.Value));
                    var ticket = serializer.Deserialize(unprotectedCookieBytes);
                    logger.LogDebug("Cookie authentication succeeded");
                    return(AuthenticateResult.Success(ticket));
                }
                catch (Exception)
                {
                    return(AuthenticateResult.Fail($"Unable to extract cookie '{AuthConstants.AUTH_COOKIE_NM}', cookie might be damaged/modified"));
                }
            }

            logger.LogDebug("Cookie authentication failed");
            return(AuthenticateResult.NoResult());
        }
Пример #5
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var    db   = context.OwinContext.Get <ApplicationDbContext>();
            string hash = GetStringSha256Hash(context.Token);

            RefreshToken foundToken = db.RefreshTokens.Where(t =>
                                                             t.TokenHash == hash &&
                                                             t.ExpiresAtUtc > DateTime.UtcNow &&
                                                             !t.Revoked
                                                             ).FirstOrDefault();

            //RefreshToken foundToken = tokens.Where(t =>
            //    t.TokenHash == hash &&
            //    t.ExpiresAtUtc > DateTime.UtcNow &&
            //    !t.Revoked
            //).FirstOrDefault();

            if (foundToken != null)
            {
                byte[] serializedTicket = Convert.FromBase64String(
                    ServerUtils.StringCipher.Decrypt(
                        foundToken.EncryptedTicket,
                        context.Token));
                TicketSerializer     serializer = new TicketSerializer();
                AuthenticationTicket ticket     = serializer.Deserialize(serializedTicket);

                context.SetTicket(ticket);
            }
        }
Пример #6
0
        public T Unprotect(string protectedText, string purpose)
        {
            TicketSerializer _serializer = new TicketSerializer();

            byte[] bytes = Convert.FromBase64String(protectedText);
            return(_serializer.Deserialize(bytes) as T);
        }
Пример #7
0
        public AuthenticationTicket Unprotect(string text)
        {
            var protectedData = Convert.FromBase64String(text);
            var ticket        = serializer.Deserialize(protectedData);

            return(ticket);
        }
Пример #8
0
        T ISecureDataFormat <T> .Unprotect(string protectedText)
        {
            TicketSerializer _serializer = new TicketSerializer();

            byte[] bytes = Convert.FromBase64String(protectedText);
            return(_serializer.Deserialize(bytes) as T);
        }
Пример #9
0
        public AuthenticationTicket Unprotect(string text)
        {
            var protectedData = _encoder.Decode(text);
            var ticketData    = _protector.Unprotect(protectedData);
            var ticket        = _serializer.Deserialize(ticketData);

            return(ticket);
        }
Пример #10
0
        public async Task <AuthenticationTicket> RetrieveAsync(string key)
        {
            var session = await _sessionStorage.GetAsync(key);

            if (session == default(Session))
            {
                return(default(AuthenticationTicket));
            }

            var ticket = _ticketSerializer.Deserialize(session.SerializedTicket);

            return(ticket);
        }
Пример #11
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var entities     = new ApplicationDbContext();
            var repo         = new ApplicationRepository(entities);
            var hashedToken  = GetHash(context.Token);
            var refreshToken = await repo.RefreshTokens.GetByIdAsync(hashedToken);

            if (refreshToken != null)
            {
                //Get protectedTicket from refreshToken class
                //context.DeserializeTicket(refreshToken.ProtectedTicket);
                TicketSerializer serializer = new TicketSerializer();
                context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(refreshToken.ProtectedTicket)));
                //await repo.RefreshTokens.DeleteAndSaveAsync(hashedToken);
            }
        }
Пример #12
0
        private TicketResult Remove(AuthenticationTokenReceiveContext context)
        {
            TicketResult result = new TicketResult();

            RedisKeyGenerator = RedisKeyGenerator ?? ((ctx, token) => token);
            string key = RedisKeyGenerator(context.Ticket, context.Token);

            byte[] ticket = Db.StringGet(key);


            if (ticket.Length > default(int))
            {
                TicketSerializer serializer = new TicketSerializer();
                result.Ticket  = serializer.Deserialize(ticket);
                result.Deleted = Db.KeyDelete(key);
            }

            return(result);
        }
        public static IEnumerable <Claim> Decode(string encodedValue)
        {
            if (string.IsNullOrEmpty(encodedValue))
            {
                return(Enumerable.Empty <Claim>());
            }

            var serializer = new TicketSerializer();

            try
            {
                var ticket = serializer.Deserialize(Convert.FromBase64String(encodedValue));

                return(ticket.Principal.Claims);
            }
            catch (Exception)
            {
                return(Enumerable.Empty <Claim>());
            }
        }
Пример #14
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            string clientId = context.OwinContext.Get <string>("as:client_id");
            string ticket   = refreshTokenService.GetAuthenticationTicket(new Guid(context.Token), clientId);

            if (!string.IsNullOrEmpty(ticket) && !string.IsNullOrWhiteSpace(ticket))
            {
                context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(ticket)));

                var command = new ReduceRefreshTokenTTL()
                {
                    ClientId             = clientId,
                    RefreshToken         = Guid.Parse(context.Token),
                    AuthenticationTicket = ticket,
                    TTL = ttlChange
                };

                this.commandBus.Send(command);
            }
        }
Пример #15
0
        private TicketResult Remove(AuthenticationTokenReceiveContext context)
        {
            TicketResult result = new TicketResult();

            StoreKeyFunc = StoreKeyFunc ?? ((ctx, token) => token);
            string key = StoreKeyFunc(context.Ticket, context.Token);

            IDatabase database = _redis.GetDatabase(_configuration.Db);

            byte[] ticket = database.StringGet(key);


            if (ticket.Length > default(int))
            {
                TicketSerializer serializer = new TicketSerializer();
                result.Ticket  = serializer.Deserialize(ticket);
                result.Deleted = database.KeyDelete(key);
            }

            return(result);
        }
Пример #16
0
        private async Task <TicketResult> RemoveAsync(AuthenticationTokenReceiveContext context)
        {
            TicketResult result = new TicketResult();

            RedisKeyGenerator = RedisKeyGenerator ?? ((ctx, token) => token);
            string key = RedisKeyGenerator(context.Ticket, context.Token);

            byte[] ticket = await Db.StringGetAsync(key);

            if (ticket != null)
            {
                TicketSerializer serializer = new TicketSerializer();
                result.Ticket  = serializer.Deserialize(ticket);
                result.Deleted = await Db.KeyDeleteAsync(key);
            }
            else
            {
                await Db.KeyDeleteAsync(context.Token);
            }

            return(result);
        }
Пример #17
0
        public void NewSerializerCanReadInteropTicket()
        {
            var identity = new ClaimsIdentity("scheme");

            identity.AddClaim(new Claim("Test", "Value"));

            var expires    = DateTime.Today;
            var issued     = new DateTime(1979, 11, 11);
            var properties = new Owin.Security.AuthenticationProperties();

            properties.IsPersistent      = true;
            properties.RedirectUri       = "/redirect";
            properties.Dictionary["key"] = "value";
            properties.ExpiresUtc        = expires;
            properties.IssuedUtc         = issued;

            var interopTicket     = new Owin.Security.AuthenticationTicket(identity, properties);
            var interopSerializer = new AspNetTicketSerializer();

            var bytes = interopSerializer.Serialize(interopTicket);

            var newSerializer = new TicketSerializer();
            var newTicket     = newSerializer.Deserialize(bytes);

            Assert.NotNull(newTicket);
            Assert.Equal(1, newTicket.Principal.Identities.Count());
            var newIdentity = newTicket.Principal.Identity as ClaimsIdentity;

            Assert.NotNull(newIdentity);
            Assert.Equal("scheme", newIdentity.AuthenticationType);
            Assert.True(newIdentity.HasClaim(c => c.Type == "Test" && c.Value == "Value"));
            Assert.NotNull(newTicket.Properties);
            Assert.True(newTicket.Properties.IsPersistent);
            Assert.Equal("/redirect", newTicket.Properties.RedirectUri);
            Assert.Equal("value", newTicket.Properties.Items["key"]);
            Assert.Equal(expires, newTicket.Properties.ExpiresUtc);
            Assert.Equal(issued, newTicket.Properties.IssuedUtc);
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>(OwinContextKeys.CLIENT_ALLOWED_ORIGIN);

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            string hashedTokenId = HashGenerator.GetHash(context.Token);

            ApplicationDbContext   appDbContext           = context.OwinContext.Get <ApplicationDbContext>();
            ApplicationUserManager applicationUserManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            AuthRepository         _repo = new AuthRepository(appDbContext, applicationUserManager);
            var refreshToken             = await _repo.FindRefreshToken(hashedTokenId);

            if (refreshToken != null)
            {
                //Get protectedTicket from refreshToken class
                //context.DeserializeTicket(refreshToken.ProtectedTicket);
                TicketSerializer serializer = new TicketSerializer();
                context.SetTicket(serializer.Deserialize(Encoding.Default.GetBytes(refreshToken.ProtectedTicket)));

                var result = await _repo.RemoveRefreshToken(hashedTokenId);
            }
        }
Пример #19
0
        public async Task <AuthenticationTicket> RetrieveAsync(string key)
        {
            var buffer = await _cache.GetAsync(key);

            return(_ts.Deserialize(buffer));
        }
        /// <summary>(インスタンス化不要な直接的な)参照</summary>
        /// <param name="key">string</param>
        /// <returns>AuthenticationTicket</returns>
        /// <remarks>OAuth 2.0 Token Introspectionのサポートのために必要</remarks>
        public static AuthenticationTicket ReferDirectly(string key)
        {
            AuthenticationTicket ticket = null;

            if (ASPNETIdentityConfig.EnableRefreshToken)
            {
                // EnableRefreshToken == true

                TicketSerializer serializer = new TicketSerializer();

                IEnumerable <byte[]> values = null;
                List <byte[]>        list   = null;

                switch (ASPNETIdentityConfig.UserStoreType)
                {
                case EnumUserStoreType.Memory:
                    RefreshTokenProvider.RefreshTokens.TryGetValue(key, out ticket);
                    break;

                case EnumUserStoreType.SqlServer:
                case EnumUserStoreType.ODPManagedDriver:
                case EnumUserStoreType.PostgreSQL:     // DMBMS

                    using (IDbConnection cnn = DataAccess.CreateConnection())
                    {
                        cnn.Open();

                        switch (ASPNETIdentityConfig.UserStoreType)
                        {
                        case EnumUserStoreType.SqlServer:

                            values = cnn.Query <byte[]>(
                                "SELECT [Value] FROM [RefreshTokenDictionary] WHERE [Key] = @Key", new { Key = key });

                            list = values.AsList();
                            if (list.Count != 0)
                            {
                                ticket = serializer.Deserialize(values.AsList()[0]);
                            }

                            break;

                        case EnumUserStoreType.ODPManagedDriver:

                            values = cnn.Query <byte[]>(
                                "SELECT \"Value\" FROM \"RefreshTokenDictionary\" WHERE \"Key\" = :Key", new { Key = key });

                            list = values.AsList();
                            if (list.Count != 0)
                            {
                                ticket = serializer.Deserialize(values.AsList()[0]);
                            }

                            break;

                        case EnumUserStoreType.PostgreSQL:

                            values = cnn.Query <byte[]>(
                                "SELECT \"value\" FROM \"refreshtokendictionary\" WHERE \"key\" = @Key", new { Key = key });

                            list = values.AsList();
                            if (list.Count != 0)
                            {
                                ticket = serializer.Deserialize(values.AsList()[0]);
                            }

                            break;
                        }
                    }

                    break;
                }
            }
            else
            {
                // EnableRefreshToken == false
            }

            return(ticket);
        }
        /// <summary>ReceiveRefreshToken</summary>
        /// <param name="context">AuthenticationTokenReceiveContext</param>
        private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
        {
            //context.DeserializeTicket(context.Token);

            // --------------------------------------------------

            if (ASPNETIdentityConfig.EnableRefreshToken)
            {
                // EnableRefreshToken == true

                AuthenticationTicket ticket;
                TicketSerializer     serializer = new TicketSerializer();

                IEnumerable <byte[]> values = null;
                List <byte[]>        list   = null;

                switch (ASPNETIdentityConfig.UserStoreType)
                {
                case EnumUserStoreType.Memory:
                    if (RefreshTokenProvider.RefreshTokens.TryRemove(context.Token, out ticket))
                    {
                        context.SetTicket(ticket);
                    }
                    break;

                case EnumUserStoreType.SqlServer:
                case EnumUserStoreType.ODPManagedDriver:
                case EnumUserStoreType.PostgreSQL:     // DMBMS

                    using (IDbConnection cnn = DataAccess.CreateConnection())
                    {
                        cnn.Open();

                        switch (ASPNETIdentityConfig.UserStoreType)
                        {
                        case EnumUserStoreType.SqlServer:

                            values = cnn.Query <byte[]>(
                                "SELECT [Value] FROM [RefreshTokenDictionary] WHERE [Key] = @Key", new { Key = context.Token });

                            list = values.AsList();
                            if (list.Count != 0)
                            {
                                ticket = serializer.Deserialize(values.AsList()[0]);
                                context.SetTicket(ticket);

                                cnn.Execute(
                                    "DELETE FROM [RefreshTokenDictionary] WHERE [Key] = @Key", new { Key = context.Token });
                            }

                            break;

                        case EnumUserStoreType.ODPManagedDriver:

                            values = cnn.Query <byte[]>(
                                "SELECT \"Value\" FROM \"RefreshTokenDictionary\" WHERE \"Key\" = :Key", new { Key = context.Token });

                            list = values.AsList();
                            if (list.Count != 0)
                            {
                                ticket = serializer.Deserialize(values.AsList()[0]);
                                context.SetTicket(ticket);

                                cnn.Execute(
                                    "DELETE FROM \"RefreshTokenDictionary\" WHERE \"Key\" = :Key", new { Key = context.Token });
                            }

                            break;

                        case EnumUserStoreType.PostgreSQL:

                            values = cnn.Query <byte[]>(
                                "SELECT \"value\" FROM \"refreshtokendictionary\" WHERE \"key\" = @Key", new { Key = context.Token });

                            list = values.AsList();
                            if (list.Count != 0)
                            {
                                ticket = serializer.Deserialize(values.AsList()[0]);
                                context.SetTicket(ticket);

                                cnn.Execute(
                                    "DELETE FROM \"refreshtokendictionary\" WHERE \"key\" = @Key", new { Key = context.Token });
                            }

                            break;
                        }
                    }

                    break;
                }
            }
            else
            {
                // EnableRefreshToken == false
            }
        }
        private TicketResult Remove(AuthenticationTokenReceiveContext context)
        {
            TicketResult result = new TicketResult();

            StoreKeyFunc = StoreKeyFunc ?? ((ctx, token) => token);
            string key = StoreKeyFunc(context.Ticket, context.Token);

            IDatabase database = _redis.GetDatabase(_configuration.Db);
            byte[] ticket = database.StringGet(key);


            if (ticket.Length > default(int))
            {
                TicketSerializer serializer = new TicketSerializer();
                result.Ticket = serializer.Deserialize(ticket);
                result.Deleted = database.KeyDelete(key);
            }

            return result;
        }
        private async Task<TicketResult> RemoveAsync(AuthenticationTokenReceiveContext context)
        {
            TicketResult result = new TicketResult();

            StoreKeyFunc = StoreKeyFunc ?? ((ctx, token) => token);
            string key = StoreKeyFunc(context.Ticket, context.Token);


            IDatabase database = _redis.GetDatabase(_configuration.Db);
            byte[] ticket = await database.StringGetAsync(key);

            if (ticket != null)
            {
                TicketSerializer serializer = new TicketSerializer();
                result.Ticket = serializer.Deserialize(ticket);
                result.Deleted = await database.KeyDeleteAsync(key);
            }
            else
            {
                await database.KeyDeleteAsync(context.Token);
            }

            return result;
        }
Пример #24
0
        public async Task <AuthenticationTicket> RetrieveAsync(string key)
        {
            byte[] ticket = await _cache.GetAsync(key);

            return(_ticketSerializer.Deserialize(ticket));
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            // define o cabecalho da resposta do contexto do Owin com a permição de origem
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {allowedOrigin});

            // pega o Id do token pelo na requisição
            var hashedTokenId = HashHelper.GetHash(context.Token);

            // Identifica o Browser
            var userAgent = HttpContext.Current.Request.UserAgent;
            var userBrowser = new HttpBrowserCapabilities {Capabilities = new Hashtable {{string.Empty, userAgent}}};
            var factory = new BrowserCapabilitiesFactory();
            factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
            var browser = userBrowser.Browser;

            var refreshTokenDomain = new RefreshTokenDomain();

            // busca o token na base de dados pelo id
            var refreshToken = await refreshTokenDomain.ReadAsync(hashedTokenId, browser);

            // se o token for encontrado
            if (refreshToken != null)
            {
                // pega os dados do ticket para deserializar e gerar um novo ticket com 
                // as informações mapeadas do usuário que utiliza este token
                var ticketSerializer = new TicketSerializer();
                var ticket = ticketSerializer.Deserialize(refreshToken.ProtectedTicket);

                context.SetTicket(ticket);

                // remove o token da base de dados pois em nossa lógica, permitimos apenas 
                // um RefreshToken por usuário e aplicação cliente
                await refreshTokenDomain.DeleteAsync(hashedTokenId, browser);
            }
        }