public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {

            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

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

            using (AutenticacionRepository _repo = new AutenticacionRepository())
            {
                var refreshToken = await _repo.BuscarRefreshToken(hashedTokenId);

                if (refreshToken != null)
                {
                    //Get protectedTicket from refreshToken class
                    context.DeserializeTicket(refreshToken.TicketProtegido);
                    var result = await _repo.RemoverRefreshToken(hashedTokenId);
                }
            }
        }
        /// <summary>
        /// Método encargado de gestionar la información de tokens
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }
            //Se genera un identificador único para el token
            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (AutenticacionRepository _repo = new AutenticacionRepository())
            {
                var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");

                //Se asignan las propiedades del token
                var token = new RefreshToken()
                {
                    Id = Helper.GetHash(refreshTokenId),
                    ClientId = clientid,
                    Subject = context.Ticket.Identity.Name,
                    FechaEmision = DateTime.UtcNow,
                    FechaExpiracion = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
                };

                context.Ticket.Properties.IssuedUtc = token.FechaEmision;
                context.Ticket.Properties.ExpiresUtc = token.FechaExpiracion;

                token.TicketProtegido = context.SerializeTicket();

                var result = await _repo.AgregarRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }

            }
        }
 /// <summary>
 /// Se inicializa el controlador y los objetos requeridos por el mismo
 /// </summary>
 public AccountController()
 {
     _repositorio = new AutenticacionRepository();
 }
 /// <summary>
 /// Constructor de la clase, inicializa los objetos requeridos
 /// </summary>
 public RefreshTokensController()
 {
     _repositorio = new AutenticacionRepository();
 }
        /// <summary>
        /// Método que valida las credenciales recibidas
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            if (allowedOrigin == null) allowedOrigin = "*";
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            using (AutenticacionRepository _repo = new AutenticacionRepository())
            {
                IdentityUser user = await _repo.BuscarUsuario(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {
                        "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                    },
                    {
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        /// <summary>
        /// Método que valida el cliente
        /// </summary>
        /// <param name="oauthContext"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext oauthContext)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            User client = null;

            if (!oauthContext.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                oauthContext.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (oauthContext.ClientId == null)
            {
                //Remove the comments from the below line oauthContext.SetError, and invalidate oauthContext 
                //if you want to force sending clientId/secrects once obtain access tokens. 
                oauthContext.Validated();
                //oauthContext.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            using (AutenticacionRepository _repo = new AutenticacionRepository())
            {
                client = _repo.BuscarCliente(oauthContext.ClientId);
            }

            //Se valida la existencia del cliente
            if (client == null)
            {
                //Si el cliente no existe, se envía la notificación invalidando la petición
                oauthContext.SetError("invalid_clientId", string.Format("El usuario '{0}' no está refistrado en el sistema", oauthContext.ClientId));
                return Task.FromResult<object>(null);
            }

            //Se valida la aplicación del cliente, si es nativa, se valida la informacióin secreta
            if (client.TipoAplicacion == TiposAplicacion.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    oauthContext.SetError("clientId_requerido", "El usuario debe ser enviado");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    //Se valida que el cliente enviado coincida con el almacenado
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        oauthContext.SetError("clientId_Invalido", "El usuario no es válido");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!client.Activo)
            {
                //Se verifica que el cliente se encuentre activo
                oauthContext.SetError("cliente_inactivo", "El usuario no se encuentra activo");
                return Task.FromResult<object>(null);
            }

            oauthContext.OwinContext.Set<string>("as:clientAllowedOrigin", client.OrigenAdmitido);
            oauthContext.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.TiempoActualizacionToken.ToString());
            //Se valida el contexto si todo se encuentra bien
            oauthContext.Validated();
            return Task.FromResult<object>(null);
        }