return json hix / mod_harbour

mod_harbour es un módulo para Apache que permite correr tus PRGs directamente en la web!!!
russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Existe en HIX o mod_harbour .... implementación para "Interceptor"... útil para la reception o descarga del token JWT, de forma desatendida...
que el server sea quien en cada solicitud que llegue, permita acceder a los datos enviados... anexo un ejemplo con nodejs..

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...');
const now = Date.now();
return next.handle().pipe(
tap(() => console.log(After... ${Date.now() - now}ms))
);
}
}

//******************************************************

const jwt = require('jsonwebtoken');

const authInterceptor = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Unauthorized');

try {
const decoded = jwt.verify(token, 'secret_key');
req.user = decoded;
next();
} catch (error) {
return res.status(401).send('Invalid token');
}
};

module.exports = authInterceptor;

Last edited by russimicro on Thu Feb 05, 2026 3:14 pm, edited 1 time in total.
russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Otto... en mod_harbour.... las funciones para jwt funcionaron .. solo debes renombrar los metodos que ya existen en mod_harbour

cJWT := _jwt_encode( hHeader, hPayload, cSecret )

? "Generated JWT:"
? cJWT
? ""

hResult := _jwt_verify( cJWT, cSecret, { "iss"=>"harbour-test" } )

Y en hix.. no existe este metodo : HB_BPOKE()

User avatar
Otto
Posts: 7020
Joined: Fri Oct 07, 2005 7:07 pm
Has thanked: 100 times
Been thanked: 91 times
Contact:

Re: return json hix / mod_harbour

Post by Otto »

In mod_harbour there isn’t a first-class concept called an interceptor like in NestJS, but the mechanism already exists implicitly.

In Harbour-based web solutions, the request entry point (Main() or a shared request handler) effectively is the interceptor. Anything you place at the beginning of that flow runs for every request, before any business logic is executed.

I’m fairly sure that a similar mechanism already exists internally in HIX. In mod_harbour, however, this can be implemented very explicitly and transparently by the developer.

A typical pattern would be:
read the Authorization header,
verify the JWT (signature + expiration),
attach the decoded payload to a request context,
and only then continue with the application logic.

In fact, the small JWT test function we discussed already contains most of what an interceptor needs. For many use cases, checking the signature and the exp claim is sufficient; everything else (roles, scopes, permissions) is policy on top of that.

So while there is no declarative “interceptor” keyword, the functionality is absolutely achievable — and in mod_harbour it can be done in a very controlled, explicit way.
Best regards,

Otto

russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Otto.. efectivamente una manera de leerlo manualmente, es implementar un método en todos los main(), que lea el header,,, e implemente el control del token,,, pero por seguridad del server, seria más práctico y seguro que ningún usuario implemente un .prg y pueda violentar la seguridad... mientras sea el servidor quien lance un servicio de lectura de todo request.. y que ejecute el método de validación que suministre el lanzador del server...

User avatar
Otto
Posts: 7020
Joined: Fri Oct 07, 2005 7:07 pm
Has thanked: 100 times
Been thanked: 91 times
Contact:

Re: return json hix / mod_harbour

Post by Otto »

Jsonsson,
Yes, that’s precisely where the real risk lies. If the server itself is publicly accessible and also issues JWTs, an attacker could attempt to obtain valid tokens through these interfaces. JWT only provides security when there is a clear separation between who is authorized to issue tokens and who is only responsible for validating them. Without this separation, JWT can become an attack vector rather than a security mechanism.

That’s why we deliberately use a dedicated proxy. Authentication and token generation are handled exclusively by the proxy, while the Harbour backend remains inaccessible from the internet and never issues tokens itself. This keeps the attack surface minimal and ensures clear responsibility.

Best regards,
Otto

User avatar
Otto
Posts: 7020
Joined: Fri Oct 07, 2005 7:07 pm
Has thanked: 100 times
Been thanked: 91 times
Contact:

Re: return json hix / mod_harbour

Post by Otto »

I think there is an important ordering issue here that is easy to overlook.
Authentication must always happen before a JWT is issued.

If a token is generated without a prior, successful authentication step, the whole mechanism becomes unsafe, because an attacker could potentially obtain valid tokens on their own. The correct flow is always: first authenticate the user (for example via credentials, API key, certificate, etc.), and only if that succeeds issue a JWT.

Your current proxy/JWT approach is conceptually correct, but it is crucial that the proxy enforces authentication before creating any token. Once CORS is enabled and an API is publicly reachable, virtually anyone can send requests to it. In that case, a proxy or a similar gateway layer is not optional but necessary, to ensure that unauthenticated requests never reach the token-issuing logic or the backend services.

russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Otto..

Efectivamente la generación del token la hago en el login.. previa autenticación...

y en los request el interceptor del server web ... valida y refresca el token según vencimientos( corto y largo)

Last edited by russimicro on Thu Feb 05, 2026 7:56 pm, edited 2 times in total.
User avatar
Otto
Posts: 7020
Joined: Fri Oct 07, 2005 7:07 pm
Has thanked: 100 times
Been thanked: 91 times
Contact:

Re: return json hix / mod_harbour

Post by Otto »

Thanks for the clarification. Conceptually, that is exactly the correct order: authenticate first, then issue the token, and validate it on every request.

What I’m currently missing, though, is where this is enforced centrally in the server flow. From what I can see, the logic for validating and refreshing the token does not appear to be implemented as a mandatory, global server-level step, but rather as application-level code.

That distinction matters, because if the interceptor is not guaranteed to run before every request, or if it can be bypassed by a PRG that does not include it, then the protection becomes optional rather than enforced.

So my question is not whether the idea is correct – it clearly is – but where exactly in the server request lifecycle this validation is hooked in, and how it is ensured that all requests go through it.

russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Otto..

el interceptor de server web es el que se asegura de descargar el token y hacer validación... como también el frontend... se encarga de anexar en cada petición : Header("Authorization") , con los datos del token... todo esto mediate un escuchador.

De esta forma cualquier petición, solo se aceptará si el server hizo previa evaluación y ejecuto método de validación y refresco del token (método suministrado por nosotros que el servidor lanza en su arranque)

Asi no hay forma de evitar él envió ni tampoco de recibir el token... en términos de usuario final : AUTOMATICO

Aqui copilot plante una solución para mod_habour :

👌. En mod_harbour no existe el concepto de interceptor como en Node.js/Express o NestJS, así que no puedes enganchar un middleware global que se ejecute antes de cada endpoint. Para evitar que el servidor tenga que “leer y validar” el JWT en todas las peticiones normales

"Si tu arquitectura crece, puedes poner un reverse proxy (NGINX, Apache) que filtre cabeceras y tokens antes de llegar a mod_harbour. Así mod_harbour solo recibe tráfico ya autenticado."

User avatar
Otto
Posts: 7020
Joined: Fri Oct 07, 2005 7:07 pm
Has thanked: 100 times
Been thanked: 91 times
Contact:

Re: return json hix / mod_harbour

Post by Otto »

Jsonsson, Yes — conceptually we are saying the same thing. The key point is that token validation must be enforced at an architectural level, not just implemented by convention inside individual PRGs, which is why a proxy or gateway layer makes the difference.

russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Otto..

muchas gracias. por ahora voy a realizar validaciones en cada .prg y voy a probar lo del servidor proxy con apache...

Solo faltaría el concepto de Carles para ver este manejo en HIX..

Saludos...

/// mi ambiente de pruebas

if (environment.apiTipoServer == "harbour") {
if( environment.apiServerWeb == "HIX") {
this.parametros = ${environment.apiUrlUserHix}+"/test.prg?"+"login="+username+"&pass="+password+"&emp="+empresa;
} else {
this.parametros = ${environment.apiUrlUser}+"/test.prg?"+"login="+username+"&pass="+password+"&emp="+empresa;
}
} else {
// nodejs
this.parametros = ${environment.apiUrlUser}+"/jsofterp/api/usuarios/login/"+username+"/"+password+"/"+empresa;
}
return this.http.get<any>(this.parametros )
}

russimicro
Posts: 413
Joined: Sun Jan 31, 2010 3:30 pm
Location: Bucaramanga - Colombia
Been thanked: 5 times

Re: return json hix / mod_harbour

Post by russimicro »

Otto : Buena tarde...

Favor analizar esta modificación sugerida para mod_harbour
y explicarnos....

  • Porque se requiere este ajuste
  • Como compilar fuentes de mod_harbour
    ...

viewtopic.php?t=46315

Gracias

Post Reply