]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/AuthorizationFilter.java
SCL REST API server
[simantics/platform.git] / bundles / org.simantics.scl.rest / src / org / simantics / scl / rest / AuthorizationFilter.java
diff --git a/bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/AuthorizationFilter.java b/bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/AuthorizationFilter.java
new file mode 100644 (file)
index 0000000..f307b66
--- /dev/null
@@ -0,0 +1,58 @@
+/*******************************************************************************
+ * Copyright (c) 2013, 2016 Association for Decentralized 
+ * Information Management in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the THTH Simantics 
+ * Division Member Component License which accompanies this 
+ * distribution, and is available at
+ * http://www.simantics.org/legal/sdmcl-v10.html
+ *
+ * Contributors:
+ *     Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.scl.rest;
+
+import java.io.IOException;
+
+import javax.ws.rs.NotAuthorizedException;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+public class AuthorizationFilter implements ContainerRequestFilter {
+
+    private final String token;
+
+    public AuthorizationFilter(String token) {
+        this.token = token;
+    }
+
+    @Override
+    public void filter(ContainerRequestContext requestContext) throws IOException {
+        // Get the HTTP Authorization header from the request
+        String authorizationHeader =  requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
+
+        // Check if the HTTP Authorization header is present and formatted correctly 
+        if (authorizationHeader == null || !authorizationHeader.startsWith("SCLRESTServer-Bearer ")) {
+            throw new NotAuthorizedException("Authorization header must be provided");
+        }
+
+        // Extract the token from the HTTP Authorization header
+        String token = authorizationHeader.substring("SCLRESTServer-Bearer".length()).trim();
+        try {
+            // Validate the token
+            validateToken(token);
+        } catch (Exception e) {
+            requestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
+        }
+    }
+
+    private void validateToken(String token) throws Exception {
+        if (!this.token.equals(token)) {
+            throw new Exception("Wrong token!");
+        }
+    }
+
+}