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  package org.apache.shiro.session.mgt.eis;
20  
21  import org.apache.shiro.session.Session;
22  import org.slf4j.Logger;
23  import org.slf4j.LoggerFactory;
24  
25  import java.io.Serializable;
26  import java.util.Random;
27  
28  /**
29   * Generates session IDs by using a {@link Random} instance to generate random IDs. The default {@code Random}
30   * implementation is a {@link java.security.SecureRandom SecureRandom} with the {@code SHA1PRNG} algorithm.
31   *
32   * @since 1.0
33   */
34  public class RandomSessionIdGenerator implements SessionIdGenerator {
35  
36      private static final Logger log = LoggerFactory.getLogger(RandomSessionIdGenerator.class);
37  
38      private static final String RANDOM_NUM_GENERATOR_ALGORITHM_NAME = "SHA1PRNG";
39      private Random random;
40  
41      public RandomSessionIdGenerator() {
42          try {
43              this.random = java.security.SecureRandom.getInstance(RANDOM_NUM_GENERATOR_ALGORITHM_NAME);
44          } catch (java.security.NoSuchAlgorithmException e) {
45              log.debug("The SecureRandom SHA1PRNG algorithm is not available on the current platform.  Using the " +
46                      "platform's default SecureRandom algorithm.", e);
47              this.random = new java.security.SecureRandom();
48          }
49      }
50  
51      public Random getRandom() {
52          return this.random;
53      }
54  
55      public void setRandom(Random random) {
56          this.random = random;
57      }
58  
59      /**
60       * Returns the String value of the configured {@link Random}'s {@link Random#nextLong() nextLong()} invocation.
61       *
62       * @param session the {@link Session} instance to which the ID will be applied.
63       * @return the String value of the configured {@link Random}'s {@link Random#nextLong()} invocation.
64       */
65      public Serializable generateId(Session session) {
66          //ignore the argument - just call the Random:
67          return Long.toString(getRandom().nextLong());
68      }
69  }