View Javadoc
1   /*
2    * Copyright 2012-2021 CodeLibs Project and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.helper;
17  
18  import java.security.SecureRandom;
19  import java.util.Random;
20  
21  import javax.servlet.http.HttpServletRequest;
22  
23  import org.apache.commons.lang3.RandomStringUtils;
24  import org.codelibs.core.lang.StringUtil;
25  import org.codelibs.fess.exception.InvalidAccessTokenException;
26  import org.codelibs.fess.util.ComponentUtil;
27  
28  public class AccessTokenHelper {
29  
30      protected Random random = new SecureRandom();
31  
32      public String generateAccessToken() {
33          return RandomStringUtils.random(ComponentUtil.getFessConfig().getApiAccessTokenLengthAsInteger(), 0, 0, true, true, null, random);
34      }
35  
36      public String getAccessTokenFromRequest(final HttpServletRequest request) {
37          final String token = request.getHeader("Authorization");
38          if (token != null) {
39              final String[] values = token.trim().split(" ");
40              if (values.length == 2 && "Bearer".equals(values[0])) {
41                  return values[1];
42              }
43              if (values.length == 1) {
44                  return values[0];
45              }
46              throw new InvalidAccessTokenException("invalid_request", "Invalid format: " + token);
47          }
48          final String name = ComponentUtil.getFessConfig().getApiAccessTokenRequestParameter();
49          if (StringUtil.isNotBlank(name)) {
50              return request.getParameter(name);
51          }
52          return null;
53      }
54  
55      public void setRandom(final Random random) {
56          this.random = random;
57      }
58  }