]> gerrit.simantics Code Review - simantics/platform.git/blob - 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
1 /*******************************************************************************
2  * Copyright (c) 2013, 2016 Association for Decentralized 
3  * Information Management in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the THTH Simantics 
6  * Division Member Component License which accompanies this 
7  * distribution, and is available at
8  * http://www.simantics.org/legal/sdmcl-v10.html
9  *
10  * Contributors:
11  *     Semantum Oy - initial API and implementation
12  *******************************************************************************/
13 package org.simantics.scl.rest;
14
15 import java.io.IOException;
16
17 import javax.ws.rs.NotAuthorizedException;
18 import javax.ws.rs.container.ContainerRequestContext;
19 import javax.ws.rs.container.ContainerRequestFilter;
20 import javax.ws.rs.core.HttpHeaders;
21 import javax.ws.rs.core.Response;
22 import javax.ws.rs.core.Response.Status;
23
24 public class AuthorizationFilter implements ContainerRequestFilter {
25
26     private final String token;
27
28     public AuthorizationFilter(String token) {
29         this.token = token;
30     }
31
32     @Override
33     public void filter(ContainerRequestContext requestContext) throws IOException {
34         // Get the HTTP Authorization header from the request
35         String authorizationHeader =  requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
36
37         // Check if the HTTP Authorization header is present and formatted correctly 
38         if (authorizationHeader == null || !authorizationHeader.startsWith("SCLRESTServer-Bearer ")) {
39             throw new NotAuthorizedException("Authorization header must be provided");
40         }
41
42         // Extract the token from the HTTP Authorization header
43         String token = authorizationHeader.substring("SCLRESTServer-Bearer".length()).trim();
44         try {
45             // Validate the token
46             validateToken(token);
47         } catch (Exception e) {
48             requestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
49         }
50     }
51
52     private void validateToken(String token) throws Exception {
53         if (!this.token.equals(token)) {
54             throw new Exception("Wrong token!");
55         }
56     }
57
58 }