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(true);
85      final Secret secret;
86      if (session instanceof HttpSession) {
87        secret = (Secret) ((HttpSession) session).getAttribute(Secret.KEY);
88      } else if (PortletUtils.isPortletApiAvailable() && session instanceof PortletSession) {
89        secret = (Secret) ((PortletSession) session).getAttribute(Secret.KEY, PortletSession.APPLICATION_SCOPE);
90      } else {
91        throw new IllegalArgumentException("Unknown session type: " + session);
92      }
93      return secret != null && secret.secret.equals(fromRequest);
94    }
95  
96    /**
97     * Encode a hidden field with the secret value from the session.
98     */
99    public static void encode(final FacesContext facesContext, final TobagoResponseWriter writer) throws IOException {
100     writer.startElement(HtmlElements.INPUT, null);
101     writer.writeAttribute(HtmlAttributes.TYPE, HtmlInputTypes.HIDDEN, false);
102     writer.writeAttribute(HtmlAttributes.NAME, Secret.KEY, false);
103     writer.writeAttribute(HtmlAttributes.ID, Secret.KEY, false);
104     final Object session = facesContext.getExternalContext().getSession(true);
105     final Secret secret;
106     if (session instanceof HttpSession) {
107       secret = (Secret) ((HttpSession) session).getAttribute(Secret.KEY);
108     } else if (PortletUtils.isPortletApiAvailable() && session instanceof PortletSession) {
109       secret = (Secret) ((PortletSession) session).getAttribute(Secret.KEY, PortletSession.APPLICATION_SCOPE);
110     } else {
111       throw new IllegalArgumentException("Unknown session type: " + session);
112     }
113     writer.writeAttribute(HtmlAttributes.VALUE, secret.secret, false);
114     writer.endElement(HtmlElements.INPUT);
115   }
116 
117   /**
118    * Create a secret attribute in the session.
119    * Should usually be called in a {@link javax.servlet.http.HttpSessionListener}.
120    */
121   public static void create(final HttpSession session) {
122     session.setAttribute(Secret.KEY, new Secret());
123   }
124 }