Thomas Vachuska | 67484d9 | 2018-07-17 11:51:54 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2018-present Open Networking Foundation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package org.onlab.rest; |
| 18 | |
| 19 | import com.google.common.collect.ImmutableSet; |
| 20 | |
| 21 | import javax.ws.rs.ForbiddenException; |
| 22 | import javax.ws.rs.container.ContainerRequestContext; |
| 23 | import javax.ws.rs.container.ContainerRequestFilter; |
| 24 | import java.io.IOException; |
| 25 | import java.util.Set; |
| 26 | |
| 27 | /** |
| 28 | * Filter that performs authorization checks on all incoming REST API requests. |
| 29 | * Methods with modify semantics require 'admin' role; all others require 'viewer' role. |
| 30 | */ |
| 31 | public class AuthorizationFilter implements ContainerRequestFilter { |
| 32 | |
| 33 | private static final String ADMIN = "admin"; |
| 34 | private static final String VIEWER = "viewer"; |
| 35 | |
| 36 | private static final String FORBIDDEN_MSG = |
| 37 | "User has insufficient privilege for this request"; |
| 38 | |
| 39 | private static final Set<String> PRIVILEGED_METHODS = |
| 40 | ImmutableSet.of("POST", "PUT", "DELETE", "PATCH"); |
| 41 | |
| 42 | private static boolean disableForTests = false; |
| 43 | |
| 44 | @Override |
| 45 | public void filter(ContainerRequestContext requestContext) throws IOException { |
| 46 | if (disableForTests) { |
| 47 | return; |
| 48 | } |
| 49 | if ((PRIVILEGED_METHODS.contains(requestContext.getMethod()) && |
| 50 | !requestContext.getSecurityContext().isUserInRole(ADMIN)) || |
| 51 | !requestContext.getSecurityContext().isUserInRole(VIEWER)) { |
| 52 | throw new ForbiddenException(FORBIDDEN_MSG); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | public static void disableForTests() { |
| 57 | disableForTests = true; |
| 58 | } |
| 59 | } |