2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.common.endpoints.http.server;
23 import java.io.IOException;
24 import javax.servlet.Filter;
25 import javax.servlet.FilterChain;
26 import javax.servlet.ServletException;
27 import javax.servlet.ServletRequest;
28 import javax.servlet.ServletResponse;
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
34 public abstract class AuthorizationFilter implements Filter {
36 private static Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);
39 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
40 throws IOException, ServletException {
42 if (!(servletRequest instanceof HttpServletRequest)) {
43 throw new ServletException("Not an HttpServletRequest instance");
46 if (!(servletResponse instanceof HttpServletResponse)) {
47 throw new ServletException("Not an HttpServletResponse instance");
50 HttpServletRequest request = (HttpServletRequest) servletRequest;
51 HttpServletResponse response = (HttpServletResponse) servletResponse;
53 String role = getRole(request);
54 boolean authorized = request.isUserInRole(role);
56 logger.info("user {} in role {} is {}authorized to {}",
57 request.getUserPrincipal().getName(), role, ((authorized) ? "" : "NOT "), request.getMethod());
60 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
62 filterChain.doFilter(servletRequest, servletResponse);
66 protected abstract String getRole(HttpServletRequest request);