View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.audit.service.security;
18  
19  import javax.servlet.http.HttpServletRequest;
20  import javax.servlet.http.HttpServletResponse;
21  
22  import org.apache.logging.log4j.LogManager;
23  import org.apache.logging.log4j.Logger;
24  import org.springframework.http.HttpStatus;
25  import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
26  
27  public class LocalAuthorizationInterceptor extends HandlerInterceptorAdapter {
28      private static final Logger LOGGER = LogManager.getLogger();
29      private final String token;
30  
31      public LocalAuthorizationInterceptor(String token) {
32          this.token = token;
33      }
34  
35      @Override
36      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
37              throws Exception {
38          LOGGER.traceEntry();
39          try {
40              if (request.getServletPath().startsWith("/swagger")) {
41                  return true;
42              }
43  
44              String authHeader = request.getHeader("Authorization");
45              if (authHeader == null || !authHeader.equals(token)) {
46                  LOGGER.error("Authorization value of " + authHeader + " does not match expected value of " + token);
47                  response.sendError(HttpStatus.UNAUTHORIZED.value());
48                  return false;
49              }
50  
51              return true;
52          } finally {
53              LOGGER.traceExit();
54          }
55  
56      }
57  }