changeset 6236:031b9f8cf76e

added OrthancPluginRegisterHttpAuthentication() for custom HTTP authentication
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 09 Jul 2025 23:27:19 +0200
parents 33bf50bffbdf
children f36bd6c5e996
files NEWS OrthancFramework/Sources/HttpServer/HttpServer.cpp OrthancFramework/Sources/HttpServer/HttpServer.h OrthancFramework/Sources/HttpServer/IIncomingHttpRequestFilter.h OrthancFramework/UnitTestsSources/RestApiTests.cpp OrthancServer/Plugins/Engine/OrthancPlugins.cpp OrthancServer/Plugins/Engine/OrthancPlugins.h OrthancServer/Plugins/Include/orthanc/OrthancCPlugin.h OrthancServer/Sources/main.cpp
diffstat 9 files changed, 315 insertions(+), 128 deletions(-) [+]
line wrap: on
line diff
--- a/NEWS	Wed Jul 09 21:48:25 2025 +0200
+++ b/NEWS	Wed Jul 09 23:27:19 2025 +0200
@@ -29,8 +29,8 @@
 * Added new primitives:
   - "OrthancPluginSetStableStatus()" to force the stabilization of a
     DICOM resource from a plugin.
-  - "OrthancPluginRedirectNotAuthenticatedToRoot()" to allow a plugin
-    to redirect unauthenticated users to a login page.
+  - "OrthancPluginRegisterHttpAuthentication()" to install a custom
+    callback to authenticate HTTP requests.
 * OrthancPluginCallRestApi() now also returns the body of DELETE requests:
   https://discourse.orthanc-server.org/t/response-to-plugin-from-orthanc-api-delete-endpoint/6022
 
--- a/OrthancFramework/Sources/HttpServer/HttpServer.cpp	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancFramework/Sources/HttpServer/HttpServer.cpp	Wed Jul 09 23:27:19 2025 +0200
@@ -622,7 +622,7 @@
   
   enum AccessMode
   {
-    AccessMode_NotAuthenticated,
+    AccessMode_Unauthorized,
     AccessMode_AuthorizationToken,
     AccessMode_RegisteredUser
   };
@@ -658,7 +658,7 @@
       }
     }
 
-    return AccessMode_NotAuthenticated;
+    return AccessMode_Unauthorized;
   }
 
 
@@ -1147,7 +1147,42 @@
   } 
 #endif /* ORTHANC_ENABLE_PUGIXML == 1 */
 
-  
+
+  std::string HttpServer::GetRelativePathToRoot(const std::string& uri)
+  {
+    if (uri.empty())
+    {
+      throw OrthancException(ErrorCode_ParameterOutOfRange);
+    }
+
+    if (uri == "/")
+    {
+      return "./";
+    }
+
+    std::string path;
+
+    if (uri[uri.size() - 1] == '/')
+    {
+      path = "../";
+    }
+    else
+    {
+      path = "./";
+    }
+
+    UriComponents components;
+    Toolbox::SplitUriComponents(components, uri);
+
+    for (size_t i = 1; i < components.size(); i++)
+    {
+      path += "../";
+    }
+
+    return path;
+  }
+
+
   static void InternalCallback(HttpOutput& output /* out */,
                                HttpMethod& method /* out */,
                                HttpServer& server,
@@ -1203,9 +1238,10 @@
       HttpToolbox::ParseGetArguments(argumentsGET, request->query_string);
     }
 
-    
+
     AccessMode accessMode = IsAccessGranted(server, headers);
 
+
 #if ORTHANC_ENABLE_MONGOOSE == 1
     // Apply the filter, if it is installed
     char remoteIp[24];
@@ -1229,6 +1265,50 @@
       requestUri = "";
     }
       
+
+    const IIncomingHttpRequestFilter *filter = server.GetIncomingHttpRequestFilter();
+
+    // Authenticate this connection
+    std::string redirection;
+    IIncomingHttpRequestFilter::AuthenticationStatus status;
+
+    if (filter == NULL)
+    {
+      status = IIncomingHttpRequestFilter::AuthenticationStatus_NotImplemented;
+    }
+    else
+    {
+      status = filter->CheckAuthentication(redirection, requestUri, headers);
+    }
+
+    switch (status)
+    {
+      case IIncomingHttpRequestFilter::AuthenticationStatus_NotImplemented:
+        // This was the only behavior available in Orthanc <= 1.12.8
+        if (server.IsAuthenticationEnabled() &&
+            accessMode == AccessMode_Unauthorized)
+        {
+          output.SendUnauthorized(server.GetRealm());   // 401 error
+          return;
+        }
+        break;
+
+      case IIncomingHttpRequestFilter::AuthenticationStatus_Success:
+        break;
+
+      case IIncomingHttpRequestFilter::AuthenticationStatus_Redirect:
+        output.Redirect(Toolbox::JoinUri(HttpServer::GetRelativePathToRoot(requestUri), redirection));
+        return;
+
+      case IIncomingHttpRequestFilter::AuthenticationStatus_Unauthorized:
+        output.SendStatus(HttpStatus_401_Unauthorized);
+        return;
+
+      default:
+        throw OrthancException(ErrorCode_ParameterOutOfRange);
+    }
+
+
     // Decompose the URI into its components
     UriComponents uri;
     try
@@ -1242,44 +1322,6 @@
     }
 
 
-    // Authenticate this connection
-    if (server.IsAuthenticationEnabled() &&
-        accessMode == AccessMode_NotAuthenticated)
-    {
-      IIncomingHttpRequestFilter *filter = server.GetIncomingHttpRequestFilter();
-      if (uri.size() > 0 &&
-          filter != NULL &&
-          filter->IsRedirectNotAuthenticatedToRoot())
-      {
-        // This is new in Orthanc 1.12.9
-        std::string redirectionToRoot;
-
-        std::string tmp(requestUri);
-        if (!tmp.empty() &&
-            tmp[tmp.size() - 1] == '/')
-        {
-          redirectionToRoot = "../";
-        }
-        else
-        {
-          redirectionToRoot = "./";
-        }
-
-        for (size_t i = 0; i < uri.size() - 1; i++)
-        {
-          redirectionToRoot += "../";
-        }
-
-        output.Redirect(redirectionToRoot);
-      }
-      else
-      {
-        output.SendUnauthorized(server.GetRealm());   // 401 error
-      }
-      return;
-    }
-
-
     // Compute the HTTP method, taking method faking into consideration
     method = HttpMethod_Get;
 
@@ -1332,10 +1374,9 @@
       // filter. In the case of an authorization bearer token, grant
       // full access to the API.
 
-      assert(accessMode == AccessMode_NotAuthenticated ||  // Could be the case if "!server.IsAuthenticationEnabled()"
+      assert(accessMode == AccessMode_Unauthorized ||  // Could be the case if "!server.IsAuthenticationEnabled()"
              accessMode == AccessMode_RegisteredUser);
       
-      IIncomingHttpRequestFilter *filter = server.GetIncomingHttpRequestFilter();
       if (filter != NULL &&
           !filter->IsAllowed(filterMethod, requestUri, remoteIp,
                              username.c_str(), headers, argumentsGET))
--- a/OrthancFramework/Sources/HttpServer/HttpServer.h	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancFramework/Sources/HttpServer/HttpServer.h	Wed Jul 09 23:27:19 2025 +0200
@@ -233,5 +233,7 @@
     {
       return availableHttpThreadsMetrics_;
     }
+
+    static std::string GetRelativePathToRoot(const std::string& uri);
   };
 }
--- a/OrthancFramework/Sources/HttpServer/IIncomingHttpRequestFilter.h	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancFramework/Sources/HttpServer/IIncomingHttpRequestFilter.h	Wed Jul 09 23:27:19 2025 +0200
@@ -31,20 +31,32 @@
   class IIncomingHttpRequestFilter : public boost::noncopyable
   {
   public:
+    enum AuthenticationStatus
+    {
+      AuthenticationStatus_NotImplemented,
+      AuthenticationStatus_Success,
+      AuthenticationStatus_Unauthorized,
+      AuthenticationStatus_Redirect
+    };
+
     virtual ~IIncomingHttpRequestFilter()
     {
     }
 
     // New in Orthanc 1.8.1
-    virtual bool IsValidBearerToken(const std::string& token) = 0;
+    virtual bool IsValidBearerToken(const std::string& token) const = 0;
+
+    // This method corresponds to HTTP authentication
+    virtual AuthenticationStatus CheckAuthentication(std::string& redirection /* out: path relative to the root */,
+                                                     const std::string& uri,
+                                                     const HttpToolbox::Arguments& httpHeaders) const = 0;
     
+    // This method corresponds to HTTP authorization
     virtual bool IsAllowed(HttpMethod method,
                            const char* uri,
                            const char* ip,
                            const char* username,
                            const HttpToolbox::Arguments& httpHeaders,
-                           const HttpToolbox::GetArguments& getArguments) = 0;
-
-    virtual bool IsRedirectNotAuthenticatedToRoot() const = 0;
+                           const HttpToolbox::GetArguments& getArguments) const = 0;
   };
 }
--- a/OrthancFramework/UnitTestsSources/RestApiTests.cpp	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancFramework/UnitTestsSources/RestApiTests.cpp	Wed Jul 09 23:27:19 2025 +0200
@@ -1386,3 +1386,14 @@
   server.Stop();
 }
 #endif
+
+
+TEST(HttpServer, GetRelativePathToRoot)
+{
+  ASSERT_THROW(HttpServer::GetRelativePathToRoot(""), OrthancException);
+  ASSERT_EQ("./", HttpServer::GetRelativePathToRoot("/"));
+  ASSERT_EQ("./", HttpServer::GetRelativePathToRoot("/system"));
+  ASSERT_EQ("../", HttpServer::GetRelativePathToRoot("/system/"));
+  ASSERT_EQ("./../../", HttpServer::GetRelativePathToRoot("/a/b/system"));
+  ASSERT_EQ("../../../", HttpServer::GetRelativePathToRoot("/a/b/system/"));
+}
--- a/OrthancServer/Plugins/Engine/OrthancPlugins.cpp	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancServer/Plugins/Engine/OrthancPlugins.cpp	Wed Jul 09 23:27:19 2025 +0200
@@ -1739,6 +1739,7 @@
     WebDavCollections webDavCollections_;  // New in Orthanc 1.10.1
     std::unique_ptr<StorageAreaFactory>  storageArea_;
     std::set<std::string> authorizationTokens_;
+    OrthancPluginHttpAuthentication  httpAuthentication_;  // New in Orthanc 1.12.9
 
     boost::recursive_mutex restCallbackInvokationMutex_;
     boost::shared_mutex restCallbackRegistrationMutex_;  // New in Orthanc 1.9.0
@@ -1763,7 +1764,6 @@
     std::string databaseServerIdentifier_;   // New in Orthanc 1.9.2
     unsigned int maxDatabaseRetries_;        // New in Orthanc 1.9.2
     bool hasStorageAreaCustomData_;          // New in Orthanc 1.12.8
-    bool redirectNotAuthenticatedToRoot_;    // New in Orthanc 1.12.9
 
     explicit PImpl(const std::string& databaseServerIdentifier) : 
       contextRefCount_(0),
@@ -1771,12 +1771,12 @@
       findCallback_(NULL),
       worklistCallback_(NULL),
       receivedInstanceCallback_(NULL),
+      httpAuthentication_(NULL),
       argc_(1),
       argv_(NULL),
       databaseServerIdentifier_(databaseServerIdentifier),
       maxDatabaseRetries_(0),
-      hasStorageAreaCustomData_(false),
-      redirectNotAuthenticatedToRoot_(false)
+      hasStorageAreaCustomData_(false)
     {
       memset(&moveCallbacks_, 0, sizeof(moveCallbacks_));
     }
@@ -2282,6 +2282,8 @@
         sizeof(int32_t) != sizeof(OrthancPluginLogCategory) ||
         sizeof(int32_t) != sizeof(OrthancPluginStoreStatus) ||
         sizeof(int32_t) != sizeof(OrthancPluginQueueOrigin) ||
+        sizeof(int32_t) != sizeof(OrthancPluginStableStatus) ||
+        sizeof(int32_t) != sizeof(OrthancPluginHttpAuthenticationStatus) ||
 
         // From OrthancCDatabasePlugin.h
         sizeof(int32_t) != sizeof(_OrthancPluginDatabaseAnswerType) ||
@@ -3084,6 +3086,26 @@
   }
 
 
+  void OrthancPlugins::RegisterHttpAuthentication(const void* parameters)
+  {
+    const _OrthancPluginHttpAuthentication& p =
+      *reinterpret_cast<const _OrthancPluginHttpAuthentication*>(parameters);
+
+    boost::unique_lock<boost::shared_mutex> lock(pimpl_->incomingHttpRequestFilterMutex_);
+
+    if (pimpl_->httpAuthentication_ == NULL)
+    {
+      CLOG(INFO, PLUGINS) << "Plugin has registered a callback to authenticate incoming HTTP requests";
+      pimpl_->httpAuthentication_ = p.callback;
+    }
+    else
+    {
+      throw OrthancException(ErrorCode_Plugin,
+                             "Only one plugin can register a callback to authenticate incoming HTTP requests");
+    }
+  }
+
+
   void OrthancPlugins::AnswerBuffer(const void* parameters)
   {
     const _OrthancPluginAnswerBuffer& p = 
@@ -5853,18 +5875,6 @@
         return true;
       }
 
-      case _OrthancPluginService_RedirectNotAuthenticatedToRoot:
-      {
-        const _OrthancPluginRedirectNotAuthenticatedToRoot& p = *reinterpret_cast<const _OrthancPluginRedirectNotAuthenticatedToRoot*>(parameters);
-
-        {
-          boost::unique_lock<boost::shared_mutex> lock(pimpl_->incomingHttpRequestFilterMutex_);
-          pimpl_->redirectNotAuthenticatedToRoot_ = (p.redirect == 1);
-        }
-
-        return true;
-      }
-
       default:
         return false;
     }
@@ -5946,6 +5956,10 @@
         RegisterStorageCommitmentScpCallback(parameters);
         return true;
 
+      case _OrthancPluginService_RegisterHttpAuthentication:
+        RegisterHttpAuthentication(parameters);
+        return true;
+
       case _OrthancPluginService_RegisterStorageArea:
       case _OrthancPluginService_RegisterStorageArea2:
       case _OrthancPluginService_RegisterStorageArea3:
@@ -6832,9 +6846,61 @@
   }
 
 
-  bool OrthancPlugins::IsRedirectNotAuthenticatedToRoot() const
+  IIncomingHttpRequestFilter::AuthenticationStatus OrthancPlugins::CheckAuthentication(
+    std::string& redirection,
+    const std::string& uri,
+    const HttpToolbox::Arguments& httpHeaders) const
   {
     boost::shared_lock<boost::shared_mutex> lock(pimpl_->incomingHttpRequestFilterMutex_);
-    return pimpl_->redirectNotAuthenticatedToRoot_;
+
+    if (pimpl_->httpAuthentication_ == NULL)
+    {
+      return IIncomingHttpRequestFilter::AuthenticationStatus_NotImplemented;
+    }
+    else
+    {
+      std::vector<const char*> keys, values;
+      keys.resize(httpHeaders.size());
+      values.resize(httpHeaders.size());
+
+      uint32_t i = 0;
+      for (HttpToolbox::Arguments::const_iterator it = httpHeaders.begin(); it != httpHeaders.end(); ++it)
+      {
+        keys[i] = it->first.c_str();
+        values[i] = it->second.c_str();
+        i++;
+      }
+
+      assert(i == httpHeaders.size());
+
+      OrthancPluginHttpAuthenticationStatus status = OrthancPluginHttpAuthenticationStatus_Unauthorized;
+      PluginMemoryBuffer32 redirectionBuffer;
+      OrthancPluginErrorCode code = pimpl_->httpAuthentication_(&status, redirectionBuffer.GetObject(), uri.c_str(), i,
+                                                                keys.empty() ? NULL : &keys[0],
+                                                                values.empty() ? NULL : &values[0]);
+
+      if (code != OrthancPluginErrorCode_Success)
+      {
+        throw OrthancException(static_cast<ErrorCode>(code));
+      }
+      else
+      {
+        switch (status)
+        {
+        case OrthancPluginHttpAuthenticationStatus_Success:
+          return IIncomingHttpRequestFilter::AuthenticationStatus_Success;
+
+        case OrthancPluginHttpAuthenticationStatus_Unauthorized:
+          return IIncomingHttpRequestFilter::AuthenticationStatus_Unauthorized;
+
+        case OrthancPluginHttpAuthenticationStatus_Redirect:
+          redirectionBuffer.MoveToString(redirection);
+          return IIncomingHttpRequestFilter::AuthenticationStatus_Redirect;
+
+        default:
+          throw OrthancException(ErrorCode_ParameterOutOfRange);
+        }
+      }
+    }
   }
 }
--- a/OrthancServer/Plugins/Engine/OrthancPlugins.h	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancServer/Plugins/Engine/OrthancPlugins.h	Wed Jul 09 23:27:19 2025 +0200
@@ -138,6 +138,8 @@
 
     void RegisterStorageCommitmentScpCallback(const void* parameters);
 
+    void RegisterHttpAuthentication(const void* parameters);
+
     void AnswerBuffer(const void* parameters);
 
     void Redirect(const void* parameters);
@@ -415,7 +417,10 @@
 
     void RegisterWebDavCollections(HttpServer& target);
 
-    bool IsRedirectNotAuthenticatedToRoot() const;
+    IIncomingHttpRequestFilter::AuthenticationStatus CheckAuthentication(
+      std::string& redirection,
+      const std::string& uri,
+      const HttpToolbox::Arguments& httpHeaders) const;
   };
 }
 
--- a/OrthancServer/Plugins/Include/orthanc/OrthancCPlugin.h	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancServer/Plugins/Include/orthanc/OrthancCPlugin.h	Wed Jul 09 23:27:19 2025 +0200
@@ -31,6 +31,7 @@
  *    - Possibly register a custom transcoder for DICOM images using OrthancPluginRegisterTranscoderCallback().
  *    - Possibly register a callback to discard instances received through DICOM C-STORE using OrthancPluginRegisterIncomingCStoreInstanceFilter().
  *    - Possibly register a callback to branch a WebDAV virtual filesystem using OrthancPluginRegisterWebDavCollection().
+ *    - Possibly register a callback to authenticate HTTP requests using OrthancPluginRegisterHttpAuthentication().
  * -# <tt>void OrthancPluginFinalize()</tt>:
  *    This function is invoked by Orthanc during its shutdown. The plugin
  *    must free all its memory.
@@ -484,7 +485,6 @@
     _OrthancPluginService_DequeueValue = 58,                        /* New in Orthanc 1.12.8 */
     _OrthancPluginService_GetQueueSize = 59,                        /* New in Orthanc 1.12.8 */
     _OrthancPluginService_SetStableStatus = 60,                     /* New in Orthanc 1.12.9 */
-    _OrthancPluginService_RedirectNotAuthenticatedToRoot = 61,      /* New in Orthanc 1.12.9 */
 
     /* Registration of callbacks */
     _OrthancPluginService_RegisterRestCallback = 1000,
@@ -508,6 +508,7 @@
     _OrthancPluginService_RegisterReceivedInstanceCallback = 1018,  /* New in Orthanc 1.10.0 */
     _OrthancPluginService_RegisterWebDavCollection = 1019,     /* New in Orthanc 1.10.1 */
     _OrthancPluginService_RegisterStorageArea3 = 1020,         /* New in Orthanc 1.12.8 */
+    _OrthancPluginService_RegisterHttpAuthentication = 1021,   /* New in Orthanc 1.12.9 */
 
     /* Sending answers to REST calls */
     _OrthancPluginService_AnswerBuffer = 2000,
@@ -1160,6 +1161,7 @@
     _OrthancPluginStoreStatus_INTERNAL = 0x7fffffff
   } OrthancPluginStoreStatus;
 
+
   /**
    * The supported modes to remove an element from a queue.
    **/
@@ -1171,6 +1173,7 @@
     _OrthancPluginQueueOrigin_INTERNAL = 0x7fffffff
   } OrthancPluginQueueOrigin;
 
+
   /**
    * The "stable" status of a resource.
    **/
@@ -1184,6 +1187,19 @@
 
 
   /**
+   * The status related to the authentication of a HTTP request.
+   **/
+  typedef enum
+  {
+    OrthancPluginHttpAuthenticationStatus_Success = 0,       /*!< The authentication has succeeded */
+    OrthancPluginHttpAuthenticationStatus_Unauthorized = 1,  /*!< The authentication has failed */
+    OrthancPluginHttpAuthenticationStatus_Redirect = 2,      /*!< The user must be redirected to another path (for login) */
+
+    _OrthancPluginHttpAuthenticationStatus_INTERNAL = 0x7fffffff
+  } OrthancPluginHttpAuthenticationStatus;
+
+
+  /**
    * @brief A 32-bit memory buffer allocated by the core system of Orthanc.
    *
    * A memory buffer allocated by the core system of Orthanc. When the
@@ -2154,7 +2170,9 @@
         sizeof(int32_t) != sizeof(OrthancPluginLogLevel) ||
         sizeof(int32_t) != sizeof(OrthancPluginLogCategory) ||
         sizeof(int32_t) != sizeof(OrthancPluginStoreStatus) ||
-        sizeof(int32_t) != sizeof(OrthancPluginQueueOrigin))
+        sizeof(int32_t) != sizeof(OrthancPluginQueueOrigin) ||
+        sizeof(int32_t) != sizeof(OrthancPluginStableStatus) ||
+        sizeof(int32_t) != sizeof(OrthancPluginHttpAuthenticationStatus))
     {
       /* Mismatch in the size of the enumerations */
       return 0;
@@ -10312,13 +10330,16 @@
   } _OrthancPluginSetStableStatus;
 
   /**
-   * @brief Change the "Stable" status of a resource.  
-   *        Forcing a resource to "Stable" if it is currently "Unstable" will change 
-   *        its Stable status AND trigger a new Stable change which will also trigger 
-   *        listener callbacks.
-   *        Forcing a resource to "Stable" if it is already "Stable" is a no-op.
-   *        Forcing a resource to "Unstable" will change its Stable status to "Unstable"
-   *        AND reset its stabilization period, no matter of its initial state.
+   * @brief Change the "Stable" status of a resource.
+   *
+   * Forcing a resource to "Stable" if it is currently "Unstable" will
+   * change its Stable status AND trigger a new Stable change which
+   * will also trigger listener callbacks.
+   *
+   * Forcing a resource to "Stable" if it is already "Stable" is a
+   * no-op.  Forcing a resource to "Unstable" will change its Stable
+   * status to "Unstable" AND reset its stabilization period, no
+   * matter of its initial state.
    *
    * @param context The Orthanc plugin context, as received by OrthancPluginInitialize().
    * @param statusHasChanged Wheter the status has changed (1) or not (0) during the execution of this command.
@@ -10341,39 +10362,66 @@
   }
 
 
-  typedef struct
-  {
-    uint8_t   redirect;
-  } _OrthancPluginRedirectNotAuthenticatedToRoot;
-
-  /**
-   * @brief Whether to redirect unauthorized requests to the root of the Web server.
-   *
-   * If a request is non-authenticated (e.g., because of bad HTTP
-   * basic authentication credentials, or because of a plugin
-   * implementing a filtering over incoming HTTP requests), Orthanc by
-   * default returns a 401 "Unauthorized" HTTP status code.
-   *
-   * However, an Orthanc plugin providing a custom user interface
-   * could want to redirect the user to a login page. In such a
-   * situation, plugins can invoke
-   * "OrthancPluginRedirectNotAuthenticatedToRoot(context, 1)". This
-   * allows the plugin to redirect the user to its login page by
-   * overriding the REST callback for the "/" path.
-   *
-   * @param context The Orthanc plugin context, as received by OrthancPluginInitialize().
-   * @param redirect Whether to redirect unauthorized (non-authenticated) requests.
+  /**
+   * @brief Callback to authenticate a HTTP request
+   *
+   * Signature of a callback function that authenticates every incoming HTTP.
+   *
+   * @param status The output status of the authentication.
+   * @param redirection If status is `OrthancPluginHttpAuthenticationStatus_Redirect`,
+   * the path where to redirect the user (typically, a login page). The path is relative
+   * to the root of the Web server of Orthanc.
+   * @param headersCount The number of HTTP headers.
+   * @param headersKeys The keys of the HTTP headers (always converted to low-case).
+   * @param headersValues The values of the HTTP headers.
    * @return 0 if success, other value if error.
-   **/
-  ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRedirectNotAuthenticatedToRoot(
-    OrthancPluginContext*  context,
-    uint8_t                redirect)
-  {
-    _OrthancPluginRedirectNotAuthenticatedToRoot params;
-    params.redirect = redirect;
-
-    return context->InvokeService(context, _OrthancPluginService_RedirectNotAuthenticatedToRoot, &params);
-  }
+   * @ingroup Callbacks
+   **/
+  typedef OrthancPluginErrorCode (*OrthancPluginHttpAuthentication) (
+    OrthancPluginHttpAuthenticationStatus*  status,       /* out */
+    OrthancPluginMemoryBuffer*              redirection,  /* out */
+    const char*                             uri,
+    uint32_t                                headersCount,
+    const char* const*                      headersKeys,
+    const char* const*                      headersValues);
+
+
+  typedef struct
+  {
+    OrthancPluginHttpAuthentication  callback;
+  } _OrthancPluginHttpAuthentication;
+
+  /**
+   * @brief Register a callback to handle HTTP authentication.
+   *
+   * This function installs a callback that is executed on each
+   * incoming HTTP request to handle HTTP authentication. At most one
+   * plugin can register such a callback. This gives the opportunity
+   * to one plugin to validate access tokens (such as a JWT), possibly
+   * redirecting the user to a login page.
+   *
+   * If one plugin installs such a callback, the built-in HTTP
+   * authentication of Orthanc is disabled. This means that the
+   * "RegisteredUsers" and "AuthenticationEnabled" configuration
+   * options of Orthanc are totally ignored. In addition, tokens
+   * generated by OrthancPluginGenerateRestApiAuthorizationToken()
+   * become ineffective.
+   *
+   * @param context The Orthanc plugin context, as received by OrthancPluginInitialize().
+   * @param callback The HTTP authentication callback.
+   * @return 0 if success, other value if error.
+   * @ingroup Callbacks
+   **/
+  ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRegisterHttpAuthentication(
+    OrthancPluginContext*            context,
+    OrthancPluginHttpAuthentication  callback)
+  {
+    _OrthancPluginHttpAuthentication params;
+    params.callback = callback;
+
+    return context->InvokeService(context, _OrthancPluginService_RegisterHttpAuthentication, &params);
+  }
+
 
 #ifdef  __cplusplus
 }
--- a/OrthancServer/Sources/main.cpp	Wed Jul 09 21:48:25 2025 +0200
+++ b/OrthancServer/Sources/main.cpp	Wed Jul 09 23:27:19 2025 +0200
@@ -534,7 +534,7 @@
   {
   }
 
-  virtual bool IsValidBearerToken(const std::string& token) ORTHANC_OVERRIDE
+  virtual bool IsValidBearerToken(const std::string& token) const ORTHANC_OVERRIDE
   {
 #if ORTHANC_ENABLE_PLUGINS == 1
     return (plugins_ != NULL &&
@@ -549,7 +549,7 @@
                          const char* ip,
                          const char* username,
                          const HttpToolbox::Arguments& httpHeaders,
-                         const HttpToolbox::GetArguments& getArguments) ORTHANC_OVERRIDE
+                         const HttpToolbox::GetArguments& getArguments) const ORTHANC_OVERRIDE
   {
 #if ORTHANC_ENABLE_PLUGINS == 1
     if (plugins_ != NULL &&
@@ -570,24 +570,24 @@
 
       switch (method)
       {
-        case HttpMethod_Get:
-          call.PushString("GET");
-          break;
+      case HttpMethod_Get:
+        call.PushString("GET");
+        break;
 
-        case HttpMethod_Put:
-          call.PushString("PUT");
-          break;
+      case HttpMethod_Put:
+        call.PushString("PUT");
+        break;
 
-        case HttpMethod_Post:
-          call.PushString("POST");
-          break;
+      case HttpMethod_Post:
+        call.PushString("POST");
+        break;
 
-        case HttpMethod_Delete:
-          call.PushString("DELETE");
-          break;
+      case HttpMethod_Delete:
+        call.PushString("DELETE");
+        break;
 
-        default:
-          return true;
+      default:
+        return true;
       }
 
       call.PushString(uri);
@@ -605,16 +605,18 @@
     return true;
   }
 
-  virtual bool IsRedirectNotAuthenticatedToRoot() const ORTHANC_OVERRIDE
+  virtual AuthenticationStatus CheckAuthentication(std::string& redirection /* out: path relative to the root */,
+                                                   const std::string& uri,
+                                                   const HttpToolbox::Arguments& httpHeaders) const ORTHANC_OVERRIDE
   {
 #if ORTHANC_ENABLE_PLUGINS == 1
     if (plugins_ != NULL)
     {
-      return plugins_->IsRedirectNotAuthenticatedToRoot();
+      return plugins_->CheckAuthentication(redirection, uri, httpHeaders);
     }
 #endif
 
-    return false;
+    return AuthenticationStatus_NotImplemented;
   }
 };