1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 }