View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.webapp;
21  
22  import org.apache.commons.codec.binary.Base64;
23  import org.apache.myfaces.tobago.portlet.PortletUtils;
24  import org.apache.myfaces.tobago.renderkit.html.HtmlAttributes;
25  import org.apache.myfaces.tobago.renderkit.html.HtmlElements;
26  import org.apache.myfaces.tobago.renderkit.html.HtmlInputTypes;
27  
28  import javax.faces.context.FacesContext;
29  import javax.portlet.PortletSession;
30  import javax.servlet.http.HttpSession;
31  import java.io.IOException;
32  import java.io.Serializable;
33  import java.security.SecureRandom;
34  import java.util.Map;
35  
36  public final class Secret implements Serializable {
37  
38    private static final long serialVersionUID = 1L;
39  
40    private static final String KEY = Secret.class.getName();
41  
42    private static final SecureRandom RANDOM = new SecureRandom();
43  
44    private static final int SECRET_LENGTH = 16;
45  
46    private static final boolean COMMONS_CODEC_AVAILABLE = commonsCodecAvailable();
47  
48    private static boolean commonsCodecAvailable() {
49      try {
50        Base64.encodeBase64URLSafeString(new byte[0]);
51        return true;
52      } catch (final Error e) {
53        return false;
54      }
55    }
56  
57    private String secret;
58  
59    private Secret() {
60      final byte[] bytes = new byte[SECRET_LENGTH];
61      RANDOM.nextBytes(bytes);
62      secret = COMMONS_CODEC_AVAILABLE ? encodeBase64(bytes) : encodeHex(bytes);
63    }
64  
65    private String encodeBase64(final byte[] bytes) {
66      return Base64.encodeBase64URLSafeString(bytes);
67    }
68  
69    private String encodeHex(final byte[] bytes) {
70      final StringBuilder builder = new StringBuilder(SECRET_LENGTH * 2);
71      for (final byte b : bytes) {
72        builder.append(String.format("%02x", b));
73      }
74      return builder.toString();
75    }
76  
77    /**
78     * Checks that the request contains a parameter {@link org.apache.myfaces.tobago.webapp.Secret#KEY}
79     * which is equals to a secret value in the session.
80     */
81    public static boolean check(final FacesContext facesContext) {
82      final Map requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
83      final String fromRequest = (String) requestParameterMap.get(Secret.KEY);
84      final Object session = facesContext.getExternalContext().getSession(false);
85      Secret secret = getSecret(session);
86      return secret != null && secret.secret.equals(fromRequest);
87    }
88  
89    private static Secret getSecret(Object session) {
90      Secret secret = null;
91      if (session!=null) {
92        if (session instanceof HttpSession) {
93          secret = (Secret) ((HttpSession) session).getAttribute(Secret.KEY);
94        } else if (PortletUtils.isPortletApiAvailable() && session instanceof PortletSession) {
95          secret = (Secret) ((PortletSession) session).getAttribute(Secret.KEY, PortletSession.APPLICATION_SCOPE);
96        } else {
97          throw new IllegalArgumentException("Unknown session type: " + session);
98        }
99      }
100     return secret;
101   }
102 
103   /**
104    * Encode a hidden field with the secret value from the session.
105    */
106   public static void encode(final FacesContext facesContext, final TobagoResponseWriter writer) throws IOException {
107     writer.startElement(HtmlElements.INPUT, null);
108     writer.writeAttribute(HtmlAttributes.TYPE, HtmlInputTypes.HIDDEN, false);
109     writer.writeAttribute(HtmlAttributes.NAME, Secret.KEY, false);
110     writer.writeAttribute(HtmlAttributes.ID, Secret.KEY, false);
111     final Object session = facesContext.getExternalContext().getSession(true);
112     final Secret secret = getSecret(session);
113     if (secret != null) {
114       writer.writeAttribute(HtmlAttributes.VALUE, secret.secret, false);
115     }
116     writer.endElement(HtmlElements.INPUT);
117   }
118 
119   /**
120    * Create a secret attribute in the session.
121    * Should usually be called in a {@link javax.servlet.http.HttpSessionListener}.
122    */
123   public static void create(final HttpSession session) {
124     session.setAttribute(Secret.KEY, new Secret());
125   }
126 }