removing empty directories after src move
git-svn-id: https://svn.apache.org/repos/asf/incubator/jsecurity/trunk@731321 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/core/src/org/jsecurity/JSecurityException.java b/core/src/org/jsecurity/JSecurityException.java
new file mode 100644
index 0000000..1d93b2f
--- /dev/null
+++ b/core/src/org/jsecurity/JSecurityException.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity;
+
+import java.io.Serializable;
+
+/**
+ * Root exception for all JSecurity runtime exceptions. This class is used as the root instead
+ * of {@link java.lang.SecurityException} to remove the potential for conflicts; many other
+ * frameworks and products (such as J2EE containers) perform special operations when
+ * encountering {@link java.lang.SecurityException}.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class JSecurityException extends RuntimeException implements Serializable {
+
+ /**
+ * Creates a new JSecurityException.
+ */
+ public JSecurityException() {
+ super();
+ }
+
+ /**
+ * Constructs a new JSecurityException.
+ *
+ * @param message the reason for the exception
+ */
+ public JSecurityException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new JSecurityException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public JSecurityException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new JSecurityException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public JSecurityException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/AbstractAuthenticator.java b/core/src/org/jsecurity/authc/AbstractAuthenticator.java
new file mode 100644
index 0000000..f2f1810
--- /dev/null
+++ b/core/src/org/jsecurity/authc/AbstractAuthenticator.java
@@ -0,0 +1,246 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.subject.PrincipalCollection;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * Superclass for almost all {@link Authenticator} implementations that performs the common work around authentication
+ * attempts.
+ *
+ * <p>This class delegates the actual authentication attempt to subclasses but supports notification for
+ * successful and failed logins as well as logouts. Notification is sent to one or more registered
+ * {@link org.jsecurity.authc.AuthenticationListener AuthenticationListener}s to allow for custom processing logic
+ * when these conditions occur.
+ *
+ * <p>In most cases, the only thing a subclass needs to do (via its {@link #doAuthenticate} implementation)
+ * is perform the actual principal/credential verification process for the submitted <tt>AuthenticationToken</tt>.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public abstract class AbstractAuthenticator implements Authenticator, LogoutAware, AuthenticationListenerRegistrar {
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+ /** Private class log instance. */
+ private static final Log log = LogFactory.getLog(AbstractAuthenticator.class);
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ /** Any registered listeners that wish to know about things during the authentication process. */
+ private Collection<AuthenticationListener> listeners;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+ /**
+ * Default no-argument constructor. Ensures the internal
+ * {@link AuthenticationListener AuthenticationListener} collection is a non-null <code>ArrayList</code>.
+ */
+ public AbstractAuthenticator() {
+ listeners = new ArrayList<AuthenticationListener>();
+ }
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+ public void setAuthenticationListeners(Collection<AuthenticationListener> listeners) {
+ if (listeners == null) {
+ this.listeners = new ArrayList<AuthenticationListener>();
+ } else {
+ this.listeners = listeners;
+ }
+ }
+
+ public void add(AuthenticationListener listener) {
+ this.listeners.add(listener);
+ }
+
+ public boolean remove(AuthenticationListener listener) {
+ return this.listeners.remove(listener);
+ }
+
+ /*-------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+ /**
+ * Notifies any registered {@link org.jsecurity.authc.AuthenticationListener AuthenticationListener}s that
+ * authentication was successful for the specified <code>token</code> which resulted in the specified
+ * <code>info</code>. This implementation merely iterates over the internal <code>listeners</code> collection and
+ * calls {@link org.jsecurity.authc.AuthenticationListener#onSuccess(AuthenticationToken, AuthenticationInfo) onSuccess}
+ * for each.
+ * @param token the submitted <code>AuthenticationToken</code> that resulted in a successful authentication.
+ * @param info the returned <code>AuthenticationInfo</code> resulting from the successful authentication.
+ */
+ protected void notifySuccess(AuthenticationToken token, AuthenticationInfo info) {
+ for (AuthenticationListener listener : this.listeners) {
+ listener.onSuccess(token, info);
+ }
+ }
+
+ /**
+ * Notifies any registered {@link org.jsecurity.authc.AuthenticationListener AuthenticationListener}s that
+ * authentication failed for the
+ * specified <code>token</code> which resulted in the specified <code>ae</code> exception. This implementation merely
+ * iterates over the internal <code>listeners</code> collection and calls
+ * {@link org.jsecurity.authc.AuthenticationListener#onFailure(AuthenticationToken, AuthenticationException) onFailure}
+ * for each.
+ * @param token the submitted <code>AuthenticationToken</code> that resulted in a failed authentication.
+ * @param ae the resulting <code>AuthenticationException<code> that caused the authentication to fail.
+ */
+ protected void notifyFailure(AuthenticationToken token, AuthenticationException ae) {
+ for (AuthenticationListener listener : this.listeners) {
+ listener.onFailure(token, ae);
+ }
+ }
+
+ /**
+ * Notifies any registered {@link org.jsecurity.authc.AuthenticationListener AuthenticationListener}s that a
+ * <code>Subject</code> has logged-out. This implementation merely
+ * iterates over the internal <code>listeners</code> collection and calls
+ * {@link org.jsecurity.authc.AuthenticationListener#onLogout(org.jsecurity.subject.PrincipalCollection) onLogout}
+ * for each.
+ * @param principals the identifying principals of the <code>Subject</code>/account logging out.
+ */
+ protected void notifyLogout(PrincipalCollection principals) {
+ for (AuthenticationListener listener : this.listeners) {
+ listener.onLogout(principals);
+ }
+ }
+
+ /**
+ * This implementation merely calls
+ * {@link #notifyLogout(org.jsecurity.subject.PrincipalCollection) notifyLogout} to allow any registered listeners
+ * to react to the logout.
+ * @param principals the identifying principals of the <code>Subject</code>/account logging out.
+ */
+ public void onLogout(PrincipalCollection principals) {
+ notifyLogout(principals);
+ }
+
+ /**
+ * Implementation of the {@link Authenticator} interface that functions in the following manner:
+ *
+ * <ol>
+ * <li>Calls template {@link #doAuthenticate doAuthenticate} method for subclass execution of the actual
+ * authentication behavior.</li>
+ * <li>If an <tt>AuthenticationException</tt> is thrown during <tt>doAuthenticate</tt>,
+ * {@link #notifyFailure(AuthenticationToken, AuthenticationException) notify} any registered
+ * {@link AuthenticationListener AuthenticationListener}s of the exception and then propogate the exception
+ * for the caller to handle.</li>
+ * <li>If no exception is thrown (indicating a successful login),
+ * {@link #notifySuccess(AuthenticationToken, AuthenticationInfo) notify} any registered
+ * {@link AuthenticationListener AuthenticationListener}s of the successful attempt.</li>
+ * <li>Return the <tt>AuthenticationInfo</tt></li>
+ * </ol>
+ *
+ * @param token the submitted token representing the subject's (user's) login principals and credentials.
+ * @return the AuthenticationInfo referencing the authenticated user's account data.
+ * @throws AuthenticationException if there is any problem during the authentication process - see the
+ * interface's JavaDoc for a more detailed explanation.
+ */
+ public final AuthenticationInfo authenticate(AuthenticationToken token)
+ throws AuthenticationException {
+
+ if (token == null) {
+ throw new IllegalArgumentException("Method argumet (authentication token) cannot be null.");
+ }
+
+ if (log.isTraceEnabled()) {
+ log.trace("Authentication attempt received for token [" + token + "]");
+ }
+
+ AuthenticationInfo info;
+ try {
+ info = doAuthenticate(token);
+ if (info == null) {
+ String msg = "No account information found for authentication token [" + token + "] by this " +
+ "Authenticator instance. Please check that it is configured correctly.";
+ throw new AuthenticationException(msg);
+ }
+ } catch (Throwable t) {
+ AuthenticationException ae = null;
+ if (t instanceof AuthenticationException) {
+ ae = (AuthenticationException) t;
+ }
+ if (ae == null) {
+ //Exception thrown was not an expected AuthenticationException. Therefore it is probably a little more
+ //severe or unexpected. So, wrap in an AuthenticationException, log to warn, and propagate:
+ String msg = "Authentication failed for token submission [" + token + "]. Possible unexpected " +
+ "error? (Typical or expected login exceptions should extend from AuthenticationException).";
+ ae = new AuthenticationException(msg, t);
+ if (log.isWarnEnabled()) {
+ log.warn(msg, t);
+ }
+ }
+ try {
+ notifyFailure(token, ae);
+ } catch (Throwable t2) {
+ String msg = "Unable to send notification for failed authentication attempt - listener error?. " +
+ "Please check your AuthenticationListener implementation(s). Logging sending exception and " +
+ "propagating original AuthenticationException instead...";
+ if (log.isWarnEnabled()) {
+ log.warn(msg, t2);
+ }
+ }
+
+
+ throw ae;
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("Authentication successful for token [" + token + "]. Returned account: [" + info + "]");
+ }
+
+ notifySuccess(token, info);
+
+ return info;
+ }
+
+ /**
+ * Template design pattern hook for subclasses to implement specific authentication behavior.
+ *
+ * <p>Common behavior for most authentication attempts is encapsulated in the
+ * {@link #authenticate} method and that method invokes this one for custom behavior.
+ *
+ * <p><b>N.B.</b> Subclasses <em>should</em> throw some kind of
+ * <tt>AuthenticationException</tt> if there is a problem during
+ * authentication instead of returning <tt>null</tt>. A <tt>null</tt> return value indicates
+ * a configuration or programming error, since <tt>AuthenticationException</tt>s should
+ * indicate any expected problem (such as an unknown account or username, or invalid password, etc).
+ *
+ * @param token the authentication token encapsulating the user's login information.
+ * @return an <tt>AuthenticationInfo</tt> object encapsulating the user's account information
+ * important to JSecurity.
+ * @throws AuthenticationException if there is a problem logging in the user.
+ */
+ protected abstract AuthenticationInfo doAuthenticate(AuthenticationToken token)
+ throws AuthenticationException;
+
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authc/Account.java b/core/src/org/jsecurity/authc/Account.java
new file mode 100644
index 0000000..77dd477
--- /dev/null
+++ b/core/src/org/jsecurity/authc/Account.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+import org.jsecurity.authz.AuthorizationInfo;
+
+/**
+ * An <tt>Account</tt> is a convenience interface that extends both {@link AuthenticationInfo} and
+ * {@link AuthorizationInfo} and represents authentication and authorization for a <em>single account</em> in a
+ * <em>single Realm</em>.
+ * <p/>
+ * This interface can be useful when an Realm implementation finds it more convenient to use a single object to
+ * encapsulate both the authentication and authorization information used by both authc and authz operations.
+ * <p/>
+ * <b>Please Note</b>: Since JSecurity sometimes logs account operations, please ensure your Account's <code>toString()</code>
+ * implementation does <em>not</em> print out account credentials (password, etc), as these might be viewable to
+ * someone reading your logs. This is good practice anyway, and account principals should rarely (if ever) be printed
+ * out for any reason. If you're using JSecurity's default implementations of this interface, they only ever print the
+ * account {@link #getPrincipals() principals}, so you do not need to do anything additional.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see SimpleAccount
+ * @since 0.9
+ */
+public interface Account extends AuthenticationInfo, AuthorizationInfo {
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authc/AccountException.java b/core/src/org/jsecurity/authc/AccountException.java
new file mode 100644
index 0000000..68a3cce
--- /dev/null
+++ b/core/src/org/jsecurity/authc/AccountException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Exception thrown due to a problem with the account
+ * under which an authentication attempt is being executed.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class AccountException extends AuthenticationException {
+
+ /**
+ * Creates a new AccountException.
+ */
+ public AccountException() {
+ super();
+ }
+
+ /**
+ * Constructs a new AccountException.
+ *
+ * @param message the reason for the exception
+ */
+ public AccountException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new AccountException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public AccountException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new AccountException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public AccountException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/AuthenticationException.java b/core/src/org/jsecurity/authc/AuthenticationException.java
new file mode 100644
index 0000000..68aa3f8
--- /dev/null
+++ b/core/src/org/jsecurity/authc/AuthenticationException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * General exception thrown due to an error during the Authentication process.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class AuthenticationException extends JSecurityException {
+
+ /**
+ * Creates a new AuthenticationException.
+ */
+ public AuthenticationException() {
+ super();
+ }
+
+ /**
+ * Constructs a new AuthenticationException.
+ *
+ * @param message the reason for the exception
+ */
+ public AuthenticationException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new AuthenticationException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public AuthenticationException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new AuthenticationException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public AuthenticationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/AuthenticationToken.java b/core/src/org/jsecurity/authc/AuthenticationToken.java
new file mode 100644
index 0000000..ef0f0e1
--- /dev/null
+++ b/core/src/org/jsecurity/authc/AuthenticationToken.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+import java.io.Serializable;
+
+/**
+ * <p>An <tt>AuthenticationToken</tt> is a consolidation of an account's principals and supporting
+ * credentials submitted by a user during an authentication attempt.
+ *
+ * <p>The token is submitted to an {@link Authenticator Authenticator} via the
+ * {@link Authenticator#authenticate(AuthenticationToken) authenticate(token)} method. The
+ * Authenticator then executes the authentication/log-in process.
+ *
+ * <p>Common implementations of an <tt>AuthenticationToken</tt> would have username/password
+ * pairs, X.509 Certificate, PGP key, or anything else you can think of. The token can be
+ * anything needed by an {@link Authenticator} to authenticate properly.
+ *
+ * <p>Because applications represent user data and credentials in different ways, implementations
+ * of this interface are application-specific. You are free to acquire a user's principals and
+ * credentials however you wish (e.g. web form, Swing form, fingerprint identification, etc) and
+ * then submit them to the JSecurity framework in the form of an implementation of this
+ * interface.
+ *
+ * <p>If your application's authentication process is username/password based
+ * (like most), instead of implementing this interface yourself, take a look at the
+ * {@link UsernamePasswordToken UsernamePasswordToken} class, as it is probably sufficient for your needs.
+ *
+ * <p>RememberMe services are enabled for a token if they implement a sub-interface of this one, called
+ * {@link RememberMeAuthenticationToken RememberMeAuthenticationToken}. Implement that interfac if you need
+ * RememberMe services (the <tt>UsernamePasswordToken</tt> already implements this interface).
+ *
+ * <p>If you are familiar with JAAS, an <tt>AuthenticationToken</tt> replaces the concept of a
+ * {@link javax.security.auth.callback.Callback}, and defines meaningful behavior
+ * (<tt>Callback</tt> is just a marker interface, and of little use). We
+ * also think the name <em>AuthenticationToken</em> more accurately reflects its true purpose
+ * in a login framework, whereas <em>Callback</em> is less obvious.
+ *
+ * @author Les Hazlewood
+ * @see RememberMeAuthenticationToken
+ * @see InetAuthenticationToken
+ * @see UsernamePasswordToken
+ * @since 0.1
+ */
+public interface AuthenticationToken extends Serializable {
+
+ /**
+ * Returns the account identity submitted during the authentication process.
+ *
+ * <p>Most application authentications are username/password based and have this
+ * object represent a username. If this is the case for your application,
+ * take a look at the {@link UsernamePasswordToken UsernamePasswordToken}, as it is probably
+ * sufficient for your use.
+ *
+ * <p>Ultimately, the object returned is application specific and can represent
+ * any account identity (user id, X.509 certificate, etc).
+ *
+ * @return the account identity submitted during the authentication process.
+ * @see UsernamePasswordToken
+ */
+ Object getPrincipal();
+
+ /**
+ * Returns the credentials submitted by the user during the authentication process that verifies
+ * the submitted {@link #getPrincipal() account identity}.
+ *
+ * <p>Most application authentications are username/password based and have this object
+ * represent a submitted password. If this is the case for your application,
+ * take a look at the {@link UsernamePasswordToken UsernamePasswordToken}, as it is probably
+ * sufficient for your use.
+ *
+ * <p>Ultimately, the credentials Object returned is application specific and can represent
+ * any credential mechanism.
+ *
+ * @return the credential submitted by the user during the authentication process.
+ */
+ Object getCredentials();
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authc/Authenticator.java b/core/src/org/jsecurity/authc/Authenticator.java
new file mode 100644
index 0000000..c98d2ed
--- /dev/null
+++ b/core/src/org/jsecurity/authc/Authenticator.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * An Authenticator is responsible for authenticating accounts in an application. It
+ * is one of the primary entry points into the JSecurity API.
+ *
+ * <p>Although not a requirement, there is usually a single 'master' Authenticator configured for
+ * an application. Enabling Pluggable Authentication Module (PAM) behavior
+ * (Two Phase Commit, etc.) is usually achieved by the single <tt>Authenticator</tt> coordinating
+ * and interacting with an application-configured set of
+ * {@link org.jsecurity.realm.Realm Realm}s.
+ *
+ * <p>Note that most JSecurity users will not interact with an <tt>Authenticator</tt> instance directly. JSecurity's
+ * default architecture is based on an overall <tt>SecurityManager</tt> which typically wraps an
+ * <tt>Authenticator</tt> instance.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @see org.jsecurity.mgt.SecurityManager
+ * @see AbstractAuthenticator AbstractAuthenticator
+ * @see org.jsecurity.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator
+ * @since 0.1
+ */
+public interface Authenticator {
+
+ /**
+ * Authenticates a user based on the submitted <tt>authenticationToken</tt>.
+ *
+ * <p>If the authentication is successful, an {@link AuthenticationInfo}
+ * object is returned that represents the user's account data relevant to JSecurity. This returned object is
+ * generally used in turn to construct a <tt>Subject</tt> representing that user's identity and
+ * access to a <tt>Session</tt>
+ *
+ * @param authenticationToken any representation of a user's principals and credentials
+ * submitted during an authentication attempt.
+ * @return the AuthenticationInfo representing the authenticating user's account data.
+ * @throws AuthenticationException if there is any problem during the authentication process.
+ * See the specific exceptions listed below to as examples of what could happen in order
+ * to accurately handle these problems and to notify the user in an appropriate manner why
+ * the authentication attempt failed. Realize an implementation of this interface may or may
+ * not throw those listed or may throw other AuthenticationExceptions, but the list shows
+ * the most common ones.
+ * @see ExpiredCredentialsException
+ * @see IncorrectCredentialsException
+ * @see ExcessiveAttemptsException
+ * @see LockedAccountException
+ * @see ConcurrentAccessException
+ * @see UnknownAccountException
+ */
+ public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)
+ throws AuthenticationException;
+}
diff --git a/core/src/org/jsecurity/authc/ConcurrentAccessException.java b/core/src/org/jsecurity/authc/ConcurrentAccessException.java
new file mode 100644
index 0000000..8fb5014
--- /dev/null
+++ b/core/src/org/jsecurity/authc/ConcurrentAccessException.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Thrown when an authentication attempt has been received for an account that has already been
+ * authenticated (i.e. logged-in), and the system is configured to prevent such concurrent access.
+ *
+ * <p>This is useful when an application must ensure that only one person is logged-in to a single
+ * account at any given time.
+ *
+ * <p>Sometimes account names and passwords are lazily given away
+ * to many people for easy access to a system. Such behavior is undesirable in systems where
+ * users are accountable for their actions, such as in government applications, or when licensing
+ * agreements must be maintained, such as those which only allow 1 user per paid license.
+ *
+ * <p>By disallowing concurrent access, such systems can ensure that each authenticated session
+ * corresponds to one and only one user at any given time.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class ConcurrentAccessException extends AccountException {
+
+ /**
+ * Creates a new ConcurrentAccessException.
+ */
+ public ConcurrentAccessException() {
+ super();
+ }
+
+ /**
+ * Constructs a new ConcurrentAccessException.
+ *
+ * @param message the reason for the exception
+ */
+ public ConcurrentAccessException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new ConcurrentAccessException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ConcurrentAccessException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new ConcurrentAccessException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ConcurrentAccessException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/CredentialsException.java b/core/src/org/jsecurity/authc/CredentialsException.java
new file mode 100644
index 0000000..dd37d78
--- /dev/null
+++ b/core/src/org/jsecurity/authc/CredentialsException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Exception thrown due to a problem with the credential(s) submitted for an
+ * account during the authentication process.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class CredentialsException extends AuthenticationException {
+
+ /**
+ * Creates a new CredentialsException.
+ */
+ public CredentialsException() {
+ super();
+ }
+
+ /**
+ * Constructs a new CredentialsException.
+ *
+ * @param message the reason for the exception
+ */
+ public CredentialsException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new CredentialsException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public CredentialsException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new CredentialsException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public CredentialsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/DisabledAccountException.java b/core/src/org/jsecurity/authc/DisabledAccountException.java
new file mode 100644
index 0000000..4a693c5
--- /dev/null
+++ b/core/src/org/jsecurity/authc/DisabledAccountException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Thrown when attempting to authenticate and the corresponding account has been disabled for
+ * some reason.
+ *
+ * @author Les Hazlewood
+ * @see LockedAccountException
+ * @since 0.1
+ */
+public class DisabledAccountException extends AccountException {
+
+ /**
+ * Creates a new DisabledAccountException.
+ */
+ public DisabledAccountException() {
+ super();
+ }
+
+ /**
+ * Constructs a new DisabledAccountException.
+ *
+ * @param message the reason for the exception
+ */
+ public DisabledAccountException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new DisabledAccountException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public DisabledAccountException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new DisabledAccountException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public DisabledAccountException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/ExcessiveAttemptsException.java b/core/src/org/jsecurity/authc/ExcessiveAttemptsException.java
new file mode 100644
index 0000000..62865bc
--- /dev/null
+++ b/core/src/org/jsecurity/authc/ExcessiveAttemptsException.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Thrown when a system is configured to only allow a certain number of authentication attempts
+ * over a period of time and the current session has failed to authenticate successfully within
+ * that number. The resulting action of such an exception is application-specific, but
+ * most systems either temporarily or permanently lock that account to prevent further
+ * attempts.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class ExcessiveAttemptsException extends AccountException {
+
+ /**
+ * Creates a new ExcessiveAttemptsException.
+ */
+ public ExcessiveAttemptsException() {
+ super();
+ }
+
+ /**
+ * Constructs a new ExcessiveAttemptsException.
+ *
+ * @param message the reason for the exception
+ */
+ public ExcessiveAttemptsException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new ExcessiveAttemptsException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ExcessiveAttemptsException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new ExcessiveAttemptsException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ExcessiveAttemptsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/ExpiredCredentialsException.java b/core/src/org/jsecurity/authc/ExpiredCredentialsException.java
new file mode 100644
index 0000000..f4fd676
--- /dev/null
+++ b/core/src/org/jsecurity/authc/ExpiredCredentialsException.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Thrown during the authentication process when the system determines the submitted credential(s)
+ * has expired and will not allow login.
+ *
+ * <p>This is most often used to alert a user that their credentials (e.g. password or
+ * cryptography key) has expired and they should change the value. In such systems, the component
+ * invoking the authentication might catch this exception and redirect the user to an appropriate
+ * view to allow them to update their password or other credentials mechanism.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class ExpiredCredentialsException extends CredentialsException {
+
+ /**
+ * Creates a new ExpiredCredentialsException.
+ */
+ public ExpiredCredentialsException() {
+ super();
+ }
+
+ /**
+ * Constructs a new ExpiredCredentialsException.
+ *
+ * @param message the reason for the exception
+ */
+ public ExpiredCredentialsException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new ExpiredCredentialsException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ExpiredCredentialsException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new ExpiredCredentialsException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ExpiredCredentialsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/IncorrectCredentialsException.java b/core/src/org/jsecurity/authc/IncorrectCredentialsException.java
new file mode 100644
index 0000000..b189114
--- /dev/null
+++ b/core/src/org/jsecurity/authc/IncorrectCredentialsException.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Thrown when attempting to authenticate with credential(s) that do not match the actual
+ * credentials associated with the account principal.
+ *
+ * <p>For example, this exception might be thrown if a user's password is "secret" and
+ * "secrets" was entered by mistake.
+ *
+ * <p>Whether or not an application wishes to let
+ * the user know if they entered incorrect credentials is at the discretion of those
+ * responsible for defining the view and what happens when this exception occurs.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class IncorrectCredentialsException extends CredentialsException {
+
+ /**
+ * Creates a new IncorrectCredentialsException.
+ */
+ public IncorrectCredentialsException() {
+ super();
+ }
+
+ /**
+ * Constructs a new IncorrectCredentialsException.
+ *
+ * @param message the reason for the exception
+ */
+ public IncorrectCredentialsException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new IncorrectCredentialsException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public IncorrectCredentialsException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new IncorrectCredentialsException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public IncorrectCredentialsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/LockedAccountException.java b/core/src/org/jsecurity/authc/LockedAccountException.java
new file mode 100644
index 0000000..3a14a37
--- /dev/null
+++ b/core/src/org/jsecurity/authc/LockedAccountException.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * A special kind of <tt>DisabledAccountException</tt>, this exception is thrown when attempting
+ * to authenticate and the corresponding account has been disabled explicitly due to being locked.
+ *
+ * <p>For example, an account can be locked if an administrator explicitly locks an account or
+ * perhaps an account can be locked automatically by the system if too many unsuccessful
+ * authentication attempts take place during a specific period of time (perhaps indicating a
+ * hacking attempt).
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class LockedAccountException extends DisabledAccountException {
+
+ /**
+ * Creates a new LockedAccountException.
+ */
+ public LockedAccountException() {
+ super();
+ }
+
+ /**
+ * Constructs a new LockedAccountException.
+ *
+ * @param message the reason for the exception
+ */
+ public LockedAccountException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new LockedAccountException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public LockedAccountException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new LockedAccountException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public LockedAccountException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/SimpleAccount.java b/core/src/org/jsecurity/authc/SimpleAccount.java
new file mode 100644
index 0000000..a9d2202
--- /dev/null
+++ b/core/src/org/jsecurity/authc/SimpleAccount.java
@@ -0,0 +1,427 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+import org.jsecurity.authz.Permission;
+import org.jsecurity.authz.SimpleAuthorizationInfo;
+import org.jsecurity.subject.PrincipalCollection;
+import org.jsecurity.subject.SimplePrincipalCollection;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Set;
+
+/**
+ * Simple implementation of the {@link org.jsecurity.authc.Account} interface that
+ * contains principal and credential and authorization information (roles and permissions) as instance variables and
+ * exposes them via getters and setters using standard JavaBean notation.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class SimpleAccount implements Account, MergableAuthenticationInfo, Serializable {
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ /**
+ * The authentication information (principals and credentials) for this account.
+ */
+ private SimpleAuthenticationInfo authcInfo;
+
+ /**
+ * The authorization information for this account.
+ */
+ private SimpleAuthorizationInfo authzInfo;
+
+ /**
+ * Indicates this account is locked. This isn't honored by all <tt>Realms</tt> but is honored by
+ * {@link org.jsecurity.realm.SimpleAccountRealm}.
+ */
+ private boolean locked;
+
+ /**
+ * Indicates credentials on this account are expired. This isn't honored by all <tt>Realms</tt> but is honored by
+ * {@link org.jsecurity.realm.SimpleAccountRealm}.
+ */
+ private boolean credentialsExpired;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+ /**
+ * Default no-argument constructor.
+ */
+ public SimpleAccount() {
+ }
+
+ /**
+ * Constructs a SimpleAccount instance for the specified realm with the given principals and credentials.
+ *
+ * @param principal the 'primary' identifying attribute of the account, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ * @param realmName the name of the realm that accesses this account data
+ */
+ public SimpleAccount(Object principal, Object credentials, String realmName) {
+ this(principal instanceof PrincipalCollection ? (PrincipalCollection) principal : new SimplePrincipalCollection(principal, realmName), credentials);
+ }
+
+ /**
+ * Constructs a SimpleAccount instance for the specified realm with the given principals and credentials.
+ * @param principals the identifying attributes of the account, at least one of which should be considered the
+ * account's 'primary' identifying attribute, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ * @param realmName the name of the realm that accesses this account data
+ */
+ public SimpleAccount(Collection principals, Object credentials, String realmName) {
+ this(new SimplePrincipalCollection(principals, realmName), credentials);
+ }
+
+ /**
+ * Constructs a SimpleAccount instance for the specified principals and credentials.
+ * @param principals the identifying attributes of the account, at least one of which should be considered the
+ * account's 'primary' identifying attribute, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ */
+ public SimpleAccount(PrincipalCollection principals, Object credentials) {
+ this.authcInfo = new SimpleAuthenticationInfo(principals, credentials);
+ this.authzInfo = new SimpleAuthorizationInfo();
+ }
+
+ /**
+ * Constructs a SimpleAccount instance for the specified principals and credentials, with the assigned roles.
+ *
+ * @param principals the identifying attributes of the account, at least one of which should be considered the
+ * account's 'primary' identifying attribute, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ * @param roles the names of the roles assigned to this account.
+ */
+ public SimpleAccount(PrincipalCollection principals, Object credentials, Set<String> roles) {
+ this.authcInfo = new SimpleAuthenticationInfo(principals, credentials);
+ this.authzInfo = new SimpleAuthorizationInfo(roles);
+ }
+
+ /**
+ * Constructs a SimpleAccount instance for the specified realm with the given principal and credentials, with the
+ * the assigned roles and permissions.
+ *
+ * @param principal the 'primary' identifying attributes of the account, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ * @param realmName the name of the realm that accesses this account data
+ * @param roleNames the names of the roles assigned to this account.
+ * @param permissions the permissions assigned to this account directly (not those assigned to any of the realms).
+ */
+ public SimpleAccount(Object principal, Object credentials, String realmName, Set<String> roleNames, Set<Permission> permissions) {
+ this.authcInfo = new SimpleAuthenticationInfo(new SimplePrincipalCollection(principal, realmName), credentials);
+ this.authzInfo = new SimpleAuthorizationInfo(roleNames);
+ this.authzInfo.setObjectPermissions(permissions);
+ }
+
+ /**
+ * Constructs a SimpleAccount instance for the specified realm with the given principals and credentials, with the
+ * the assigned roles and permissions.
+ *
+ * @param principals the identifying attributes of the account, at least one of which should be considered the
+ * account's 'primary' identifying attribute, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ * @param realmName the name of the realm that accesses this account data
+ * @param roleNames the names of the roles assigned to this account.
+ * @param permissions the permissions assigned to this account directly (not those assigned to any of the realms).
+ */
+ public SimpleAccount(Collection principals, Object credentials, String realmName, Set<String> roleNames, Set<Permission> permissions) {
+ this.authcInfo = new SimpleAuthenticationInfo(new SimplePrincipalCollection(principals, realmName), credentials);
+ this.authzInfo = new SimpleAuthorizationInfo(roleNames);
+ this.authzInfo.setObjectPermissions(permissions);
+ }
+
+ /**
+ * Constructs a SimpleAccount instance from the given principals and credentials, with the
+ * the assigned roles and permissions.
+ *
+ * @param principals the identifying attributes of the account, at least one of which should be considered the
+ * account's 'primary' identifying attribute, for example, a user id or username.
+ * @param credentials the credentials that verify identity for the account
+ * @param roleNames the names of the roles assigned to this account.
+ * @param permissions the permissions assigned to this account directly (not those assigned to any of the realms).
+ */
+ public SimpleAccount(PrincipalCollection principals, Object credentials, Set<String> roleNames, Set<Permission> permissions) {
+ this.authcInfo = new SimpleAuthenticationInfo(principals, credentials);
+ this.authzInfo = new SimpleAuthorizationInfo(roleNames);
+ this.authzInfo.setObjectPermissions(permissions);
+ }
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+
+ /**
+ * Returns the principals, aka the identifying attributes (username, user id, first name, last name, etc) of this
+ * Account.
+ * <p/>
+ * At least one of these attributes should be the account's 'primary' identifier, such as a username or unique
+ * user id. By convention, usually the first principal (that is, <code>principals.iterator().next()</code>) is the
+ * 'primary' one.
+ *
+ * @return all the principals, aka the identifying attributes, of this Account.
+ */
+ public PrincipalCollection getPrincipals() {
+ return authcInfo.getPrincipals();
+ }
+
+ /**
+ * Sets the principals, aka the identifying attributes (username, user id, first name, last name, etc) of this
+ * Account.
+ * <p/>
+ * At least one of these attributes should be the account's 'primary' identifier, such as a username or unique
+ * user id. By convention, usually the first principal (that is, <code>principals.iterator().next()</code>) is the
+ * 'primary' one.
+ * @param principals all the principals, aka the identifying attributes, of this Account.
+ * @see Account#getPrincipals()
+ */
+ public void setPrincipals(PrincipalCollection principals) {
+ this.authcInfo.setPrincipals(principals);
+ }
+
+
+ /**
+ * Simply returns <code>this.authcInfo.getCredentials</code>. The <code>authcInfo</code> attribute is constructed
+ * via the constructors to wrap the input arguments.
+ *
+ * @return this Account's credentials.
+ */
+ public Object getCredentials() {
+ return authcInfo.getCredentials();
+ }
+
+ /**
+ * Sets this Account's credentials that verify one or more of the Account's
+ * {@link #getPrincipals() principals}, such as a password or private key.
+ *
+ * @param credentials the credentials associated with this Account that verify one or more of the Account principals.
+ * @see Account#getCredentials()
+ */
+ public void setCredentials(Object credentials) {
+ this.authcInfo.setCredentials(credentials);
+ }
+
+ /**
+ * Returns <code>this.authzInfo.getRoles();</code>
+ * @return the Account's assigned roles.
+ */
+ public Collection<String> getRoles() {
+ return authzInfo.getRoles();
+ }
+
+ /**
+ * Sets the Account's assigned roles. Simply calls <code>this.authzInfo.setRoles(roles)</code>.
+ *
+ * @param roles the Account's assigned roles.
+ * @see Account#getRoles()
+ */
+ public void setRoles(Set<String> roles) {
+ this.authzInfo.setRoles(roles);
+ }
+
+ /**
+ * Adds a role to this Account's set of assigned roles. Simply delegates to
+ * <code>this.authzInfo.addRole(role)</code>.
+ *
+ * @param role a role to assign to this Account.
+ */
+ public void addRole(String role) {
+ this.authzInfo.addRole(role);
+ }
+
+ /**
+ * Adds one or more roles to this Account's set of assigned roles. Simply delegates to
+ * <code>this.authzInfo.addRoles(roles)</code>.
+ *
+ * @param roles one or more roles to assign to this Account.
+ */
+ public void addRole(Collection<String> roles) {
+ this.authzInfo.addRoles(roles);
+ }
+
+ /**
+ * Returns all String-based permissions assigned to this Account. Simply delegates to
+ * <code>this.authzInfo.getStringPermissions()</code>.
+ * @return all String-based permissions assigned to this Account.
+ */
+ public Collection<String> getStringPermissions() {
+ return authzInfo.getStringPermissions();
+ }
+
+ /**
+ * Sets the String-based permissions assigned to this Account. Simply delegates to
+ * <code>this.authzInfo.setStringPermissions(permissions)</code>.
+ * @param permissions all String-based permissions assigned to this Account.
+ * @see Account#getStringPermissions()
+ */
+ public void setStringPermissions(Set<String> permissions) {
+ this.authzInfo.setStringPermissions(permissions);
+ }
+
+ /**
+ * Assigns a String-based permission directly to this Account (not to any of its realms).
+ * @param permission the String-based permission to assign.
+ */
+ public void addStringPermission(String permission) {
+ this.authzInfo.addStringPermission(permission);
+ }
+
+ /**
+ * Assigns one or more string-based permissions directly to this Account (not to any of its realms).
+ * @param permissions one or more String-based permissions to assign.
+ */
+ public void addStringPermissions(Collection<String> permissions) {
+ this.authzInfo.addStringPermissions(permissions);
+ }
+
+ /**
+ * Returns all object-based permissions assigned directly to this Account (not any of its realms).
+ * @return all object-based permissions assigned directly to this Account (not any of its realms).
+ */
+ public Collection<Permission> getObjectPermissions() {
+ return authzInfo.getObjectPermissions();
+ }
+
+ /**
+ * Sets all object-based permissions assigned directly to this Account (not any of its realms).
+ * @param permissions the object-based permissions to assign directly to this Account.
+ */
+ public void setObjectPermissions(Set<Permission> permissions) {
+ this.authzInfo.setObjectPermissions(permissions);
+ }
+
+ /**
+ * Assigns an object-based permission directly to this Account (not any of its realms).
+ * @param permission the object-based permission to assign directly to this Account (not any of its realms).
+ */
+ public void addObjectPermission(Permission permission) {
+ this.authzInfo.addObjectPermission(permission);
+ }
+
+ /**
+ * Assigns one or more object-based permissions directly to this Account (not any of its realms).
+ * @param permissions one or more object-based permissions to assign directly to this Account (not any of its realms).
+ */
+ public void addObjectPermissions(Collection<Permission> permissions) {
+ this.authzInfo.addObjectPermissions(permissions);
+ }
+
+ /**
+ * Returns <code>true</code> if this Account is locked and thus cannot be used to login, <code>false</code> otherwise.
+ * @return <code>true</code> if this Account is locked and thus cannot be used to login, <code>false</code> otherwise.
+ */
+ public boolean isLocked() {
+ return locked;
+ }
+
+ /**
+ * Sets whether or not the account is locked and can be used to login.
+ * @param locked <code>true</code> if this Account is locked and thus cannot be used to login, <code>false</code> otherwise.
+ */
+ public void setLocked(boolean locked) {
+ this.locked = locked;
+ }
+
+ /**
+ * Returns whether or not the Account's credentials are expired. This usually indicates that the Subject or an application
+ * administrator would need to change the credentials before the account could be used.
+ * @return whether or not the Account's credentials are expired.
+ */
+ public boolean isCredentialsExpired() {
+ return credentialsExpired;
+ }
+
+ /**
+ * Sets whether or not the Account's credentials are expired. A <code>true</code> value indicates that the Subject
+ * or application administrator would need to change their credentials before the account could be used.
+ * @param credentialsExpired <code>true</code> if this Account's credentials are expired and need to be changed,
+ * <code>false</code> otherwise.
+ */
+ public void setCredentialsExpired(boolean credentialsExpired) {
+ this.credentialsExpired = credentialsExpired;
+ }
+
+
+ /**
+ * Merges the specified <code>AuthenticationInfo</code> into this <code>Account</code>.
+ * <p/>
+ * If the specified argument is also an instance of {@link SimpleAccount SimpleAccount}, the
+ * {@link #isLocked()} and {@link #isCredentialsExpired()} attributes are merged (set on this instance) as well
+ * (only if their values are <code>true</code>).
+ *
+ * @param info the <code>AuthenticationInfo</code> to merge into this account.
+ */
+ public void merge(AuthenticationInfo info) {
+ authcInfo.merge(info);
+
+ // Merge SimpleAccount specific info
+ if (info instanceof SimpleAccount) {
+ SimpleAccount otherAccount = (SimpleAccount) info;
+ if (otherAccount.isLocked()) {
+ setLocked(true);
+ }
+
+ if (otherAccount.isCredentialsExpired()) {
+ setCredentialsExpired(true);
+ }
+ }
+ }
+
+ /**
+ * If the {@link #getPrincipals() principals} are not null, returns <code>principals.hashCode()</code>, otherwise
+ * returns 0 (zero).
+ * @return <code>principals.hashCode()</code> if they are not null, 0 (zero) otherwise.
+ */
+ public int hashCode() {
+ return (getPrincipals() != null ? getPrincipals().hashCode() : 0);
+ }
+
+ /**
+ * Returns <code>true</code> if the specified object is also a {@link SimpleAccount SimpleAccount} and its
+ * {@link #getPrincipals() principals} are equal to this object's <code>principals</code>, <code>false</code> otherwise.
+ * @param o the object to test for equality.
+ * @return <code>true</code> if the specified object is also a {@link SimpleAccount SimpleAccount} and its
+ * {@link #getPrincipals() principals} are equal to this object's <code>principals</code>, <code>false</code> otherwise.
+ */
+ public boolean equals(Object o) {
+ if (o == this) {
+ return true;
+ }
+ if (o instanceof SimpleAccount) {
+ SimpleAccount sa = (SimpleAccount) o;
+ //principal should be unique across the application, so only check this for equality:
+ return (getPrincipals() != null ? getPrincipals().equals(sa.getPrincipals()) : sa.getPrincipals() == null);
+ }
+ return false;
+ }
+
+ /**
+ * Returns {@link #getPrincipals() principals}.toString() if they are not null, otherwise prints out the string
+ * "empty"
+ * @return the String representation of this Account object.
+ */
+ public String toString() {
+ return getPrincipals() != null ? getPrincipals().toString() : "empty";
+ }
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authc/UnknownAccountException.java b/core/src/org/jsecurity/authc/UnknownAccountException.java
new file mode 100644
index 0000000..35869bb
--- /dev/null
+++ b/core/src/org/jsecurity/authc/UnknownAccountException.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+/**
+ * Thrown when attempting to authenticate with a principal that doesn't exist in the system (e.g.
+ * by specifying a username that doesn't relate to a user account).
+ *
+ * <p>Whether or not an application wishes to alert a user logging in to the system of this fact is
+ * at the discretion of those responsible for designing the view and what happens when this
+ * exception occurs.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class UnknownAccountException extends AccountException {
+
+ /**
+ * Creates a new UnknownAccountException.
+ */
+ public UnknownAccountException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnknownAccountException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnknownAccountException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnknownAccountException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownAccountException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnknownAccountException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownAccountException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/UsernamePasswordToken.java b/core/src/org/jsecurity/authc/UsernamePasswordToken.java
new file mode 100644
index 0000000..20bb241
--- /dev/null
+++ b/core/src/org/jsecurity/authc/UsernamePasswordToken.java
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc;
+
+import java.net.InetAddress;
+
+/**
+ * <p>A simple username/password authentication token to support the most widely-used authentication mechanism. This
+ * class also implements the {@link RememberMeAuthenticationToken RememberMeAuthenticationToken} interface to support
+ * "Remember Me" services across user sessions as well as the
+ * {@link InetAuthenticationToken InetAuthenticationToken} interface to retain the IP address location from where the
+ * authentication attempt is occuring.</p>
+ *
+ * <p>"Remember Me" authentications are disabled by default, but if the application developer wishes to allow
+ * it for a login attempt, all that is necessary is to call {@link #setRememberMe setRememberMe(true)}. If the underlying
+ * <tt>SecurityManager</tt> implementation also supports <tt>RememberMe</tt> services, the user's identity will be
+ * remembered across sessions.
+ *
+ * <p>Note that this class stores a password as a char[] instead of a String
+ * (which may seem more logical). This is because Strings are immutable and their
+ * internal value cannot be overwritten - meaning even a nulled String instance might be accessible in memory at a later
+ * time (e.g. memory dump). This is not good for sensitive information such as passwords. For more information, see the
+ * <a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#PBEEx">
+ * Java Cryptography Extension Reference Guide</a>.</p>
+ *
+ * <p>To avoid this possibility of later memory access, the application developer should always call
+ * {@link #clear() clear()} after using the token to perform a login attempt.</p>
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class UsernamePasswordToken implements InetAuthenticationToken, RememberMeAuthenticationToken {
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ /** The username */
+ private String username;
+
+ /** The password, in char[] format */
+ private char[] password;
+
+ /**
+ * Whether or not 'rememberMe' should be enabled for the corresponding login attempt;
+ * default is <code>false</code> */
+ private boolean rememberMe = false;
+
+ /**
+ * The location from where the login attempt occurs, or <code>null</code> if not known or explicitly
+ * omitted.
+ */
+ private InetAddress inetAddress;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+
+ /**
+ * JavaBeans compatible no-arg constructor.
+ */
+ public UsernamePasswordToken() {
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted
+ * during an authentication attempt, with a <tt>null</tt> {@link #getInetAddress() inetAddress} and a
+ * <tt>rememberMe</tt> default of <tt>false</tt>.
+ *
+ * @param username the username submitted for authentication
+ * @param password the password character array submitted for authentication
+ */
+ public UsernamePasswordToken(final String username, final char[] password) {
+ this(username, password, false, null);
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted
+ * during an authentication attempt, with a <tt>null</tt> {@link #getInetAddress() inetAddress} and
+ * a <tt>rememberMe</tt> default of <tt>false</tt>
+ *
+ * <p>This is a convience constructor and maintains the password internally via a character
+ * array, i.e. <tt>password.toCharArray();</tt>. Note that storing a password as a String
+ * in your code could have possible security implications as noted in the class JavaDoc.</p>
+ *
+ * @param username the username submitted for authentication
+ * @param password the password string submitted for authentication
+ */
+ public UsernamePasswordToken(final String username, final String password) {
+ this(username, password != null ? password.toCharArray() : null, false, null);
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted, the
+ * inetAddress from where the attempt is occurring, and a default <tt>rememberMe</tt> value of <tt>false</tt>
+ *
+ * @param username the username submitted for authentication
+ * @param password the password string submitted for authentication
+ * @param inetAddress the inetAddress from where the attempt is occuring
+ * @since 0.2
+ */
+ public UsernamePasswordToken(final String username, final char[] password, final InetAddress inetAddress) {
+ this(username, password, false, inetAddress);
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted, the
+ * inetAddress from where the attempt is occurring, and a default <tt>rememberMe</tt> value of <tt>false</tt>
+ *
+ * <p>This is a convience constructor and maintains the password internally via a character
+ * array, i.e. <tt>password.toCharArray();</tt>. Note that storing a password as a String
+ * in your code could have possible security implications as noted in the class JavaDoc.</p>
+ *
+ * @param username the username submitted for authentication
+ * @param password the password string submitted for authentication
+ * @param inetAddress the inetAddress from where the attempt is occuring
+ * @since 0.2
+ */
+ public UsernamePasswordToken(final String username, final String password, final InetAddress inetAddress) {
+ this(username, password != null ? password.toCharArray() : null, false, inetAddress);
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted, as well as if the user
+ * wishes their identity to be remembered across sessions.
+ *
+ * @param username the username submitted for authentication
+ * @param password the password string submitted for authentication
+ * @param rememberMe if the user wishes their identity to be remembered across sessions
+ * @since 0.9
+ */
+ public UsernamePasswordToken(final String username, final char[] password, final boolean rememberMe) {
+ this(username, password, rememberMe, null);
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted, as well as if the user
+ * wishes their identity to be remembered across sessions.
+ *
+ * <p>This is a convience constructor and maintains the password internally via a character
+ * array, i.e. <tt>password.toCharArray();</tt>. Note that storing a password as a String
+ * in your code could have possible security implications as noted in the class JavaDoc.</p>
+ *
+ * @param username the username submitted for authentication
+ * @param password the password string submitted for authentication
+ * @param rememberMe if the user wishes their identity to be remembered across sessions
+ * @since 0.9
+ */
+ public UsernamePasswordToken(final String username, final String password, final boolean rememberMe) {
+ this(username, password != null ? password.toCharArray() : null, rememberMe, null);
+ }
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted, if the user
+ * wishes their identity to be remembered across sessions, and the inetAddress from where the attempt is ocurring.
+ *
+ * @param username the username submitted for authentication
+ * @param password the password character array submitted for authentication
+ * @param rememberMe if the user wishes their identity to be remembered across sessions
+ * @param inetAddress the inetAddress from where the attempt is occuring
+ * @since 0.9
+ */
+ public UsernamePasswordToken(final String username, final char[] password,
+ final boolean rememberMe, final InetAddress inetAddress) {
+
+ this.username = username;
+ this.password = password;
+ this.rememberMe = rememberMe;
+ this.inetAddress = inetAddress;
+ }
+
+
+ /**
+ * Constructs a new UsernamePasswordToken encapsulating the username and password submitted, if the user
+ * wishes their identity to be remembered across sessions, and the inetAddress from where the attempt is ocurring.
+ *
+ * <p>This is a convience constructor and maintains the password internally via a character
+ * array, i.e. <tt>password.toCharArray();</tt>. Note that storing a password as a String
+ * in your code could have possible security implications as noted in the class JavaDoc.</p>
+ *
+ * @param username the username submitted for authentication
+ * @param password the password string submitted for authentication
+ * @param rememberMe if the user wishes their identity to be remembered across sessions
+ * @param inetAddress the inetAddress from where the attempt is occuring
+ * @since 0.9
+ */
+ public UsernamePasswordToken(final String username, final String password,
+ final boolean rememberMe, final InetAddress inetAddress) {
+ this(username, password != null ? password.toCharArray() : null, rememberMe, inetAddress);
+ }
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+
+ /**
+ * Returns the username submitted during an authentication attempt.
+ *
+ * @return the username submitted during an authentication attempt.
+ */
+ public String getUsername() {
+ return username;
+ }
+
+ /**
+ * Sets the username for submission during an authentication attempt.
+ *
+ * @param username the username to be used for submission during an authentication attempt.
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+
+ /**
+ * Returns the password submitted during an authentication attempt as a character array.
+ *
+ * @return the password submitted during an authentication attempt as a character array.
+ */
+ public char[] getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the password for submission during an authentication attempt.
+ *
+ * @param password the password to be used for submission during an authentication attemp.
+ */
+ public void setPassword(char[] password) {
+ this.password = password;
+ }
+
+ /**
+ * Simply returns {@link #getUsername() getUsername()}.
+ *
+ * @return the {@link #getUsername() username}.
+ * @see org.jsecurity.authc.AuthenticationToken#getPrincipal()
+ */
+ public Object getPrincipal() {
+ return getUsername();
+ }
+
+ /**
+ * Returns the {@link #getPassword() password} char array.
+ *
+ * @return the {@link #getPassword() password} char array.
+ * @see org.jsecurity.authc.AuthenticationToken#getCredentials()
+ */
+ public Object getCredentials() {
+ return getPassword();
+ }
+
+ /**
+ * Returns the inetAddress from where the authentication attempt occurs. May be <tt>null</tt> if the inetAddress
+ * is unknown or explicitly omitted. It is up to the Authenticator implementation processing this token if
+ * an authentication attempt without an inetAddress is valid or not.
+ *
+ * <p>(JSecurity's default Authenticator
+ * allows <tt>null</tt> IPs to support localhost and proxy server environments).</p>
+ *
+ * @return the inetAddress from where the authentication attempt occurs, or <tt>null</tt> if it is unknown or
+ * explicitly omitted.
+ * @since 0.2
+ */
+ public InetAddress getInetAddress() {
+ return inetAddress;
+ }
+
+ /**
+ * Sets the inetAddress from where the authentication attempt occurs. It is up to the Authenticator
+ * implementation processing this token if an authentication attempt without an inetAddress is valid or not.
+ *
+ * <p>(JSecurity's default Authenticator
+ * allows <tt>null</tt> IPs to allow localhost and proxy server environments).</p>
+ *
+ * @param inetAddress the inetAddress from where the authentication attempt occurs.
+ * @since 0.2
+ */
+ public void setInetAddress(InetAddress inetAddress) {
+ this.inetAddress = inetAddress;
+ }
+
+ /**
+ * Returns <tt>true</tt> if the submitting user wishes their identity (principal(s)) to be remembered
+ * across sessions, <tt>false</tt> otherwise. Unless overridden, this value is <tt>false</tt> by default.
+ *
+ * @return <tt>true</tt> if the submitting user wishes their identity (principal(s)) to be remembered
+ * across sessions, <tt>false</tt> otherwise (<tt>false</tt> by default).
+ * @since 0.9
+ */
+ public boolean isRememberMe() {
+ return rememberMe;
+ }
+
+ /**
+ * Sets if the submitting user wishes their identity (pricipal(s)) to be remembered across sessions. Unless
+ * overridden, the default value is <tt>false</tt>, indicating <em>not</em> to be remembered across sessions.
+ *
+ * @param rememberMe value inidicating if the user wishes their identity (principal(s)) to be remembered across
+ * sessions.
+ * @since 0.9
+ */
+ public void setRememberMe(boolean rememberMe) {
+ this.rememberMe = rememberMe;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+
+ /**
+ * Clears out (nulls) the username, password, rememberMe, and inetAddress. The password bytes are explicitly set to
+ * <tt>0x00</tt> before nulling to eliminate the possibility of memory access at a later time.
+ */
+ public void clear() {
+ this.username = null;
+ this.inetAddress = null;
+ this.rememberMe = false;
+
+ if (this.password != null) {
+ for (int i = 0; i < password.length; i++) {
+ this.password[i] = 0x00;
+ }
+ this.password = null;
+ }
+
+ }
+
+ /**
+ * Returns the String representation. It does not include the password in the resulting
+ * string for security reasons to prevent accidentially printing out a password
+ * that might be widely viewable).
+ *
+ * @return the String representation of the <tt>UsernamePasswordToken</tt>, omitting
+ * the password.
+ */
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append(getClass().getName());
+ sb.append(" - ");
+ sb.append(username);
+ sb.append(", rememberMe=").append(rememberMe);
+ if (inetAddress != null) {
+ sb.append(" (").append(inetAddress).append(")");
+ }
+ return sb.toString();
+ }
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authc/credential/AllowAllCredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/AllowAllCredentialsMatcher.java
new file mode 100644
index 0000000..2b2c3ed
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/AllowAllCredentialsMatcher.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+
+/**
+ * A credentials matcher that always returns <tt>true</tt> when matching credentials no matter what arguments
+ * are passed in. This can be used for testing or when credentials are implicitly trusted for a particular
+ * {@link org.jsecurity.realm.Realm Realm}.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class AllowAllCredentialsMatcher implements CredentialsMatcher {
+
+ /**
+ * Returns <code>true</code> <em>always</em> no matter what the method arguments are.
+ *
+ * @param token the token submitted for authentication.
+ * @param info the account being verified for access
+ * @return <code>true</code> <em>always</em>.
+ */
+ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
+ return true;
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/CredentialsMatcher.java
new file mode 100644
index 0000000..9eb5486
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/CredentialsMatcher.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+
+/**
+ * Interface implemented by classes that can determine if an AuthenticationToken's provided
+ * credentials matches a corresponding account's credentials stored in the system.
+ *
+ * <p>Simple direct comparisons are handled well by the
+ * {@link org.jsecurity.authc.credential.SimpleCredentialsMatcher SimpleCredentialsMatcher}. If you
+ * hash user's credentials before storing them in a realm (a common practice), look at the
+ * {@link org.jsecurity.authc.credential.HashedCredentialsMatcher HashedCredentialsMatcher} implementations,
+ * as they support this scenario.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see SimpleCredentialsMatcher
+ * @see AllowAllCredentialsMatcher
+ * @see Md5CredentialsMatcher
+ * @see Sha1CredentialsMatcher
+ * @since 0.1
+ */
+public interface CredentialsMatcher {
+
+ /**
+ * Returns <tt>true</tt> if the provided token credentials match the stored account credentials,
+ * <tt>false</tt> otherwise.
+ *
+ * @param token the <tt>AuthenticationToken</tt> submitted during the authentication attempt
+ * @param info the <tt>AuthenticationInfo</tt> stored in the system.
+ * @return <tt>true</tt> if the provided token credentials match the stored account credentials,
+ * <tt>false</tt> otherwise.
+ */
+ boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authc/credential/HashedCredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/HashedCredentialsMatcher.java
new file mode 100644
index 0000000..c9d1209
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/HashedCredentialsMatcher.java
@@ -0,0 +1,272 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+
+/**
+ * A <tt>HashedCredentialMatcher</tt> provides support for hashing of supplied <tt>AuthenticationToken</tt> credentials
+ * before being compared to those in the <tt>AuthenticationInfo</tt> from the data store.
+ *
+ * <p>Credential hashing is one of the most common security techniques when safeguarding a user's private credentials
+ * (passwords, keys, etc). Most developers never want to store their users' credentials in plain form, viewable by
+ * anyone, so they often hash the users' credentials before they are saved in the data store.</p>
+ *
+ * <p>This class (and its subclasses) function as follows:</p>
+ *
+ * <p>It first hashes the <tt>AuthenticationToken</tt> credentials supplied by the user during their login. It then
+ * compares this hashed value directly with the <tt>AuthenticationInfo</tt> credentials stored in the system. The stored account
+ * credentials are expected to already be in hashed form. If these two values are equal, the submitted credentials
+ * match.</p>
+ *
+ * <h3>Salting and Multiple Hash Iterations</h3>
+ *
+ * <p>Because simple hashing is sometimes not good enough for many applications, this class also supports 'salting'
+ * and multiple hash iterations. Please read this excellent
+ * <a href="http://www.owasp.org/index.php/Hashing_Java" _target="blank">Hashing Java article</a> to learn about
+ * salting and multiple iterations and why you might want to use them. (Note of sections 5
+ * "Why add salt?" and 6 "Hardening against the attacker's attack").
+ *
+ * <p>We should also note here that all of JSecurity's Hash implementations (for example,
+ * {@link org.jsecurity.crypto.hash.Md5Hash Md5Hash}, {@link org.jsecurity.crypto.hash.Sha1Hash Sha1Hash}, etc)
+ * support salting and multiple hash iterations via overloaded constructors.</p>
+ *
+ * <h4>Salting</h4>
+ *
+ * <p>Salting of the authentication token's credentials hash is disabled by default, but you may enable it by setting
+ * {@link #setHashSalted hashSalted} to
+ * <tt>true</tt>. If you do enable it, the value used to salt the hash will be
+ * obtained from {@link #getSalt(AuthenticationToken) getSalt(authenticationToken)}.
+ *
+ * <p>The default <tt>getSalt</tt> implementation merely returns
+ * <code>token.getPrincipal()</code>, effectively using the user's identity as the salt, a most common
+ * technique. If you wish to provide the authentication token's salt another way, you may override this
+ * <tt>getSalt</tt> method.
+ *
+ * <h4>Multiple Hash Iterations</h4>
+ *
+ * <p>If you hash your users' credentials multiple times before persisting to the data store, you will also need to
+ * set this class's {@link #setHashIterations(int) hashIterations} property.</p>
+ *
+ * <p><b>Note:</b> <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> and
+ * <a href="http://en.wikipedia.org/wiki/SHA_hash_functions">SHA-1</a> algorithms are now known to be vulnerable to
+ * compromise and/or collisions (read the linked pages for more). While most applications are ok with either of these
+ * two, if your application mandates high security, use the SHA-256 (or higher) hashing algorithms and their
+ * supporting <code>CredentialsMatcher</code> implementations.</p>
+ *
+ * @author Les Hazlewood
+ * @see org.jsecurity.crypto.hash.Md5Hash
+ * @see org.jsecurity.crypto.hash.Sha1Hash
+ * @see org.jsecurity.crypto.hash.Sha256Hash
+ * @since 0.9
+ */
+public abstract class HashedCredentialsMatcher extends SimpleCredentialsMatcher {
+
+ private boolean storedCredentialsHexEncoded = true; //false means base64 encoded
+ private boolean hashSalted = false;
+ private int hashIterations = 1;
+
+ /**
+ * Returns <tt>true</tt> if the system's stored credential hash is Hex encoded, <tt>false</tt> if it
+ * is Base64 encoded.
+ *
+ * <p>Default value is <tt>true</tt> for convenience - all of JSecurity's {@link Hash Hash#toString()}
+ * implementations return Hex encoded values by default, making this class's use with those implementations
+ * easier.</p>
+ *
+ * @return <tt>true</tt> if the system's stored credential hash is Hex encoded, <tt>false</tt> if it
+ * is Base64 encoded. Default is <tt>true</tt>
+ */
+ public boolean isStoredCredentialsHexEncoded() {
+ return storedCredentialsHexEncoded;
+ }
+
+ /**
+ * Sets the indicator if this system's stored credential hash is Hex encoded or not.
+ *
+ * <p>A value of <tt>true</tt> will cause this class to decode the system credential from Hex, a
+ * value of <tt>false</tt> will cause this class to decode the system credential from Base64.</p>
+ *
+ * <p>Unless overridden via this method, the default value is <tt>true</tt> for convenience - all of JSecurity's
+ * {@link Hash Hash#toString()} implementations return Hex encoded values by default, making this class's use with
+ * those implementations easier.</p>.
+ *
+ * @param storedCredentialsHexEncoded the indicator if this system's stored credential hash is Hex
+ * encoded or not ('not' automatically implying it is Base64 encoded).
+ */
+ public void setStoredCredentialsHexEncoded(boolean storedCredentialsHexEncoded) {
+ this.storedCredentialsHexEncoded = storedCredentialsHexEncoded;
+ }
+
+ /**
+ * Returns <tt>true</tt> if a submitted <tt>AuthenticationToken</tt>'s credentials should be salted when hashing,
+ * <tt>false</tt> if it should not be salted.
+ *
+ * <p>If enabled, the salt used will be obtained via the {@link #getSalt(AuthenticationToken) getSalt} method.
+ *
+ * <p>The default value is <tt>false</tt>.
+ *
+ * @return <tt>true</tt> if a submitted <tt>AuthenticationToken</tt>'s credentials should be salted when hashing,
+ * <tt>false</tt> if it should not be salted.
+ */
+ public boolean isHashSalted() {
+ return hashSalted;
+ }
+
+ /**
+ * Sets whether or not to salt a submitted <tt>AuthenticationToken</tt>'s credentials when hashing.
+ *
+ * <p>If enabled, the salt used will be obtained via the {@link #getSalt(AuthenticationToken) getSalt} method.
+ *
+ * <p>The default value is <tt>false</tt>.
+ *
+ * @param hashSalted whether or not to salt a submitted <tt>AuthenticationToken</tt>'s credentials when hashing.
+ */
+ public void setHashSalted(boolean hashSalted) {
+ this.hashSalted = hashSalted;
+ }
+
+ /**
+ * Returns the number of times a submitted <tt>AuthenticationToken</tt>'s credentials will be hashed before
+ * comparing to the credentials stored in the system.
+ *
+ * <p>Unless overridden, the default value is <tt>1</tt>, meaning a normal hash execution will occur.
+ *
+ * @return the number of times a submitted <tt>AuthenticationToken</tt>'s credentials will be hashed before
+ * comparing to the credentials stored in the system.
+ */
+ public int getHashIterations() {
+ return hashIterations;
+ }
+
+ /**
+ * Sets the number of times a submitted <tt>AuthenticationToken</tt>'s credentials will be hashed before comparing
+ * to the credentials stored in the system.
+ *
+ * <p>Unless overridden, the default value is <tt>1</tt>, meaning a normal single hash execution will occur.
+ *
+ * <p>If this argument is less than 1 (i.e. 0 or negative), the default value of 1 is applied. There must always be
+ * at least 1 hash iteration (otherwise there would be no hash).
+ *
+ * @param hashIterations the number of times to hash a submitted <tt>AuthenticationToken</tt>'s credentials.
+ */
+ public void setHashIterations(int hashIterations) {
+ if (hashIterations < 1) {
+ this.hashIterations = 1;
+ } else {
+ this.hashIterations = hashIterations;
+ }
+ }
+
+ /**
+ * Returns a salt value used to hash the token's credentials.
+ *
+ * <p>This default implementation merely returns <code>token.getPrincipal()</code>, effectively using the user's
+ * identity (username, user id, etc) as the salt, a most common technique. If you wish to provide the
+ * authentication token's salt another way, you may override this method.
+ *
+ * @param token the AuthenticationToken submitted during the authentication attempt.
+ * @return a salt value to use to hash the authentication token's credentials.
+ */
+ protected Object getSalt(AuthenticationToken token) {
+ return token.getPrincipal();
+ }
+
+ /**
+ * As this is a HashedCredentialMatcher, this method overrides the parent method by returning a hashed value
+ * of the submitted token's credentials.
+ *
+ * <p>Based on this class's configuration, the return value may be salted and/or
+ * hashed multiple times (see the class-level JavaDoc for more information on salting and
+ * multiple hash iterations).
+ *
+ * @param token the authentication token submitted during the authentication attempt.
+ * @return the hashed value of the authentication token's credentials.
+ */
+ protected Object getCredentials(AuthenticationToken token) {
+ Object credentials = token.getCredentials();
+ Object salt = isHashSalted() ? getSalt(token) : null;
+ return hashProvidedCredentials(credentials, salt, getHashIterations());
+ }
+
+ /**
+ * Returns a {@link Hash Hash} instance representing the already-hashed AuthenticationInfo credentials stored in the system.
+ *
+ * <p>This method reconstructs a {@link Hash Hash} instance based on a <code>info.getCredentials</code> call,
+ * but it does <em>not</em> hash that value - it is expected that method call will return an already-hashed value.
+ *
+ * <p>This implementation's reconstruction effort functions as follows:
+ *
+ * <ol>
+ * <li>Convert <code>account.getCredentials()</code> to a byte array via the {@link #toBytes toBytes} method.
+ * <li>If <code>account.getCredentials()</code> was originally a String or char[] before <tt>toBytes</tt> was
+ * called, check for encoding:
+ * <li>If {@link #storedCredentialsHexEncoded storedCredentialsHexEncoded}, Hex decode that byte array, otherwise
+ * Base64 decode the byte array</li>
+ * <li>Set the byte[] array directly on the <tt>Hash</tt> implementation and return it.</li>
+ * </ol>
+ *
+ * @param info the AuthenticationInfo from which to retrive the credentials which assumed to be in already-hashed form.
+ * @return a {@link Hash Hash} instance representing the given AuthenticationInfo's stored credentials.
+ */
+ protected Object getCredentials(AuthenticationInfo info) {
+ Object credentials = info.getCredentials();
+
+ byte[] storedBytes = toBytes(credentials);
+
+ if (credentials instanceof String || credentials instanceof char[]) {
+ //account.credentials were a char[] or String, so
+ //we need to do text decoding first:
+ if (isStoredCredentialsHexEncoded()) {
+ storedBytes = Hex.decode(storedBytes);
+ } else {
+ storedBytes = Base64.decode(storedBytes);
+ }
+ }
+ AbstractHash hash = newHashInstance();
+ hash.setBytes(storedBytes);
+ return hash;
+ }
+
+ /**
+ * Hashes the provided credentials a total of <tt>hashIterations</tt> times, using the given salt. The hash
+ * implementation/algorithm used is left to subclasses.
+ *
+ * @param credentials the submitted authentication token's credentials to hash
+ * @param salt the value to salt the hash, or <tt>null</tt> if a salt will not be used.
+ * @param hashIterations the number of times to hash the credentials. At least one hash will always occur though,
+ * even if this argument is 0 or negative.
+ * @return the hashed value of the provided credentials, according to the specified salt and hash iterations.
+ */
+ protected abstract Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations);
+
+ /**
+ * Returns a new, <em>uninitialized</em> instance, without its byte array set. Used as a utility method in the
+ * {@link SimpleCredentialsMatcher#getCredentials(org.jsecurity.authc.AuthenticationInfo) getCredentials(AuthenticationInfo)} implementation.
+ *
+ * @return a new, <em>uninitialized</em> instance, without its byte array set.
+ */
+ protected abstract AbstractHash newHashInstance();
+
+}
diff --git a/core/src/org/jsecurity/authc/credential/Md2CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/Md2CredentialsMatcher.java
new file mode 100644
index 0000000..f12f629
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/Md2CredentialsMatcher.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+import org.jsecurity.crypto.hash.Md2Hash;
+
+/**
+ * <tt>HashedCredentialsMatcher</tt> implementation that expects the stored <tt>AuthenticationInfo</tt> credentials to be
+ * MD2 hashed.
+ *
+ * <p><b>Note:</b> the MD2, <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> and
+ * <a href="http://en.wikipedia.org/wiki/SHA_hash_functions">SHA-1</a> algorithms are now known to be vulnerable to
+ * compromise and/or collisions (read the linked pages for more). While most applications are ok with either of these
+ * two, if your application mandates high security, use the SHA-256 (or higher) hashing algorithms and their
+ * supporting <code>CredentialsMatcher</code> implementations.</p>
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Md2CredentialsMatcher extends HashedCredentialsMatcher {
+
+ /**
+ * Creates a new <em>uninitialized</em> {@link Md2Hash Md2Hash} instance, without it's byte array set.
+ *
+ * @return a new <em>uninitialized</em> {@link Md2Hash Md2Hash} instance, without it's byte array set.
+ */
+ protected AbstractHash newHashInstance() {
+ return new Md2Hash();
+ }
+
+ /**
+ * This implementation merely returns
+ * <code>new {@link Md2Hash#Md2Hash(Object, Object, int) Md2Hash(credentials,salt,hashIterations)}</code>.
+ */
+ protected Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations) {
+ return new Md2Hash(credentials, salt, hashIterations);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/Md5CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/Md5CredentialsMatcher.java
new file mode 100644
index 0000000..bc2fdb2
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/Md5CredentialsMatcher.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+import org.jsecurity.crypto.hash.Md5Hash;
+
+/**
+ * <tt>HashedCredentialsMatcher</tt> implementation that expects the stored <tt>AuthenticationInfo</tt> credentials to be
+ * MD5 hashed.
+ *
+ * <p><b>Note:</b> <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> and
+ * <a href="http://en.wikipedia.org/wiki/SHA_hash_functions">SHA-1</a> algorithms are now known to be vulnerable to
+ * compromise and/or collisions (read the linked pages for more). While most applications are ok with either of these
+ * two, if your application mandates high security, use the SHA-256 (or higher) hashing algorithms and their
+ * supporting <code>CredentialsMatcher</code> implementations.</p>
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Md5CredentialsMatcher extends HashedCredentialsMatcher {
+
+ /**
+ * Creates a new <em>uninitialized</em> {@link Md5Hash Md5Hash} instance, without it's byte array set.
+ *
+ * @return a new <em>uninitialized</em> {@link Md5Hash Md5Hash} instance, without it's byte array set.
+ */
+ protected AbstractHash newHashInstance() {
+ return new Md5Hash();
+ }
+
+ /**
+ * This implementation merely returns
+ * <code>new {@link Md5Hash#Md5Hash(Object, Object, int) Md5Hash(credentials,salt,hashIterations)}</code>.
+ */
+ protected Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations) {
+ return new Md5Hash(credentials, salt, hashIterations);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/Sha1CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/Sha1CredentialsMatcher.java
new file mode 100644
index 0000000..d7c7b84
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/Sha1CredentialsMatcher.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+import org.jsecurity.crypto.hash.Sha1Hash;
+
+/**
+ * <tt>HashedCredentialsMatcher</tt> implementation that expects the stored <tt>AuthenticationInfo</tt> credentials to be
+ * SHA hashed.
+ *
+ * <p><b>Note:</b> <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> and
+ * <a href="http://en.wikipedia.org/wiki/SHA_hash_functions">SHA-1</a> algorithms are now known to be vulnerable to
+ * compromise and/or collisions (read the linked pages for more). While most applications are ok with either of these
+ * two, if your application mandates high security, use the SHA-256 (or higher) hashing algorithms and their
+ * supporting <code>CredentialsMatcher</code> implementations.</p>
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha1CredentialsMatcher extends HashedCredentialsMatcher {
+
+ /**
+ * Creates a new <em>uninitialized</em> {@link Sha1Hash Sha1Hash} instance, without it's byte array set.
+ *
+ * @return a new <em>uninitialized</em> {@link Sha1Hash Sha1Hash} instance, without it's byte array set.
+ */
+ protected AbstractHash newHashInstance() {
+ return new Sha1Hash();
+ }
+
+ /**
+ * This implementation merely returns
+ * <code>new {@link Sha1Hash#Sha1Hash(Object, Object, int) Sha1Hash(credentials,salt,hashIterations)}</code>.
+ */
+ protected Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations) {
+ return new Sha1Hash(credentials, salt, hashIterations);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/Sha256CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/Sha256CredentialsMatcher.java
new file mode 100644
index 0000000..4cb1df8
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/Sha256CredentialsMatcher.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+import org.jsecurity.crypto.hash.Sha256Hash;
+
+/**
+ * <tt>HashedCredentialsMatcher</tt> implementation that expects the stored <tt>AuthenticationInfo</tt> credentials to be
+ * SHA-256 hashed.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha256CredentialsMatcher extends HashedCredentialsMatcher {
+
+ /**
+ * Creates a new <em>uninitialized</em> {@link Sha256Hash Sha256Hash} instance, without it's byte array set.
+ *
+ * @return a new <em>uninitialized</em> {@link Sha256Hash Sha256Hash} instance, without it's byte array set.
+ */
+ protected AbstractHash newHashInstance() {
+ return new Sha256Hash();
+ }
+
+ /**
+ * This implementation merely returns
+ * <code>new {@link Sha256Hash#Sha256Hash(Object, Object, int) Sha256Hash(credentials,salt,hashIterations)}</code>.
+ */
+ protected Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations) {
+ return new Sha256Hash(credentials, salt, hashIterations);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/Sha384CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/Sha384CredentialsMatcher.java
new file mode 100644
index 0000000..40ea703
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/Sha384CredentialsMatcher.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+import org.jsecurity.crypto.hash.Sha384Hash;
+
+/**
+ * <tt>HashedCredentialsMatcher</tt> implementation that expects the stored <tt>AuthenticationInfo</tt> credentials to be
+ * SHA-384 hashed.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha384CredentialsMatcher extends HashedCredentialsMatcher {
+
+ /**
+ * Creates a new <em>uninitialized</em> {@link Sha384Hash Sha384Hash} instance, without it's byte array set.
+ *
+ * @return a new <em>uninitialized</em> {@link Sha384Hash Sha384Hash} instance, without it's byte array set.
+ */
+ protected AbstractHash newHashInstance() {
+ return new Sha384Hash();
+ }
+
+ /**
+ * This implementation merely returns
+ * <code>new {@link Sha384Hash#Sha384Hash(Object, Object, int) Sha384Hash(credentials,salt,hashIterations)}</code>.
+ */
+ protected Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations) {
+ return new Sha384Hash(credentials, salt, hashIterations);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/Sha512CredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/Sha512CredentialsMatcher.java
new file mode 100644
index 0000000..0205386
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/Sha512CredentialsMatcher.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.jsecurity.crypto.hash.AbstractHash;
+import org.jsecurity.crypto.hash.Hash;
+import org.jsecurity.crypto.hash.Sha512Hash;
+
+/**
+ * <tt>HashedCredentialsMatcher</tt> implementation that expects the stored <tt>AuthenticationInfo</tt> credentials to be
+ * SHA-512 hashed.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha512CredentialsMatcher extends HashedCredentialsMatcher {
+
+ /**
+ * Creates a new <em>uninitialized</em> {@link Sha512Hash Sha512Hash} instance, without it's byte array set.
+ *
+ * @return a new <em>uninitialized</em> {@link Sha512Hash Sha512Hash} instance, without it's byte array set.
+ */
+ protected AbstractHash newHashInstance() {
+ return new Sha512Hash();
+ }
+
+ /**
+ * This implementation merely returns
+ * <code>new {@link Sha512Hash#Sha512Hash(Object, Object, int) Sha512Hash(credentials,salt,hashIterations)}</code>.
+ */
+ protected Hash hashProvidedCredentials(Object credentials, Object salt, int hashIterations) {
+ return new Sha512Hash(credentials, salt, hashIterations);
+ }
+}
diff --git a/core/src/org/jsecurity/authc/credential/SimpleCredentialsMatcher.java b/core/src/org/jsecurity/authc/credential/SimpleCredentialsMatcher.java
new file mode 100644
index 0000000..196fb1b
--- /dev/null
+++ b/core/src/org/jsecurity/authc/credential/SimpleCredentialsMatcher.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.credential;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.codec.CodecSupport;
+
+import java.util.Arrays;
+
+/**
+ * Simple CredentialsMatcher implementation. Supports direct (plain) comparison for credentials of type
+ * byte[], char[], and Strings, and if the arguments do not match these types, then reverts back to simple
+ * <code>Object.equals</code> comparison.
+ *
+ * <p>Hashing comparisons (the most common technique used in secure applications) are not supported by this class, but
+ * instead by {@link HashedCredentialsMatcher HashedCredentialsMatcher} implementations.
+ *
+ * @author Les Hazlewood
+ * @see HashedCredentialsMatcher
+ * @see Md5CredentialsMatcher
+ * @see Sha1CredentialsMatcher
+ * @since 0.9
+ */
+public class SimpleCredentialsMatcher extends CodecSupport implements CredentialsMatcher {
+
+ private static final Log log = LogFactory.getLog(SimpleCredentialsMatcher.class);
+
+ /**
+ * Returns the <tt>token</tt>'s credentials.
+ *
+ * <p>This default implementation merely returns
+ * {@link AuthenticationToken#getCredentials() authenticationToken.getCredentials()} and exists as a template hook
+ * if subclasses wish to obtain the credentials in a different way or convert them to a different format before
+ * returning.
+ *
+ * @param token the <tt>AuthenticationToken</tt> submitted during the authentication attempt.
+ * @return the <tt>token</tt>'s associated credentials.
+ */
+ protected Object getCredentials(AuthenticationToken token) {
+ return token.getCredentials();
+ }
+
+ /**
+ * Returns the <tt>account</tt>'s credentials.
+ *
+ * <p>This default implementation merely returns
+ * {@link AuthenticationInfo#getCredentials() account.getCredentials()} and exists as a template hook if subclasses
+ * wish to obtain the credentials in a different way or convert them to a different format before
+ * returning.
+ *
+ * @param info the <tt>AuthenticationInfo</tt> stored in the data store to be compared against the submitted authentication
+ * token's credentials.
+ * @return the <tt>account</tt>'s associated credentials.
+ */
+ protected Object getCredentials(AuthenticationInfo info) {
+ return info.getCredentials();
+ }
+
+ /**
+ * Returns <tt>true</tt> if the <tt>tokenCredentials</tt> argument is logically equal to the
+ * <tt>accountCredentials</tt> argument.
+ *
+ * <p>If both arguments are either a byte array (byte[]), char array (char[]) or String, they will be both be
+ * converted to raw byte arrays via the {@link #toBytes toBytes} method first, and then resulting byte arrays
+ * are compared via {@link Arrays#equals(byte[], byte[]) Arrays.equals(byte[],byte[])}.</p>
+ *
+ * <p>If either argument cannot be converted to a byte array as described, a simple Object <code>equals</code>
+ * comparison is made.</p>
+ *
+ * <p>Subclasses should override this method for more explicit equality checks.
+ *
+ * @param tokenCredentials the <tt>AuthenticationToken</tt>'s associated credentials.
+ * @param accountCredentials the <tt>AuthenticationInfo</tt>'s stored credentials.
+ * @return <tt>true</tt> if the <tt>tokenCredentials</tt> are equal to the <tt>accountCredentials</tt>.
+ */
+ protected boolean equals(Object tokenCredentials, Object accountCredentials) {
+ if (log.isDebugEnabled()) {
+ log.debug("Performing credentials equality check for tokenCredentials of type [" +
+ tokenCredentials.getClass().getName() + " and accountCredentials of type [" +
+ accountCredentials.getClass().getName() + "]");
+ }
+ if ((tokenCredentials instanceof byte[] || tokenCredentials instanceof char[] || tokenCredentials instanceof String) &&
+ (accountCredentials instanceof byte[] || accountCredentials instanceof char[] || accountCredentials instanceof String)) {
+ if (log.isDebugEnabled()) {
+ log.debug("Both credentials arguments can be easily converted to byte arrays. Performing " +
+ "array equals comparison");
+ }
+ byte[] tokenBytes = toBytes(tokenCredentials);
+ byte[] accountBytes = toBytes(accountCredentials);
+ return Arrays.equals(tokenBytes, accountBytes);
+ } else {
+ return accountCredentials.equals(tokenCredentials);
+ }
+ }
+
+ /**
+ * This implementation acquires the <tt>token</tt>'s credentials
+ * (via {@link #getCredentials(AuthenticationToken) getCredentials(token)})
+ * and then the <tt>account</tt>'s credentials
+ * (via {@link #getCredentials(org.jsecurity.authc.AuthenticationInfo) getCredentials(account)}) and then passes both of
+ * them to the {@link #equals(Object,Object) equals(tokenCredentials, accountCredentials)} method for equality
+ * comparison.
+ *
+ * @param token the <tt>AuthenticationToken</tt> submitted during the authentication attempt.
+ * @param info the <tt>AuthenticationInfo</tt> stored in the system matching the token principal.
+ * @return <tt>true</tt> if the provided token credentials are equal to the stored account credentials,
+ * <tt>false</tt> otherwise
+ */
+ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
+ Object tokenCredentials = getCredentials(token);
+ Object accountCredentials = getCredentials(info);
+ return equals(tokenCredentials, accountCredentials);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authc/pam/ModularRealmAuthenticator.java b/core/src/org/jsecurity/authc/pam/ModularRealmAuthenticator.java
new file mode 100644
index 0000000..5a20973
--- /dev/null
+++ b/core/src/org/jsecurity/authc/pam/ModularRealmAuthenticator.java
@@ -0,0 +1,331 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authc.pam;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.*;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.subject.PrincipalCollection;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * A <tt>ModularRealmAuthenticator</tt> delgates account lookups to a pluggable (modular) collection of
+ * {@link Realm}s. This enables PAM (Pluggable Authentication Module) behavior in JSecurity.
+ * In addition to authorization duties, a JSecurity Realm can also be thought of a PAM 'module'.
+ *
+ * <p>Using this Authenticator allows you to "plug-in" your own
+ * <tt>Realm</tt>s as you see fit. Common realms are those based on accessing
+ * LDAP, relational databases, file systems, etc.
+ *
+ * <p>If only one realm is configured (this is often the case for most applications), authentication success is naturally
+ * only dependent upon invoking this one Realm's
+ * {@link Realm#getAuthenticationInfo(org.jsecurity.authc.AuthenticationToken)} method.
+ *
+ * <p>But if two or more realms are configured, PAM behavior is implemented by iterating over the collection of realms
+ * and interacting with each over the course of the authentication attempt. As this is more complicated, this
+ * authenticator allows customized behavior for interpreting what happens when interacting with multiple realms - for
+ * example, you might require all realms to be successful during the attempt, or perhaps only at least one must be
+ * successful, or some other interpretation. This customized behavior can be performed via the use of a
+ * {@link #setModularAuthenticationStrategy(ModularAuthenticationStrategy) ModularAuthenticationStrategy}, which
+ * you can inject as a property of this class.
+ *
+ * <p>The strategy object provides callback methods that allow you to
+ * determine what constitutes a success or failure in a multi-realm (PAM) scenario. And because this only makes sense
+ * in a mult-realm scenario, the strategy object is only utilized when more than one Realm is configured.
+ *
+ * <p>For greater security in a multi-realm configuration, unless overridden, the default implementation is the
+ * {@link AllSuccessfulModularAuthenticationStrategy AllSuccessfulModularAuthenticationStrategy}
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see #setRealms
+ * @see AllSuccessfulModularAuthenticationStrategy
+ * @see AtLeastOneSuccessfulModularAuthenticationStrategy
+ * @since 0.1
+ */
+public class ModularRealmAuthenticator extends AbstractAuthenticator {
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+ private static final Log log = LogFactory.getLog(ModularRealmAuthenticator.class);
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ /**
+ * List of realms that will be iterated through when a user authenticates.
+ */
+ private Collection<Realm> realms;
+
+ /**
+ * The authentication strategy to use during authentication attempts.
+ */
+ private ModularAuthenticationStrategy modularAuthenticationStrategy;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+ /**
+ * Default no-argument constructor which
+ * {@link #setModularAuthenticationStrategy(ModularAuthenticationStrategy) enables} a
+ * {@link org.jsecurity.authc.pam.AllSuccessfulModularAuthenticationStrategy AllSuccessfulModularAuthenticationStrategy}
+ * by default.
+ */
+ public ModularRealmAuthenticator() {
+ ModularAuthenticationStrategy strategy = new AllSuccessfulModularAuthenticationStrategy();
+ setModularAuthenticationStrategy(strategy);
+ }
+
+ /**
+ * Constructor which initializes this <code>Authenticator</code> with a single realm to use during
+ * an authentiation attempt. Because
+ * this would set a single realm, no {@link #setModularAuthenticationStrategy(ModularAuthenticationStrategy)
+ * modularAuthenticationStrategy} would be used during authentication attempts.
+ * @param realm the realm to consult during an authentication attempt.
+ */
+ public ModularRealmAuthenticator(Realm realm) {
+ setRealm(realm);
+ }
+
+ /**
+ * Constructor which initializes this <code>Authenticator</code> with multiple realms that will be
+ * consulted during an authentication attempt, effectively enabling PAM (Pluggable Authentication Module)
+ * behavior according to the configured
+ * {@link #setModularAuthenticationStrategy(ModularAuthenticationStrategy) ModularAuthenticationStrategy}.
+ * @param realms the realms to consult during an authentication attempt.
+ */
+ public ModularRealmAuthenticator(List<Realm> realms) {
+ setRealms(realms);
+ }
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+ /**
+ * Convenience setter for single-realm environments (fairly common). This method just wraps the realm in a
+ * collection and then calls {@link #setRealms}.
+ *
+ * @param realm the realm to consult during authentication attempts.
+ */
+ public void setRealm(Realm realm) {
+ List<Realm> realms = new ArrayList<Realm>(1);
+ realms.add(realm);
+ setRealms(realms);
+ }
+
+ /**
+ * Sets all realms used by this Authenticator, providing PAM (Pluggable Authentication Module) configuration.
+ *
+ * @param realms the realms to consult during authentication attempts.
+ */
+ public void setRealms(Collection<Realm> realms) {
+ this.realms = realms;
+ }
+
+ /**
+ * Returns the realm(s) used by this <code>Authenticator</code> during an authentication attempt.
+ * @return the realm(s) used by this <code>Authenticator</code> during an authentication attempt.
+ */
+ protected Collection<Realm> getRealms() {
+ return this.realms;
+ }
+
+ /**
+ * Returns the <tt>ModularAuthenticationStrategy</tt> utilized by this modular authenticator during a multi-realm
+ * log-in attempt. This object is only used when two or more Realms are configured.
+ *
+ * <p>Unless overridden by
+ * the {@link #setModularAuthenticationStrategy(ModularAuthenticationStrategy)} method, the default implementation
+ * is the {@link AllSuccessfulModularAuthenticationStrategy}.
+ *
+ * @return the <tt>ModularAuthenticationStrategy</tt> utilized by this modular authenticator during a log-in attempt.
+ * @since 0.2
+ */
+ public ModularAuthenticationStrategy getModularAuthenticationStrategy() {
+ return modularAuthenticationStrategy;
+ }
+
+ /**
+ * Allows overriding the default <tt>ModularAuthenticationStrategy</tt> utilized during multi-realm log-in attempts.
+ * This object is only used when two or more Realms are configured.
+ *
+ * @param modularAuthenticationStrategy the strategy implementation to use during log-in attempts.
+ * @since 0.2
+ */
+ public void setModularAuthenticationStrategy(ModularAuthenticationStrategy modularAuthenticationStrategy) {
+ this.modularAuthenticationStrategy = modularAuthenticationStrategy;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+ /**
+ * Used by the internal {@link #doAuthenticate} implementation to ensure that the <tt>realms</tt> property
+ * has been set. The default implementation ensures the property is not null and not empty.
+ *
+ * @throws IllegalStateException if the <tt>realms</tt> property is configured incorrectly.
+ */
+ protected void assertRealmsConfigured() throws IllegalStateException {
+ Collection<Realm> realms = getRealms();
+ if (realms == null || realms.isEmpty()) {
+ String msg = "Configuration error: No realms have been configured! One or more realms must be " +
+ "present to execute an authentication attempt.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ /**
+ * Performs the authentication attempt by interacting with the single configured realm, which is significantly
+ * simpler than performing multi-realm logic.
+ *
+ * @param realm the realm to consult for AuthenticationInfo.
+ * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
+ * @return the AuthenticationInfo associated with the user account corresponding to the specified <tt>token</tt>
+ */
+ protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
+ if (!realm.supports(token)) {
+ String msg = "Realm [" + realm + "] does not support authentication token [" +
+ token + "]. Please ensure that the appropriate Realm implementation is " +
+ "configured correctly or that the realm accepts AuthenticationTokens of this type.";
+ throw new UnsupportedTokenException(msg);
+ }
+ AuthenticationInfo info = realm.getAuthenticationInfo(token);
+ if (info == null) {
+ String msg = "Realm [" + realm + "] was unable to find account data for the " +
+ "submitted AuthenticationToken [" + token + "].";
+ throw new UnknownAccountException(msg);
+ }
+ return info;
+ }
+
+ /**
+ * Performs the multi-realm authentication attempt by calling back to a {@link ModularAuthenticationStrategy} object
+ * as each realm is consulted for <tt>AuthenticationInfo</tt> for the specified <tt>token</tt>.
+ *
+ * @param realms the multiple realms configured on this Authenticator instance.
+ * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
+ * @return an aggregated AuthenticationInfo instance representing account data across all the successfully
+ * consulted realms.
+ */
+ protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
+
+ ModularAuthenticationStrategy strategy = getModularAuthenticationStrategy();
+
+ AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Iterating through [" + realms.size() + "] realms for PAM authentication");
+ }
+
+ for (Realm realm : realms) {
+
+ if (realm.supports(token)) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Attempting to authenticate token [" + token + "] " +
+ "using realm of type [" + realm + "]");
+ }
+
+ AuthenticationInfo info = null;
+ Throwable t = null;
+ try {
+ info = realm.getAuthenticationInfo(token);
+ } catch (Throwable throwable) {
+ t = throwable;
+ if (log.isTraceEnabled()) {
+ String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
+ log.trace(msg, t);
+ }
+ }
+
+ aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
+
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Realm of type [" + realm + "] does not support token " +
+ "[" + token + "]. Skipping realm.");
+ }
+ }
+ }
+
+ aggregate = strategy.afterAllAttempts(token, aggregate);
+
+ return aggregate;
+ }
+
+
+ /**
+ * <p>Attempts to authenticate the given token by iterating over the internal collection of
+ * {@link Realm}s. For each realm, first the {@link Realm#supports(org.jsecurity.authc.AuthenticationToken)}
+ * method will be called to determine if the realm supports the <tt>authenticationToken</tt> method argument.
+ *
+ * If a realm does support
+ * the token, its {@link Realm#getAuthenticationInfo(org.jsecurity.authc.AuthenticationToken)}
+ * method will be called. If the realm returns a non-null account, the token will be
+ * considered authenticated for that realm and the account data recorded. If the realm returns <tt>null</tt>,
+ * the next realm will be consulted. If no realms support the token or all supporting realms return null,
+ * an {@link AuthenticationException} will be thrown to indicate that the user could not be authenticated.
+ *
+ * <p>After all realms have been consulted, the information from each realm is aggregated into a single
+ * {@link AuthenticationInfo} object and returned.
+ *
+ * @param authenticationToken the token containing the authentication principal and credentials for the
+ * user being authenticated.
+ * @return account information attributed to the authenticated user.
+ * @throws AuthenticationException if the user could not be authenticated or the user is denied authentication
+ * for the given principal and credentials.
+ */
+ protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
+ assertRealmsConfigured();
+ Collection<Realm> realms = getRealms();
+ if (realms.size() == 1) {
+ return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
+ } else {
+ return doMultiRealmAuthentication(realms, authenticationToken);
+ }
+ }
+
+ /**
+ * First calls <code>super.onLogout(principals)</code> to ensure a logout notification is issued, and for each
+ * wrapped <tt>Realm</tt> that implements the {@link LogoutAware LogoutAware} interface, calls
+ * <code>((LogoutAware)realm).onLogout(principals)</code> to allow each realm the opportunity to perform
+ * logout/cleanup operations during an user-logout.
+ *
+ * <p>JSecurity's Realm implementations all implement the <tt>LogoutAware</tt> interface by default and can be
+ * overridden for realm-specific logout logic.
+ *
+ * @param principals the application-specific Subject/user identifier.
+ */
+ public void onLogout(PrincipalCollection principals) {
+ super.onLogout(principals);
+ Collection<Realm> realms = getRealms();
+ if (realms != null && !realms.isEmpty()) {
+ for (Realm realm : realms) {
+ if (realm instanceof LogoutAware) {
+ ((LogoutAware) realm).onLogout(principals);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/authz/AuthorizationException.java b/core/src/org/jsecurity/authz/AuthorizationException.java
new file mode 100644
index 0000000..902be58
--- /dev/null
+++ b/core/src/org/jsecurity/authz/AuthorizationException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * Exception thrown if there is a problem during authorization (access control check).
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class AuthorizationException extends JSecurityException {
+
+ /**
+ * Creates a new AuthorizationException.
+ */
+ public AuthorizationException() {
+ super();
+ }
+
+ /**
+ * Constructs a new AuthorizationException.
+ *
+ * @param message the reason for the exception
+ */
+ public AuthorizationException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new AuthorizationException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public AuthorizationException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new AuthorizationException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public AuthorizationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authz/Authorizer.java b/core/src/org/jsecurity/authz/Authorizer.java
new file mode 100644
index 0000000..11086a6
--- /dev/null
+++ b/core/src/org/jsecurity/authz/Authorizer.java
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz;
+
+import org.jsecurity.subject.PrincipalCollection;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * An <tt>Authorizer</tt> performs authorization (access control) operations for any given Subject
+ * (aka 'application user').
+ *
+ * <p>Each method requires a subject principal to perform the action for the corresponding Subject/user.
+ *
+ * <p>This principal argument is usually an object representing a user database primary key or a String username or
+ * something similar that uniquely identifies an application user. The runtime value of the this principal
+ * is application-specific and provided by the application's configured Realms.
+ *
+ * <p>Note that there are many *Permission methods in this interface overloaded to accept String arguments instead of
+ * {@link Permission Permission} instances. They are a convenience allowing the caller to use a String representation of
+ * a {@link Permission Permission} if desired. Most implementations of this interface will simply convert these
+ * String values to {@link Permission Permission} instances and then just call the corresponding type-safe method.
+ * (JSecurity's default implementations do String-to-Permission conversion for these methods using
+ * {@link org.jsecurity.authz.permission.PermissionResolver PermissionResolver}s.)
+ *
+ * <p>These overloaded *Permission methods <em>do</em> forego type-saftey for the benefit of convenience and simplicity,
+ * so you should choose which ones to use based on your preferences and needs.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public interface Authorizer {
+
+ /**
+ * Returns <tt>true</tt> if the corresponding subject/user is permitted to perform an action or access a resource
+ * summarized by the specified permission string.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param principals the application-specific subject/user identifier.
+ * @param permission the String representation of a Permission that is being checked.
+ * @return true if the corresponding Subject/user is permitted, false otherwise.
+ * @see #isPermitted(PrincipalCollection principals,Permission permission)
+ * @since 0.9
+ */
+ boolean isPermitted(PrincipalCollection principals, String permission);
+
+ /**
+ * Returns <tt>true</tt> if the corresponding subject/user is permitted to perform an action or access a resource
+ * summarized by the specified permission.
+ *
+ * <p>More specifically, this method determines if any <tt>Permission</tt>s associated
+ * with the subject {@link Permission#implies(Permission) imply} the specified permission.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permission the permission that is being checked.
+ * @return true if the corresponding Subject/user is permitted, false otherwise.
+ */
+ boolean isPermitted(PrincipalCollection subjectPrincipal, Permission permission);
+
+ /**
+ * Checks if the corresponding Subject implies the given permission strings and returns a boolean array
+ * indicating which permissions are implied.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permissions the String representations of the Permissions that are being checked.
+ * @return an array of booleans whose indices correspond to the index of the
+ * permissions in the given list. A true value at an index indicates the user is permitted for
+ * for the associated <tt>Permission</tt> string in the list. A false value at an index
+ * indicates otherwise.
+ * @since 0.9
+ */
+ boolean[] isPermitted(PrincipalCollection subjectPrincipal, String... permissions);
+
+ /**
+ * Checks if the corresponding Subject/user implies the given Permissions and returns a boolean array indicating
+ * which permissions are implied.
+ *
+ * <p>More specifically, this method should determine if each <tt>Permission</tt> in
+ * the array is {@link Permission#implies(Permission) implied} by permissions
+ * already associated with the subject.
+ *
+ * <p>This is primarily a performance-enhancing method to help reduce the number of
+ * {@link #isPermitted} invocations over the wire in client/server systems.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permissions the permissions that are being checked.
+ * @return an array of booleans whose indices correspond to the index of the
+ * permissions in the given list. A true value at an index indicates the user is permitted for
+ * for the associated <tt>Permission</tt> object in the list. A false value at an index
+ * indicates otherwise.
+ */
+ boolean[] isPermitted(PrincipalCollection subjectPrincipal, List<Permission> permissions);
+
+ /**
+ * Returns <tt>true</tt> if the corresponding Subject/user implies all of the specified permission strings,
+ * <tt>false</tt> otherwise.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permissions the String representations of the Permissions that are being checked.
+ * @return true if the user has all of the specified permissions, false otherwise.
+ * @see #isPermittedAll(PrincipalCollection,Collection)
+ * @since 0.9
+ */
+ boolean isPermittedAll(PrincipalCollection subjectPrincipal, String... permissions);
+
+ /**
+ * Returns <tt>true</tt> if the corresponding Subject/user implies all of the specified permissions, <tt>false</tt>
+ * otherwise.
+ *
+ * <p>More specifically, this method determines if all of the given <tt>Permission</tt>s are
+ * {@link Permission#implies(Permission) implied by} permissions already associated with the subject.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permissions the permissions to check.
+ * @return true if the user has all of the specified permissions, false otherwise.
+ */
+ boolean isPermittedAll(PrincipalCollection subjectPrincipal, Collection<Permission> permissions);
+
+ /**
+ * Ensures the corresponding Subject/user implies the specified permission String.
+ *
+ * <p>If the subject's existing associated permissions do not {@link Permission#implies(Permission)} imply}
+ * the given permission, an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permission the String representation of the Permission to check.
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the user does not have the permission.
+ * @since 0.9
+ */
+ void checkPermission(PrincipalCollection subjectPrincipal, String permission) throws AuthorizationException;
+
+ /**
+ * Ensures a subject/user {@link Permission#implies(Permission)} implies} the specified <tt>Permission</tt>.
+ * If the subject's exisiting associated permissions do not {@link Permission#implies(Permission)} imply}
+ * the given permission, an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permission the Permission to check.
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the user does not have the permission.
+ */
+ void checkPermission(PrincipalCollection subjectPrincipal, Permission permission) throws AuthorizationException;
+
+ /**
+ * Ensures the corresponding Subject/user
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) implies} all of the
+ * specified permission strings.
+ *
+ * If the subject's exisiting associated permissions do not
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) imply} all of the given permissions,
+ * an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permissions the string representations of Permissions to check.
+ * @throws AuthorizationException if the user does not have all of the given permissions.
+ * @since 0.9
+ */
+ void checkPermissions(PrincipalCollection subjectPrincipal, String... permissions) throws AuthorizationException;
+
+ /**
+ * Ensures the corresponding Subject/user
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) implies} all of the
+ * specified permission strings.
+ *
+ * If the subject's exisiting associated permissions do not
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) imply} all of the given permissions,
+ * an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param permissions the Permissions to check.
+ * @throws AuthorizationException if the user does not have all of the given permissions.
+ */
+ void checkPermissions(PrincipalCollection subjectPrincipal, Collection<Permission> permissions) throws AuthorizationException;
+
+ /**
+ * Returns <tt>true</tt> if the corresponding Subject/user has the specified role, <tt>false</tt> otherwise.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param roleIdentifier the application-specific role identifier (usually a role id or role name).
+ * @return <tt>true</tt> if the corresponding subject has the specified role, <tt>false</tt> otherwise.
+ */
+ boolean hasRole(PrincipalCollection subjectPrincipal, String roleIdentifier);
+
+ /**
+ * Checks if the corresponding Subject/user has the specified roles, returning a boolean array indicating
+ * which roles are associated with the given subject.
+ *
+ * <p>This is primarily a performance-enhancing method to help reduce the number of
+ * {@link #hasRole} invocations over the wire in client/server systems.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
+ * @return an array of booleans whose indices correspond to the index of the
+ * roles in the given identifiers. A true value indicates the user has the
+ * role at that index. False indicates the user does not have the role at that index.
+ */
+ boolean[] hasRoles(PrincipalCollection subjectPrincipal, List<String> roleIdentifiers);
+
+ /**
+ * Returns <tt>true</tt> if the corresponding Subject/user has all of the specified roles, <tt>false</tt> otherwise.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
+ * @return true if the user has all the roles, false otherwise.
+ */
+ boolean hasAllRoles(PrincipalCollection subjectPrincipal, Collection<String> roleIdentifiers);
+
+ /**
+ * Asserts the corresponding Subject/user has the specified role by returning quietly if they do or throwing an
+ * {@link org.jsecurity.authz.AuthorizationException} if they do not.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param roleIdentifier the application-specific role identifier (usually a role id or role name ).
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the user does not have the role.
+ */
+ void checkRole(PrincipalCollection subjectPrincipal, String roleIdentifier) throws AuthorizationException;
+
+ /**
+ * Asserts the corresponding Subject/user has all of the specified roles by returning quietly if they do or
+ * throwing an {@link org.jsecurity.authz.AuthorizationException} if they do not.
+ *
+ * @param subjectPrincipal the application-specific subject/user identifier.
+ * @param roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the user does not have all of the specified roles.
+ */
+ void checkRoles(PrincipalCollection subjectPrincipal, Collection<String> roleIdentifiers) throws AuthorizationException;
+
+}
+
diff --git a/core/src/org/jsecurity/authz/HostUnauthorizedException.java b/core/src/org/jsecurity/authz/HostUnauthorizedException.java
new file mode 100644
index 0000000..37b972e
--- /dev/null
+++ b/core/src/org/jsecurity/authz/HostUnauthorizedException.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz;
+
+import java.net.InetAddress;
+
+/**
+ * Thrown when a particular client (that is, host address) has not been enabled to access the system
+ * or if the client has been enabled access but is not permitted to perform a particluar operation
+ * or access a particular resource.
+ *
+ * @author Les Hazlewood
+ * @see org.jsecurity.session.SessionFactory#start(java.net.InetAddress)
+ * @since 0.1
+ */
+public class HostUnauthorizedException extends UnauthorizedException {
+
+ private InetAddress hostAddress;
+
+ /**
+ * Creates a new HostUnauthorizedException.
+ */
+ public HostUnauthorizedException() {
+ super();
+ }
+
+ /**
+ * Constructs a new HostUnauthorizedException.
+ *
+ * @param message the reason for the exception
+ */
+ public HostUnauthorizedException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new HostUnauthorizedException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public HostUnauthorizedException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new HostUnauthorizedException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public HostUnauthorizedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new HostUnauthorizedException associated with the given host address.
+ *
+ * @param hostAddress the address of the host unauthorized to perform a particular action or
+ * access a particular resource.
+ */
+ public HostUnauthorizedException(InetAddress hostAddress) {
+ this("The system is not cofigured to allow access for host [" +
+ hostAddress.getHostAddress() + "]");
+ }
+
+ /**
+ * Returns the host address associated with this exception.
+ *
+ * @return the host address associated with this exception.
+ */
+ public InetAddress getHostAddress() {
+ return this.hostAddress;
+ }
+
+ /**
+ * Sets the host address associated with this exception.
+ *
+ * @param hostAddress the host address associated with this exception.
+ */
+ public void setHostAddress(InetAddress hostAddress) {
+ this.hostAddress = hostAddress;
+ }
+}
diff --git a/core/src/org/jsecurity/authz/UnauthenticatedException.java b/core/src/org/jsecurity/authz/UnauthenticatedException.java
new file mode 100644
index 0000000..4048b85
--- /dev/null
+++ b/core/src/org/jsecurity/authz/UnauthenticatedException.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz;
+
+/**
+ * Exception thrown when attempting to execute an authorization action when a successful
+ * authentication hasn't yet occurred.
+ *
+ * <p>Authorizations can only be performed after a successful
+ * authentication because authorization data (roles, permissions, etc) must always be associated
+ * with a known identity. Such a known identity can only be obtained upon a successful log-in.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class UnauthenticatedException extends AuthorizationException {
+
+ /**
+ * Creates a new UnauthenticatedException.
+ */
+ public UnauthenticatedException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnauthenticatedException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnauthenticatedException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnauthenticatedException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnauthenticatedException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnauthenticatedException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnauthenticatedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core/src/org/jsecurity/authz/UnauthorizedException.java b/core/src/org/jsecurity/authz/UnauthorizedException.java
new file mode 100644
index 0000000..fd8b393
--- /dev/null
+++ b/core/src/org/jsecurity/authz/UnauthorizedException.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz;
+
+/**
+ * Thrown to indicate a requested operation or access to a requested resource is not allowed.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class UnauthorizedException extends AuthorizationException {
+
+ /**
+ * Creates a new UnauthorizedException.
+ */
+ public UnauthorizedException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnauthorizedException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnauthorizedException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnauthorizedException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnauthorizedException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnauthorizedException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnauthorizedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/authz/annotation/RequiresAuthentication.java b/core/src/org/jsecurity/authz/annotation/RequiresAuthentication.java
new file mode 100644
index 0000000..75d33aa
--- /dev/null
+++ b/core/src/org/jsecurity/authz/annotation/RequiresAuthentication.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Requires the current Subject to have been authenticated <em>during their current session</em> for the annotated
+ * class/instance/method to be accessed or invoked. This is <em>more</em> restrictive than the
+ * {@link RequiresUser RequiresUser} annotation.
+ * <p/>
+ * This annotation basically ensures that
+ * <code>{@link org.jsecurity.subject.Subject subject}.{@link org.jsecurity.subject.Subject#isAuthenticated() isAuthenticated()} === true</code>
+ * <p/>
+ * See the {@link RequiresUser RequiresUser} and
+ * {@link org.jsecurity.authc.RememberMeAuthenticationToken RememberMeAuthenticationToken} JavaDoc for an
+ * explaination of why these two states are considered different.
+ *
+ * @see RequiresUser
+ * @see RequiresGuest
+ *
+ * @since 0.9.0
+ * @author Les Hazlewood
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresAuthentication {
+}
diff --git a/core/src/org/jsecurity/authz/annotation/RequiresGuest.java b/core/src/org/jsecurity/authz/annotation/RequiresGuest.java
new file mode 100644
index 0000000..e9e1ead
--- /dev/null
+++ b/core/src/org/jsecurity/authz/annotation/RequiresGuest.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Requires the current Subject to be a "guest", that is, they are not authenticated <em>or</em> remembered
+ * from a previous session for the annotated class/instance/method to be accessed or invoked.
+ * <p/>
+ * This annotation is the logical inverse of the {@link RequiresUser RequiresUser} annotation. That is,
+ * <code>RequiresUser == !RequiresGuest</code>, or more accurately,
+ * <p/>
+ * <code>RequiresGuest === subject.{@link org.jsecurity.subject.Subject#getPrincipal() getPrincipal()} == null</code>.
+ *
+ * @see RequiresAuthentication
+ * @see RequiresUser
+ *
+ * @since 0.9.0
+ * @author Les Hazlewood
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresGuest {
+}
diff --git a/core/src/org/jsecurity/authz/annotation/RequiresPermissions.java b/core/src/org/jsecurity/authz/annotation/RequiresPermissions.java
new file mode 100644
index 0000000..af3258c
--- /dev/null
+++ b/core/src/org/jsecurity/authz/annotation/RequiresPermissions.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * <p>
+ * Requires the current executor's Subject to imply a particular permission in
+ * order to execute the annotated method. If the executor's associated
+ * {@link org.jsecurity.subject.Subject Subject} determines that the
+ * executor does not imply the specified permission, the method will not be executed.
+ * </p>
+ *
+ * <p>For example, this declaration:
+ * <p/>
+ * <code>@RequiresPermissions( "file:read,write:aFile.txt" )<br/>
+ * void someMethod();</code>
+ * <p/>
+ * indicates the current user must be able to both <tt>read</tt> and <tt>write</tt>
+ * to the file <tt>aFile.txt</tt> in order for the <tt>someMethod()</tt> to execute, otherwise
+ * an {@link org.jsecurity.authz.AuthorizationException AuthorizationException} will be thrown.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see org.jsecurity.subject.Subject#checkPermission
+ * @since 0.1
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresPermissions {
+
+ /**
+ * The permission string which will be passed to {@link org.jsecurity.subject.Subject#isPermitted(String)}
+ * to determine if the user is allowed to invoke the code protected by this annotation.
+ */
+ String value();
+
+}
+
diff --git a/core/src/org/jsecurity/authz/annotation/RequiresRoles.java b/core/src/org/jsecurity/authz/annotation/RequiresRoles.java
new file mode 100644
index 0000000..4d15c14
--- /dev/null
+++ b/core/src/org/jsecurity/authz/annotation/RequiresRoles.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Requires the currently executing {@link org.jsecurity.subject.Subject Subject} to have one or more specified roles
+ * in order to execute the annotated method. If they do not have the role(s), the method will not be executed and
+ * an {@link org.jsecurity.authz.AuthorizationException AuthorizationException} is thrown.
+ * <p/>
+ * For example,
+ * <p/>
+ * <code>@RequiresRoles("aRoleName");<br/>
+ * void someMethod();</code>
+ * <p/>
+ * means <tt>someMethod()</tt> could only be executed by subjects who have been assigned the
+ * 'aRoleName' role.
+ *
+ * <p><b>*Usage Note*:</b> Be careful using this annotation if your application has a <em>dynamic</em>
+ * security model where roles can be added and deleted at runtime. If your application allowed the
+ * annotated role to be deleted during runtime, the method would not be able to
+ * be executed by anyone (at least until a new role with the same name was created again).
+ *
+ * <p>If you require such dynamic functionality, only the
+ * {@link RequiresPermissions RequiresPermissions} annotation makes sense - Permission
+ * types will not change during runtime for an application since permissions directly correspond to how
+ * the application's functionality is programmed (that is, they reflect the application's functionality only, not
+ * <em>who</em> is executing the the functionality).
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see org.jsecurity.subject.Subject#hasRole(String)
+ * @since 0.1
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresRoles {
+
+ /**
+ * A single String role name or multiple comma-delimitted role names required in order for the method
+ * invocation to be allowed.
+ */
+ String value();
+
+}
diff --git a/core/src/org/jsecurity/authz/annotation/RequiresUser.java b/core/src/org/jsecurity/authz/annotation/RequiresUser.java
new file mode 100644
index 0000000..a154bee
--- /dev/null
+++ b/core/src/org/jsecurity/authz/annotation/RequiresUser.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Requires the current Subject to be an application <em>user</em> for the annotated class/instance/method to be
+ * accessed or invoked. This is <em>less</em> restrictive than the {@link RequiresAuthentication RequiresAuthentication}
+ * annotation.
+ * <p/>
+ * JSecurity defines a "user" as a Subject that is either
+ * "remembered" <b><em>or</em></b> authenticated:
+ * <ul>
+ * <li>An <b>authenticated</b> user is a Subject that has successfully logged in (proven their identity)
+ * <em>during their current session</em>.</li>
+ * <li>A <b>remembered</b> user is any Subject that has proven their identity at least once, although not necessarily
+ * during their current session, and asked the system to remember them.</li>
+ * </ul>
+ * <p/>
+ * See the {@link org.jsecurity.authc.RememberMeAuthenticationToken RememberMeAuthenticationToken} JavaDoc for an
+ * explaination of why these two states are considered different.
+ *
+ * @see RequiresAuthentication
+ * @see RequiresGuest
+ *
+ * @since 0.9.0
+ * @author Les Hazlewood
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresUser {
+}
diff --git a/core/src/org/jsecurity/authz/aop/AnnotationsAuthorizingMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/AnnotationsAuthorizingMethodInterceptor.java
new file mode 100644
index 0000000..c63431c
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/AnnotationsAuthorizingMethodInterceptor.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.aop.MethodInvocation;
+import org.jsecurity.authz.AuthorizationException;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * An <tt>AnnotationsAuthorizingMethodInterceptor</tt> is a MethodInterceptor that asserts a given method is authorized
+ * to execute based on one or more configured <tt>AuthorizingAnnotationMethodInterceptor</tt>s.
+ *
+ * <p>This allows multiple annotations on a method to be processed before the method
+ * executes, and if any of the <tt>AuthorizingAnnotationMethodInterceptor</tt>s indicate that the method should not be
+ * executed, an <tt>AuthorizationException</tt> will be thrown, otherwise the method will be invoked as expected.
+ *
+ * <p>It is essentially a convenience mechanism to allow multiple annotations to be processed in a single method
+ * interceptor.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public abstract class AnnotationsAuthorizingMethodInterceptor extends AuthorizingMethodInterceptor {
+
+ /**
+ * The method interceptors to execute for the annotated method.
+ */
+ protected Collection<AuthorizingAnnotationMethodInterceptor> methodInterceptors;
+
+ /**
+ * Default no-argument constructor that defaults the
+ * {@link #methodInterceptors methodInterceptors} attribute to contain two interceptors by default - the
+ * {@link org.jsecurity.authz.aop.RoleAnnotationMethodInterceptor RoleAnnotationMethodInterceptor} and the
+ * {@link org.jsecurity.authz.aop.PermissionAnnotationMethodInterceptor PermissionAnnotationMethodInterceptor} to
+ * support role and permission annotations.
+ */
+ public AnnotationsAuthorizingMethodInterceptor() {
+ methodInterceptors = new ArrayList<AuthorizingAnnotationMethodInterceptor>(5);
+ methodInterceptors.add(new RoleAnnotationMethodInterceptor());
+ methodInterceptors.add(new PermissionAnnotationMethodInterceptor());
+ methodInterceptors.add(new AuthenticatedAnnotationMethodInterceptor());
+ methodInterceptors.add(new UserAnnotationMethodInterceptor());
+ methodInterceptors.add(new GuestAnnotationMethodInterceptor());
+ }
+
+ /**
+ * Returns the method interceptors to execute for the annotated method.
+ * <p/>
+ * Unless overridden by the {@link #setMethodInterceptors(java.util.Collection)} method, the default collection
+ * contains a
+ * {@link org.jsecurity.authz.aop.RoleAnnotationMethodInterceptor RoleAnnotationMethodInterceptor} and a
+ * {@link org.jsecurity.authz.aop.PermissionAnnotationMethodInterceptor PermissionAnnotationMethodInterceptor} to
+ * support role and permission annotations automatically.
+ * @return the method interceptors to execute for the annotated method.
+ */
+ public Collection<AuthorizingAnnotationMethodInterceptor> getMethodInterceptors() {
+ return methodInterceptors;
+ }
+
+ /**
+ * Sets the method interceptors to execute for the annotated method.
+ * @param methodInterceptors the method interceptors to execute for the annotated method.
+ * @see #getMethodInterceptors()
+ */
+ public void setMethodInterceptors(Collection<AuthorizingAnnotationMethodInterceptor> methodInterceptors) {
+ this.methodInterceptors = methodInterceptors;
+ }
+
+ /**
+ * Iterates over the internal {@link #getMethodInterceptors() methodInterceptors} collection, and for each one,
+ * ensures that if the interceptor
+ * {@link org.jsecurity.authz.aop.AuthorizingAnnotationMethodInterceptor#supports(org.jsecurity.aop.MethodInvocation) supports}
+ * the invocation, that the interceptor
+ * {@link org.jsecurity.authz.aop.AuthorizingAnnotationMethodInterceptor#assertAuthorized(org.jsecurity.aop.MethodInvocation) asserts}
+ * that the invocation is authorized to proceed.
+ */
+ protected void assertAuthorized(MethodInvocation methodInvocation) throws AuthorizationException {
+ //default implementation just ensures no deny votes are cast:
+ Collection<AuthorizingAnnotationMethodInterceptor> aamis = getMethodInterceptors();
+ if (aamis != null && !aamis.isEmpty()) {
+ for (AuthorizingAnnotationMethodInterceptor aami : aamis) {
+ if (aami.supports(methodInvocation)) {
+ aami.assertAuthorized(methodInvocation);
+ }
+ }
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/AuthenticatedAnnotationHandler.java b/core/src/org/jsecurity/authz/aop/AuthenticatedAnnotationHandler.java
new file mode 100644
index 0000000..e957134
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/AuthenticatedAnnotationHandler.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.UnauthenticatedException;
+import org.jsecurity.authz.annotation.RequiresAuthentication;
+
+import java.lang.annotation.Annotation;
+
+/**
+ * Handles {@link RequiresAuthentication RequiresAuthentication} annotations and ensures the calling subject is
+ * authenticated before allowing access.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class AuthenticatedAnnotationHandler extends AuthorizingAnnotationHandler {
+
+ /**
+ * Default no-argument constructor that ensures this handler to process
+ * {@link org.jsecurity.authz.annotation.RequiresAuthentication RequiresAuthentication} annotations.
+ */
+ public AuthenticatedAnnotationHandler() {
+ super(RequiresAuthentication.class);
+ }
+
+ /**
+ * Ensures that the calling <code>Subject</code> is authenticated, and if not, throws an
+ * {@link org.jsecurity.authz.UnauthenticatedException UnauthenticatedException} indicating the method is not allowed to be executed.
+ *
+ * @param a the annotation to inspect
+ * @throws org.jsecurity.authz.UnauthenticatedException if the calling <code>Subject</code> has not yet
+ * authenticated.
+ */
+ public void assertAuthorized(Annotation a) throws UnauthenticatedException {
+ if (a instanceof RequiresAuthentication && !getSubject().isAuthenticated() ) {
+ throw new UnauthenticatedException( "The current Subject is not authenticated. Access denied." );
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/AuthenticatedAnnotationMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/AuthenticatedAnnotationMethodInterceptor.java
new file mode 100644
index 0000000..c9e9ec1
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/AuthenticatedAnnotationMethodInterceptor.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresAuthentication RequiresAuthenticated} annotation
+ * is declared, and if so, ensures the calling
+ * <code>Subject</code>.{@link org.jsecurity.subject.Subject#isAuthenticated() isAuthenticated()} before invoking
+ * the method.
+ *
+ * @since 0.9.0
+ * @author Les Hazlewood
+ */
+public class AuthenticatedAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
+
+ /**
+ * Default no-argument constructor that ensures this interceptor looks for
+ * {@link org.jsecurity.authz.annotation.RequiresAuthentication RequiresAuthentication} annotations in a method
+ * declaration.
+ */
+ public AuthenticatedAnnotationMethodInterceptor() {
+ super( new AuthenticatedAnnotationHandler() );
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/AuthorizingAnnotationHandler.java b/core/src/org/jsecurity/authz/aop/AuthorizingAnnotationHandler.java
new file mode 100644
index 0000000..dda4eff
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/AuthorizingAnnotationHandler.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.aop.AnnotationHandler;
+import org.jsecurity.authz.AuthorizationException;
+
+import java.lang.annotation.Annotation;
+
+/**
+ * An AnnotationHandler that executes authorization (access control) behavior based on directive(s) found in a
+ * JSR-175 Annotation.
+ *
+ * @since 0.9.0
+ * @author Les Hazlewood
+ */
+public abstract class AuthorizingAnnotationHandler extends AnnotationHandler {
+
+ /**
+ * Constructs an <code>AuthorizingAnnotationHandler</code> who processes annotations of the
+ * specified type. Immediately calls <code>super(annotationClass)</code>.
+ *
+ * @param annotationClass the type of annotation this handler will process.
+ */
+ public AuthorizingAnnotationHandler(Class<? extends Annotation> annotationClass) {
+ super(annotationClass);
+ }
+
+ /**
+ * Ensures the calling Subject is authorized to execute based on the directive(s) found in the given
+ * annotation.
+ * <p/>
+ * As this is an AnnotationMethodInterceptor, the implementations of this method typically inspect the annotation
+ * and perform a corresponding authorization check based.
+ *
+ * @param a the <code>Annotation</code> to check for performing an authorization check.
+ * @throws org.jsecurity.authz.AuthorizationException if the class/instance/method is not allowed to proceed/execute.
+ */
+ public abstract void assertAuthorized(Annotation a) throws AuthorizationException;
+}
diff --git a/core/src/org/jsecurity/authz/aop/AuthorizingAnnotationMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/AuthorizingAnnotationMethodInterceptor.java
new file mode 100644
index 0000000..a04aa53
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/AuthorizingAnnotationMethodInterceptor.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.aop.AnnotationMethodInterceptor;
+import org.jsecurity.aop.MethodInvocation;
+import org.jsecurity.authz.AuthorizationException;
+
+/**
+ * An <tt>AnnotationMethodInterceptor</tt> that asserts the calling code is authorized to execute the method
+ * before allowing the invocation to continue by inspecting code annotations to perform an access control check.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public abstract class AuthorizingAnnotationMethodInterceptor extends AnnotationMethodInterceptor {
+
+ /**
+ * Constructor that ensures the internal <code>handler</code> is set which will be used to perform the
+ * authorization assertion checks when a supported annotation is encountered.
+ * @param handler the internal <code>handler</code> used to perform authorization assertion checks when a
+ * supported annotation is encountered.
+ */
+ public AuthorizingAnnotationMethodInterceptor( AuthorizingAnnotationHandler handler ) {
+ super(handler);
+ }
+
+ /**
+ * Ensures the <code>methodInvocation</code> is allowed to execute first before proceeding by calling the
+ * {@link #assertAuthorized(org.jsecurity.aop.MethodInvocation) assertAuthorized} method first.
+ *
+ * @param methodInvocation the method invocation to check for authorization prior to allowing it to proceed/execute.
+ * @return the return value from the method invocation (the value of {@link org.jsecurity.aop.MethodInvocation#proceed() MethodInvocation.proceed()}).
+ * @throws AuthorizationException if the <code>MethodInvocation</code> is not allowed to proceed.
+ * @throws Throwable if any other error occurs.
+ */
+ public Object invoke(MethodInvocation methodInvocation) throws Throwable {
+ assertAuthorized(methodInvocation);
+ return methodInvocation.proceed();
+ }
+
+ /**
+ * Ensures the calling Subject is authorized to execute the specified <code>MethodInvocation</code>.
+ * <p/>
+ * As this is an AnnotationMethodInterceptor, this implementation merely delegates to the internal
+ * {@link AuthorizingAnnotationHandler AuthorizingAnnotationHandler} by first acquiring the annotation by
+ * calling {@link #getAnnotation(MethodInvocation) getAnnotation(methodInvocation)} and then calls
+ * {@link AuthorizingAnnotationHandler#assertAuthorized(java.lang.annotation.Annotation) handler.assertAuthorized(annotation)}.
+ *
+ * @param mi the <code>MethodInvocation</code> to check to see if it is allowed to proceed/execute.
+ * @throws AuthorizationException if the method invocation is not allowed to continue/execute.
+ */
+ public void assertAuthorized(MethodInvocation mi) throws AuthorizationException {
+ ((AuthorizingAnnotationHandler)getHandler()).assertAuthorized(getAnnotation(mi));
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/AuthorizingMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/AuthorizingMethodInterceptor.java
new file mode 100644
index 0000000..62b4747
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/AuthorizingMethodInterceptor.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.aop.MethodInterceptorSupport;
+import org.jsecurity.aop.MethodInvocation;
+import org.jsecurity.authz.AuthorizationException;
+
+/**
+ * Basic abstract class to support intercepting methods that perform authorization (access control) checks.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AuthorizingMethodInterceptor extends MethodInterceptorSupport {
+
+ /**
+ * Invokes the specified method (<code>methodInvocation.{@link org.jsecurity.aop.MethodInvocation#proceed proceed}()</code>
+ * if authorization is allowed by first
+ * calling {@link #assertAuthorized(org.jsecurity.aop.MethodInvocation) assertAuthorized}.
+ */
+ public Object invoke(MethodInvocation methodInvocation) throws Throwable {
+ assertAuthorized(methodInvocation);
+ return methodInvocation.proceed();
+ }
+
+ /**
+ * Asserts that the specified MethodInvocation is allowed to continue by performing any necessary authorization
+ * (access control) checks first.
+ * @param methodInvocation the <code>MethodInvocation</code> to invoke.
+ * @throws AuthorizationException if the <code>methodInvocation</code> should not be allowed to continue/execute.
+ */
+ protected abstract void assertAuthorized(MethodInvocation methodInvocation) throws AuthorizationException;
+
+}
diff --git a/core/src/org/jsecurity/authz/aop/GuestAnnotationHandler.java b/core/src/org/jsecurity/authz/aop/GuestAnnotationHandler.java
new file mode 100644
index 0000000..716a954
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/GuestAnnotationHandler.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.UnauthenticatedException;
+import org.jsecurity.authz.annotation.RequiresGuest;
+
+import java.lang.annotation.Annotation;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresGuest RequiresGuest} annotation
+ * is declared, and if so, ensures the calling <code>Subject</code> does <em>not</em>
+ * have an {@link org.jsecurity.subject.Subject#getPrincipal() identity} before invoking the method.
+ * <p>
+ * This annotation essentially ensures that <code>subject.{@link org.jsecurity.subject.Subject#getPrincipal() getPrincipal()} == null</code>.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class GuestAnnotationHandler extends AuthorizingAnnotationHandler {
+
+ /**
+ * Default no-argument constructor that ensures this interceptor looks for
+ *
+ * {@link org.jsecurity.authz.annotation.RequiresGuest RequiresGuest} annotations in a method
+ * declaration.
+ */
+ public GuestAnnotationHandler() {
+ super(RequiresGuest.class);
+ }
+
+ /**
+ * Ensures that the calling <code>Subject</code> is NOT a <em>user</em>, that is, they do not
+ * have an {@link org.jsecurity.subject.Subject#getPrincipal() identity} before continuing. If they are
+ * a user ({@link org.jsecurity.subject.Subject#getPrincipal() Subject.getPrincipal()} != null), an
+ * <code>AuthorizingException</code> will be thrown indicating that execution is not allowed to continue.
+ *
+ * @param a the annotation to check for one or more roles
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the calling <code>Subject</code> is not a "guest".
+ */
+ public void assertAuthorized(Annotation a) throws AuthorizationException {
+ if (a instanceof RequiresGuest && getSubject().getPrincipal() != null) {
+ throw new UnauthenticatedException("Attempting to perform a guest-only operation. The current Subject is " +
+ "not a guest (they have been authenticated or remembered from a previous login). Access " +
+ "denied.");
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/GuestAnnotationMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/GuestAnnotationMethodInterceptor.java
new file mode 100644
index 0000000..46b1ced
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/GuestAnnotationMethodInterceptor.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresGuest RequiresGuest} annotation
+ * is declared, and if so, ensures the calling <code>Subject</code> does <em>not</em>
+ * have an {@link org.jsecurity.subject.Subject#getPrincipal() identity} before invoking the method.
+ * <p>
+ * This annotation essentially ensures that <code>subject.{@link org.jsecurity.subject.Subject#getPrincipal() getPrincipal()} == null</code>.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class GuestAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
+
+ /**
+ * Default no-argument constructor that ensures this interceptor looks for
+ * {@link org.jsecurity.authz.annotation.RequiresGuest RequiresGuest} annotations in a method
+ * declaration.
+ */
+ public GuestAnnotationMethodInterceptor() {
+ super(new GuestAnnotationHandler());
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/PermissionAnnotationHandler.java b/core/src/org/jsecurity/authz/aop/PermissionAnnotationHandler.java
new file mode 100644
index 0000000..f92967a
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/PermissionAnnotationHandler.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.UnauthorizedException;
+import org.jsecurity.authz.annotation.RequiresPermissions;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.PermissionUtils;
+
+import java.lang.annotation.Annotation;
+import java.util.Set;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresPermissions RequiresPermissions} annotation is
+ * declared, and if so, performs a permission check to see if the calling <code>Subject</code> is allowed continued
+ * access.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class PermissionAnnotationHandler extends AuthorizingAnnotationHandler {
+
+ /**
+ * Default no-argument constructor that ensures this handler looks for
+ * {@link org.jsecurity.authz.annotation.RequiresPermissions RequiresPermissions} annotations.
+ */
+ public PermissionAnnotationHandler() {
+ super(RequiresPermissions.class);
+ }
+
+ /**
+ * Returns the annotation {@link RequiresPermissions#value value}, from which the Permission will be constructed.
+ *
+ * @param a the RequiresPermissions annotation being inspected.
+ * @return the annotation's <code>value</code>, from which the Permission will be constructed.
+ */
+ protected String getAnnotationValue(Annotation a) {
+ RequiresPermissions rpAnnotation = (RequiresPermissions)a;
+ return rpAnnotation.value();
+ }
+
+ /**
+ * Ensures that the calling <code>Subject</code> has the Annotation's specified permissions, and if not, throws an
+ * <code>AuthorizingException</code> indicating access is denied.
+ *
+ * @param a the RequiresPermission annotation being inspected to check for one or more permissions
+ * @throws org.jsecurity.authz.AuthorizationException if the calling <code>Subject</code> does not have the permission(s) necessary to
+ * continue access or execution.
+ */
+ public void assertAuthorized(Annotation a) throws AuthorizationException {
+ if ( !(a instanceof RequiresPermissions) ) {
+ return;
+ }
+ String p = getAnnotationValue(a);
+ Set<String> perms = PermissionUtils.toPermissionStrings(p);
+
+ Subject subject = getSubject();
+
+ if (perms.size() == 1) {
+ if (!subject.isPermitted(perms.iterator().next())) {
+ String msg = "Calling Subject does not have required permission [" + p + "]. " +
+ "Method invocation denied.";
+ throw new UnauthorizedException(msg);
+ }
+ } else {
+ String[] permStrings = new String[perms.size()];
+ permStrings = perms.toArray(permStrings);
+ if (!subject.isPermittedAll(permStrings)) {
+ String msg = "Calling Subject does not have required permissions [" + p + "]. " +
+ "Method invocation denied.";
+ throw new UnauthorizedException(msg);
+ }
+
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/PermissionAnnotationMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/PermissionAnnotationMethodInterceptor.java
new file mode 100644
index 0000000..1385e81
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/PermissionAnnotationMethodInterceptor.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.annotation.RequiresPermissions;
+
+/**
+ * Checks to see if a @{@link RequiresPermissions RequiresPermissions} annotation is declared, and if so, performs
+ * a permission check to see if the calling <code>Subject</code> is allowed to call the method.
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class PermissionAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
+
+ /*
+ * The character to look for that closes a permission definition.
+ **/
+ //private static final char ARRAY_CLOSE_CHAR = ']';
+
+ /**
+ * Default no-argument constructor that ensures this interceptor looks for
+ * {@link RequiresPermissions RequiresPermissions} annotations in a method declaration.
+ */
+ public PermissionAnnotationMethodInterceptor() {
+ super( new PermissionAnnotationHandler() );
+ }
+
+ /*
+ * Infers the permission from the specified name path in the annotation.
+ * @param methodArgs the <code>MethodInvocation</code> method arguments.
+ * @param namePath the Annotation 'name' value, which is a string-based permission definition.
+ * @return the String permission representation.
+ * @throws Exception if there is an error infering the target.
+ *
+ protected String inferTargetFromPath(Object[] methodArgs, String namePath) throws Exception {
+ int propertyStartIndex = -1;
+
+ char[] chars = namePath.toCharArray();
+ StringBuilder buf = new StringBuilder();
+ //init iteration at index 1 (instead of 0). This is because the first
+ //character must be the ARRAY_OPEN_CHAR (eliminates unnecessary iteration)
+ for (int i = 1; i < chars.length; i++) {
+ if (chars[i] == ARRAY_CLOSE_CHAR) {
+ // skip the delimiting period after the ARRAY_CLOSE_CHAR. The resulting
+ // index is the init of the property path that we'll use with
+ // BeanUtils.getProperty:
+ propertyStartIndex = i + 2;
+ break;
+ } else {
+ buf.append(chars[i]);
+ }
+ }
+
+ Integer methodArgIndex = Integer.parseInt(buf.toString());
+ String beanUtilsPath = new String(chars, propertyStartIndex,
+ chars.length - propertyStartIndex);
+ Object targetValue = PropertyUtils.getProperty(methodArgs[methodArgIndex], beanUtilsPath);
+ return targetValue.toString();
+ }
+
+ /*
+ * Returns the <code>MethodInvocation</code>'s arguments, or <code>null</code> if there were none.
+ * @param invocation the methodInvocation to inspect.
+ * @return the method invocation's method arguments, or <code>null</code> if there were none.
+ *
+ protected Object[] getMethodArguments(MethodInvocation invocation) {
+ if (invocation != null) {
+ return invocation.getArguments();
+ } else {
+ return null;
+ }
+ }
+
+ /*
+ * Returns the annotation {@link RequiresPermissions#value value}, from which the Permission will be constructed.
+ *
+ * @param invocation the method being invoked.
+ * @return the method annotation's <code>value</code>, from which the Permission will be constructed.
+ *
+ protected String getAnnotationValue(MethodInvocation invocation) {
+ RequiresPermissions prAnnotation = (RequiresPermissions) getAnnotation(invocation);
+ return prAnnotation.value();
+ } */
+}
diff --git a/core/src/org/jsecurity/authz/aop/RoleAnnotationHandler.java b/core/src/org/jsecurity/authz/aop/RoleAnnotationHandler.java
new file mode 100644
index 0000000..7532267
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/RoleAnnotationHandler.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.UnauthorizedException;
+import org.jsecurity.authz.annotation.RequiresRoles;
+
+import java.lang.annotation.Annotation;
+import java.util.Arrays;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresRoles RequiresRoles} annotation is declared, and if so, performs
+ * a role check to see if the calling <code>Subject</code> is allowed to proceed.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class RoleAnnotationHandler extends AuthorizingAnnotationHandler {
+
+ /**
+ * Default no-argument constructor that ensures this handler looks for
+ * {@link org.jsecurity.authz.annotation.RequiresRoles RequiresRoles} annotations.
+ */
+ public RoleAnnotationHandler() {
+ super(RequiresRoles.class);
+ }
+
+ /**
+ * Ensures that the calling <code>Subject</code> has the Annotation's specified roles, and if not, throws an
+ * <code>AuthorizingException</code> indicating that access is denied.
+ *
+ * @param a the RequiresRoles annotation to use to check for one or more roles
+ * @throws org.jsecurity.authz.AuthorizationException if the calling <code>Subject</code> does not have the role(s) necessary to
+ * proceed.
+ */
+ public void assertAuthorized(Annotation a) throws AuthorizationException {
+ if ( !(a instanceof RequiresRoles ) ) {
+ return;
+ }
+ RequiresRoles rrAnnotation = (RequiresRoles)a;
+
+ String roleId = rrAnnotation.value();
+
+ String[] roles = roleId.split(",");
+
+ if (roles.length == 1) {
+ if (!getSubject().hasRole(roles[0])) {
+ String msg = "Calling Subject does not have required role [" + roleId + "]. " +
+ "MethodInvocation denied.";
+ throw new UnauthorizedException(msg);
+ }
+ } else {
+ Set<String> rolesSet = new LinkedHashSet<String>(Arrays.asList(roles));
+ if (!getSubject().hasAllRoles(rolesSet)) {
+ String msg = "Calling Subject does not have required roles [" + roleId + "]. " +
+ "MethodInvocation denied.";
+ throw new UnauthorizedException(msg);
+ }
+ }
+ }
+
+}
diff --git a/core/src/org/jsecurity/authz/aop/RoleAnnotationMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/RoleAnnotationMethodInterceptor.java
new file mode 100644
index 0000000..683ef8a
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/RoleAnnotationMethodInterceptor.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.annotation.RequiresRoles;
+
+/**
+ * Checks to see if a @{@link RequiresRoles RequiresRoles} annotation is declared, and if so, performs
+ * a role check to see if the calling <code>Subject</code> is allowed to invoke the method.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class RoleAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
+
+ /**
+ * Default no-argument constructor that ensures this interceptor looks for
+ * {@link RequiresRoles RequiresRoles} annotations in a method declaration.
+ */
+ public RoleAnnotationMethodInterceptor() {
+ super( new RoleAnnotationHandler() );
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/UserAnnotationHandler.java b/core/src/org/jsecurity/authz/aop/UserAnnotationHandler.java
new file mode 100644
index 0000000..57d9165
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/UserAnnotationHandler.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.UnauthenticatedException;
+import org.jsecurity.authz.annotation.RequiresUser;
+
+import java.lang.annotation.Annotation;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresUser RequiresUser} annotation
+ * is declared, and if so, ensures the calling <code>Subject</code> is <em>either</em>
+ * {@link org.jsecurity.subject.Subject#isAuthenticated() authenticated} <b><em>or</em></b> remembered via remember
+ * me services before allowing access.
+ * <p>
+ * This annotation essentially ensures that <code>subject.{@link org.jsecurity.subject.Subject#getPrincipal() getPrincipal()} != null</code>.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class UserAnnotationHandler extends AuthorizingAnnotationHandler {
+
+ /**
+ * Default no-argument constructor that ensures this handler looks for
+ *
+ * {@link org.jsecurity.authz.annotation.RequiresUser RequiresUser} annotations.
+ */
+ public UserAnnotationHandler() {
+ super(RequiresUser.class);
+ }
+
+ /**
+ * Ensures that the calling <code>Subject</code> is a <em>user</em>, that is, they are <em>either</code>
+ * {@link org.jsecurity.subject.Subject#isAuthenticated() authenticated} <b><em>or</em></b> remembered via remember
+ * me services before allowing access, and if not, throws an
+ * <code>AuthorizingException</code> indicating access is not allowed.
+ *
+ * @param a the RequiresUser annotation to check
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the calling <code>Subject</code> is not authenticated or remembered via rememberMe services.
+ */
+ public void assertAuthorized(Annotation a) throws AuthorizationException {
+ if (a instanceof RequiresUser && getSubject().getPrincipal() == null) {
+ throw new UnauthenticatedException("Attempting to perform a user-only operation. The current Subject is " +
+ "not a user (they haven't been authenticated or remembered from a previous login). " +
+ "Access denied.");
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/authz/aop/UserAnnotationMethodInterceptor.java b/core/src/org/jsecurity/authz/aop/UserAnnotationMethodInterceptor.java
new file mode 100644
index 0000000..374c726
--- /dev/null
+++ b/core/src/org/jsecurity/authz/aop/UserAnnotationMethodInterceptor.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.aop;
+
+/**
+ * Checks to see if a @{@link org.jsecurity.authz.annotation.RequiresUser RequiresUser} annotation
+ * is declared, and if so, ensures the calling <code>Subject</code> is <em>either</em>
+ * {@link org.jsecurity.subject.Subject#isAuthenticated() authenticated} <b><em>or</em></b> remembered via remember
+ * me services before invoking the method.
+ * <p>
+ * This annotation essentially ensures that <code>subject.{@link org.jsecurity.subject.Subject#getPrincipal() getPrincipal()} != null</code>.
+ *
+ * @author Les Hazlewood
+ * @since 0.9.0
+ */
+public class UserAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
+
+ /**
+ * Default no-argument constructor that ensures this interceptor looks for
+ *
+ * {@link org.jsecurity.authz.annotation.RequiresUser RequiresUser} annotations in a method
+ * declaration.
+ */
+ public UserAnnotationMethodInterceptor() {
+ super( new UserAnnotationHandler() );
+ }
+
+}
diff --git a/core/src/org/jsecurity/authz/permission/AllPermission.java b/core/src/org/jsecurity/authz/permission/AllPermission.java
new file mode 100644
index 0000000..baac423
--- /dev/null
+++ b/core/src/org/jsecurity/authz/permission/AllPermission.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.permission;
+
+import org.jsecurity.authz.Permission;
+
+import java.io.Serializable;
+
+/**
+ * An all <tt>AllPermission</tt> instance is one that always implies any other permission; that is, its
+ * {@link #implies implies} method always returns <tt>true</tt>.
+ *
+ * <p>You should be very careful about the users, roles, and/or groups to which this permission is assigned since
+ * those respective entities will have the ability to do anything. As such, an instance of this class
+ * is typically only assigned only to "root" or "administrator" users or roles.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class AllPermission implements Permission, Serializable {
+
+ /**
+ * Always returns <tt>true</tt>, indicating any Subject granted this permission can do anything.
+ *
+ * @param p the Permission to check for implies logic.
+ * @return <tt>true</tt> always, indicating any Subject grated this permission can do anything.
+ */
+ public boolean implies(Permission p) {
+ return true;
+ }
+}
diff --git a/core/src/org/jsecurity/authz/permission/InvalidPermissionStringException.java b/core/src/org/jsecurity/authz/permission/InvalidPermissionStringException.java
new file mode 100644
index 0000000..520b1ea
--- /dev/null
+++ b/core/src/org/jsecurity/authz/permission/InvalidPermissionStringException.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.permission;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * Thrown by {@link PermissionResolver#resolvePermission(String)} when the String being parsed is not
+ * valid for that resolver.
+ *
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public class InvalidPermissionStringException extends JSecurityException {
+
+ private String permissionString;
+
+ /**
+ * Constructs a new exception with the given message and permission string.
+ *
+ * @param message the exception message.
+ * @param permissionString the invalid permission string.
+ */
+ public InvalidPermissionStringException(String message, String permissionString) {
+ super(message);
+ this.permissionString = permissionString;
+ }
+
+ /**
+ * Returns the permission string that was invalid and caused this exception to
+ * be thrown.
+ *
+ * @return the permission string.
+ */
+ public String getPermissionString() {
+ return this.permissionString;
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/authz/permission/PermissionResolver.java b/core/src/org/jsecurity/authz/permission/PermissionResolver.java
new file mode 100644
index 0000000..5d34ffb
--- /dev/null
+++ b/core/src/org/jsecurity/authz/permission/PermissionResolver.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.permission;
+
+import org.jsecurity.authz.Permission;
+
+/**
+ * <p>A PermisisonResolver resolves a String value and converts it into a
+ * {@link org.jsecurity.authz.Permission} instance.
+ *
+ * <p>The default {@link org.jsecurity.authz.permission.WildcardPermissionResolver} should be
+ * suitable for most purposes, which constructs {@link org.jsecurity.authz.permission.WildcardPermission} objects.
+ * However, any resolver may be configured if an application wishes to use different
+ * {@link org.jsecurity.authz.Permission} implementations.</p>
+ *
+ * <p>A <tt>PermissionResolver</tt> is used by many JSecurity components such as annotations, property file
+ * configuration, URL configuration, etc. It is useful whenever a String representation of a permission is specified
+ * and that String needs to be converted to a Permission instance before executing a security check.</p>
+ * <p/>
+ * JSecurity chooses to support {@link WildcardPermission Wildcardpermission}s by default in almost all components and
+ * we do that in the form of the {@link WildcardPermissionResolver WildcardPermissionResolver}. One of the nice
+ * things about <code>WildcardPermission</code>s being supported by default is that it makes it very easy to
+ * store complex permissions in the database - and also makes it very easy to represent permissions in JSP files,
+ * annotations, etc., where a simple string representation is useful.
+ * <p/>
+ * Although this happens to be the JSecurity default, you are of course free to provide custom
+ * String-to-Permission conversion by providing JSecurity components any instance of this interface.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see org.jsecurity.mgt.AuthorizingSecurityManager#setPermissionResolver(PermissionResolver) AuthorizingSecurityManager.setPermissionResolver
+ * @see org.jsecurity.authz.ModularRealmAuthorizer#setPermissionResolver(PermissionResolver) ModularRealmAuthorizer.setPermissionResolver
+ * @see org.jsecurity.realm.AuthorizingRealm#setPermissionResolver(PermissionResolver) AuthorizingRealm.setPermissionResolver
+ * @see PermissionResolverAware PermissionResolverAware
+ * @since 0.9
+ */
+public interface PermissionResolver {
+
+ /**
+ * Resolves a Permission based on the given String representation.
+ *
+ * @param permissionString the String representation of a permission.
+ * @return A Permission object that can be used internally to determine a subject's permissions.
+ * @throws InvalidPermissionStringException
+ * if the permission string is not valid for this resolver.
+ */
+ Permission resolvePermission(String permissionString);
+
+}
diff --git a/core/src/org/jsecurity/authz/permission/PermissionResolverAware.java b/core/src/org/jsecurity/authz/permission/PermissionResolverAware.java
new file mode 100644
index 0000000..f82e369
--- /dev/null
+++ b/core/src/org/jsecurity/authz/permission/PermissionResolverAware.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.permission;
+
+/**
+ * Interface implemented by a component that wishes to use any application-configured <tt>PermissionResolver</tt> that
+ * might already exist instead of potentially creating one itself.
+ *
+ * <p>This is mostly implemented by {@link org.jsecurity.authz.Authorizer Authorizer} and
+ * {@link org.jsecurity.realm.Realm Realm} implementations since they
+ * are the ones performing permission checks and need to know how to resolve Strings into
+ * {@link org.jsecurity.authz.Permission Permission} instances.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface PermissionResolverAware {
+
+ /**
+ * Sets the specified <tt>PermissionResolver</tt> on this instance.
+ *
+ * @param pr the <tt>PermissionResolver</tt> being set.
+ */
+ public void setPermissionResolver(PermissionResolver pr);
+}
diff --git a/core/src/org/jsecurity/authz/permission/WildcardPermission.java b/core/src/org/jsecurity/authz/permission/WildcardPermission.java
new file mode 100644
index 0000000..aaf8f0a
--- /dev/null
+++ b/core/src/org/jsecurity/authz/permission/WildcardPermission.java
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.permission;
+
+import org.jsecurity.authz.Permission;
+import org.jsecurity.util.CollectionUtils;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A <code>WildcardPermission</code> is a very flexible permission construct supporting multiple levels of
+ * permission matching. However, most people will probably follow some standard conventions as explained below.
+ *
+ * <h3>Simple Usage</h3>
+ *
+ * In the simplest form, <code>WildcardPermission</code> can be used as a simple permission string. You could grant a
+ * user an "editNewsletter" permission and then check to see if the user has the editNewsletter
+ * permission by calling
+ * <p/>
+ * <code>subject.isPermitted("editNewsletter")</code>
+ * <p/>
+ * This is (mostly) equivalent to
+ * <p/>
+ * <code>subject.isPermitted( new WildcardPermission("editNewsletter") )</code>
+ * <p/>
+ * but more on that later.
+ * <p/>
+ * The simple permission string may work for simple applications, but it requires you to have permissions like
+ * <code>"viewNewsletter"</code>, <code>"deleteNewsletter"</code>,
+ * <code>"createNewsletter"</code>, etc. You can also grant a user <code>"*"</code> permissions
+ * using the wildcard character (giving this class its name), which means they have <em>all</em> permissions. But
+ * using this approach there's no way to just say a user has "all newsletter permissions".
+ * <p/>
+ * For this reason, <code>WildcardPermission</code> supports multiple <em>levels</em> of permissioning.
+ *
+ * <h3>Multiple Levels</h3>
+ *
+ * WildcardPermission</code> also supports the concept of multiple <em>levels</em>. For example, you could
+ * restructure the previous simple example by granting a user the permission <code>"newsletter:edit"</code>.
+ * The colon in this example is a special character used by the <code>WildcardPermission</code> that delimits the
+ * next token in the permission.
+ * <p/>
+ * In this example, the first token is the <em>domain</em> that is being operated on
+ * and the second token is the <em>action</em> being performed. Each level can contain multiple values. So you
+ * could simply grant a user the permission <code>"newsletter:view,edit,create"</code> which gives them
+ * access to perform <code>view</code>, <code>edit</code>, and <code>create</code> actions in the <code>newsletter</code>
+ * <em>domain</em>. Then you could check to see if the user has the <code>"newsletter:create"</code>
+ * permission by calling
+ * <p/>
+ * <code>subject.isPermitted("newsletter:create")</code>
+ * <p/>
+ * (which would return true).
+ * <p/>
+ * In addition to granting multiple permissions via a single string, you can grant all permission for a particular
+ * level. So if you wanted to grant a user all actions in the <code>newsletter</code> domain, you could simply give
+ * them <code>"newsletter:*"</code>. Now, any permission check for <code>"newsletter:XXX"</code>
+ * will return <code>true</code>. It is also possible to use the wildcard token at the domain level (or both): so you
+ * could grant a user the <code>"view"</code> action across all domains <code>"*:view"</code>.
+ *
+ * <h3>Instance-level Access Control</h3>
+ *
+ * Another common usage of the <code>WildcardPermission</code> is to model instance-level Access Control Lists.
+ * In this scenario you use three tokens - the first is the <em>domain</em>, the second is the <em>action</em>, and
+ * the third is the <em>instance</em> you are acting on.
+ * <p/>
+ * So for example you could grant a user <code>"newsletter:edit:12,13,18"</code>. In this example, assume
+ * that the third token is the system's ID of the newsletter. That would allow the user to edit newsletters
+ * <code>12</code>, <code>13</code>, and <code>18</code>. This is an extremely powerful way to express permissions,
+ * since you can now say things like <code>"newsletter:*:13"</code> (grant a user all actions for newsletter
+ * <code>13</code>), <code>"newsletter:view,create,edit:*"</code> (allow the user to
+ * <code>view</code>, <code>create</code>, or <code>edit</code> <em>any</em> newsletter), or
+ * <code>"newsletter:*:*</code> (allow the user to perform <em>any</em> action on <em>any</em> newsletter).
+ * <p/>
+ * To perform checks against these instance-level permissions, the application should include the instance ID in the
+ * permission check like so:
+ * <p/>
+ * <code>subject.isPermitted( "newsletter:edit:13" )</code>
+ * <p/>
+ * There is no limit to the number of tokens that can be used, so it is up to your imagination in terms of ways that
+ * this could be used in your application. However, the JSecurity team likes to standardize some common usages shown
+ * above to help people get started and provide consistency in the JSecurity community.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class WildcardPermission implements Permission, Serializable {
+
+ //TODO - JavaDoc methods
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+ protected static final String WILDCARD_TOKEN = "*";
+ protected static final String PART_DIVIDER_TOKEN = ":";
+ protected static final String SUBPART_DIVIDER_TOKEN = ",";
+ protected static final boolean DEFAULT_CASE_SENSITIVE = false;
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ private List<Set<String>> parts;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+ public WildcardPermission(String wildcardString) {
+ this(wildcardString, DEFAULT_CASE_SENSITIVE);
+ }
+
+ public WildcardPermission(String wildcardString, boolean caseSensitive) {
+ if (wildcardString == null || wildcardString.trim().length() == 0) {
+ throw new IllegalArgumentException("Wildcard string cannot be null or empty. Make sure permission strings are properly formatted.");
+ }
+
+ wildcardString = wildcardString.trim();
+
+ List<String> parts = CollectionUtils.asList(wildcardString.split(PART_DIVIDER_TOKEN));
+
+ this.parts = new ArrayList<Set<String>>();
+ for (String part : parts) {
+ Set<String> subparts = CollectionUtils.asSet(part.split(SUBPART_DIVIDER_TOKEN));
+
+ if (!caseSensitive) {
+ subparts = lowercase(subparts);
+ }
+
+ if (subparts.isEmpty()) {
+ throw new IllegalArgumentException("Wildcard string cannot contain parts with only dividers. Make sure permission strings are properly formatted.");
+ }
+
+ this.parts.add(subparts);
+ }
+
+ if (this.parts.isEmpty()) {
+ throw new IllegalArgumentException("Wildcard string cannot contain only dividers. Make sure permission strings are properly formatted.");
+ }
+ }
+
+ private Set<String> lowercase(Set<String> subparts) {
+ Set<String> lowerCasedSubparts = new LinkedHashSet<String>(subparts.size());
+ for (String subpart : subparts) {
+ lowerCasedSubparts.add(subpart.toLowerCase());
+ }
+ return lowerCasedSubparts;
+ }
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+ protected List<Set<String>> getParts() {
+ return this.parts;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+
+ public boolean implies(Permission p) {
+ // By default only supports comparisons with other WildcardPermissions
+ if (!(p instanceof WildcardPermission)) {
+ return false;
+ }
+
+ WildcardPermission wp = (WildcardPermission) p;
+
+ List<Set<String>> otherParts = wp.getParts();
+
+ int i = 0;
+ for (Set<String> otherPart : otherParts) {
+
+ // If this permission has less parts than the other permission, everything after the number of parts contained
+ // in this permission is automatically implied, so return true
+ if (getParts().size() - 1 < i) {
+ return true;
+
+ } else {
+ Set<String> part = getParts().get(i);
+
+ if (!part.contains(WILDCARD_TOKEN) && !part.containsAll(otherPart)) {
+ return false;
+ }
+
+ i++;
+ }
+
+ }
+
+ // If this permission has more parts than the other parts, only imply it if all of the other parts are wildcards
+ for (; i < getParts().size(); i++) {
+ Set<String> part = getParts().get(i);
+ if (!part.contains(WILDCARD_TOKEN)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/core/src/org/jsecurity/authz/permission/WildcardPermissionResolver.java b/core/src/org/jsecurity/authz/permission/WildcardPermissionResolver.java
new file mode 100644
index 0000000..f40e05a
--- /dev/null
+++ b/core/src/org/jsecurity/authz/permission/WildcardPermissionResolver.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.authz.permission;
+
+import org.jsecurity.authz.Permission;
+
+/**
+ * <tt>PermissionResolver</tt> implementation that returns a new {@link WildcardPermission WildcardPermission}
+ * based on the input string.
+ *
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public class WildcardPermissionResolver implements PermissionResolver {
+
+ /**
+ * Returns a new {@link WildcardPermission WildcardPermission} instance constructed based on the specified
+ * <tt>permissionString</tt>.
+ *
+ * @param permissionString the permission string to convert to a {@link Permission Permission} instance.
+ * @return a new {@link WildcardPermission WildcardPermission} instance constructed based on the specified
+ * <tt>permissionString</tt>
+ */
+ public Permission resolvePermission(String permissionString) {
+ return new WildcardPermission(permissionString);
+ }
+}
diff --git a/core/src/org/jsecurity/codec/Base64.java b/core/src/org/jsecurity/codec/Base64.java
new file mode 100644
index 0000000..36a68e5
--- /dev/null
+++ b/core/src/org/jsecurity/codec/Base64.java
@@ -0,0 +1,506 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.codec;
+
+/**
+ * Provides Base64 encoding and decoding as defined by RFC 2045.
+ *
+ * <p>
+ * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
+ * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
+ * </p>
+ *
+ * <p>This class was borrowed from Apache Commons Codec SVN repository (rev. 618419) with modifications
+ * to enable Base64 conversion without a full dependecny on Commons Codec. We didn't want to reinvent the wheel of
+ * great work they've done, but also didn't want to force every JSecurity user to depend on the commons-codec.jar</p>
+ *
+ * <p>As per the Apache 2.0 license, the original copyright notice and all author and copyright information have
+ * remained in tact.</p>
+ *
+ * @author Apache Software Foundation
+ * @author Les Hazlewood
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
+ * @since 0.9
+ */
+public class Base64 {
+
+ /**
+ * Chunk size per RFC 2045 section 6.8.
+ *
+ * <p>The character limit does not count the trailing CRLF, but counts all other characters, including any
+ * equal signs.</p>
+ *
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
+ */
+ static final int CHUNK_SIZE = 76;
+
+ /**
+ * Chunk separator per RFC 2045 section 2.1.
+ *
+ * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
+ */
+ static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
+
+ /**
+ * The base length.
+ */
+ private static final int BASELENGTH = 255;
+
+ /**
+ * Lookup length.
+ */
+ private static final int LOOKUPLENGTH = 64;
+
+ /**
+ * Used to calculate the number of bits in a byte.
+ */
+ private static final int EIGHTBIT = 8;
+
+ /**
+ * Used when encoding something which has fewer than 24 bits.
+ */
+ private static final int SIXTEENBIT = 16;
+
+ /**
+ * Used to determine how many bits data contains.
+ */
+ private static final int TWENTYFOURBITGROUP = 24;
+
+ /**
+ * Used to get the number of Quadruples.
+ */
+ private static final int FOURBYTE = 4;
+
+ /**
+ * Used to test the sign of a byte.
+ */
+ private static final int SIGN = -128;
+
+ /**
+ * Byte used to pad output.
+ */
+ private static final byte PAD = (byte) '=';
+
+ /**
+ * Contains the Base64 values <code>0</code> through <code>63</code> accessed by using character encodings as
+ * indices.
+ *
+ * <p>For example, <code>base64Alphabet['+']</code> returns <code>62</code>.</p>
+ *
+ * <p>The value of undefined encodings is <code>-1</code>.</p>
+ */
+ private static final byte[] base64Alphabet = new byte[BASELENGTH];
+
+ /**
+ * <p>Contains the Base64 encodings <code>A</code> through <code>Z</code>, followed by <code>a</code> through
+ * <code>z</code>, followed by <code>0</code> through <code>9</code>, followed by <code>+</code>, and
+ * <code>/</code>.</p>
+ *
+ * <p>This array is accessed by using character values as indices.</p>
+ *
+ * <p>For example, <code>lookUpBase64Alphabet[62] </code> returns <code>'+'</code>.</p>
+ */
+ private static final byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
+
+ // Populating the lookup and character arrays
+ static {
+ for (int i = 0; i < BASELENGTH; i++) {
+ base64Alphabet[i] = (byte) -1;
+ }
+ for (int i = 'Z'; i >= 'A'; i--) {
+ base64Alphabet[i] = (byte) (i - 'A');
+ }
+ for (int i = 'z'; i >= 'a'; i--) {
+ base64Alphabet[i] = (byte) (i - 'a' + 26);
+ }
+ for (int i = '9'; i >= '0'; i--) {
+ base64Alphabet[i] = (byte) (i - '0' + 52);
+ }
+
+ base64Alphabet['+'] = 62;
+ base64Alphabet['/'] = 63;
+
+ for (int i = 0; i <= 25; i++) {
+ lookUpBase64Alphabet[i] = (byte) ('A' + i);
+ }
+
+ for (int i = 26, j = 0; i <= 51; i++, j++) {
+ lookUpBase64Alphabet[i] = (byte) ('a' + j);
+ }
+
+ for (int i = 52, j = 0; i <= 61; i++, j++) {
+ lookUpBase64Alphabet[i] = (byte) ('0' + j);
+ }
+
+ lookUpBase64Alphabet[62] = (byte) '+';
+ lookUpBase64Alphabet[63] = (byte) '/';
+ }
+
+ /**
+ * Returns whether or not the <code>octect</code> is in the base 64 alphabet.
+ *
+ * @param octect The value to test
+ * @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
+ */
+ private static boolean isBase64(byte octect) {
+ if (octect == PAD) {
+ return true;
+ } else if (octect < 0 || base64Alphabet[octect] == -1) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ /**
+ * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.
+ *
+ * @param arrayOctect byte array to test
+ * @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is
+ * empty; false, otherwise
+ */
+ public static boolean isBase64(byte[] arrayOctect) {
+
+ arrayOctect = discardWhitespace(arrayOctect);
+
+ int length = arrayOctect.length;
+ if (length == 0) {
+ // shouldn't a 0 length array be valid base64 data?
+ // return false;
+ return true;
+ }
+ for (int i = 0; i < length; i++) {
+ if (!isBase64(arrayOctect[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Discards any whitespace from a base-64 encoded block.
+ *
+ * @param data The base-64 encoded data to discard the whitespace from.
+ * @return The data, less whitespace (see RFC 2045).
+ */
+ static byte[] discardWhitespace(byte[] data) {
+ byte groomedData[] = new byte[data.length];
+ int bytesCopied = 0;
+
+ for (byte aByte : data) {
+ switch (aByte) {
+ case (byte) ' ':
+ case (byte) '\n':
+ case (byte) '\r':
+ case (byte) '\t':
+ break;
+ default:
+ groomedData[bytesCopied++] = aByte;
+ }
+ }
+
+ byte packedData[] = new byte[bytesCopied];
+
+ System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+ return packedData;
+ }
+
+ /**
+ * Base64 encodes the specified byte array and then encodes it as a String using JSecurity's preferred character
+ * encoding (UTF-8).
+ *
+ * @param bytes the byte array to Base64 encode.
+ * @return a UTF-8 encoded String of the resulting Base64 encoded byte array.
+ */
+ public static String encodeToString(byte[] bytes) {
+ byte[] encoded = encode(bytes);
+ return CodecSupport.toString(encoded);
+ }
+
+ /**
+ * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
+ *
+ * @param binaryData binary data to encodeToChars
+ * @return Base64 characters chunked in 76 character blocks
+ */
+ public static byte[] encodeChunked(byte[] binaryData) {
+ return encode(binaryData, true);
+ }
+
+ /**
+ * Encodes a byte[] containing binary data, into a byte[] containing characters in the Base64 alphabet.
+ *
+ * @param pArray a byte array containing binary data
+ * @return A byte array containing only Base64 character data
+ */
+ public static byte[] encode(byte[] pArray) {
+ return encode(pArray, false);
+ }
+
+ /**
+ * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
+ *
+ * @param binaryData Array containing binary data to encodeToChars.
+ * @param isChunked if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
+ * @return Base64-encoded data.
+ * @throws IllegalArgumentException Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
+ */
+ public static byte[] encode(byte[] binaryData, boolean isChunked) {
+ long binaryDataLength = binaryData.length;
+ long lengthDataBits = binaryDataLength * EIGHTBIT;
+ long fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
+ long tripletCount = lengthDataBits / TWENTYFOURBITGROUP;
+ long encodedDataLengthLong = 0;
+ int chunckCount = 0;
+
+ if (fewerThan24bits != 0) {
+ // data not divisible by 24 bit
+ encodedDataLengthLong = (tripletCount + 1) * 4;
+ } else {
+ // 16 or 8 bit
+ encodedDataLengthLong = tripletCount * 4;
+ }
+
+ // If the output is to be "chunked" into 76 character sections,
+ // for compliance with RFC 2045 MIME, then it is important to
+ // allow for extra length to account for the separator(s)
+ if (isChunked) {
+
+ chunckCount = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math
+ .ceil((float) encodedDataLengthLong / CHUNK_SIZE));
+ encodedDataLengthLong += chunckCount * CHUNK_SEPARATOR.length;
+ }
+
+ if (encodedDataLengthLong > Integer.MAX_VALUE) {
+ throw new IllegalArgumentException(
+ "Input array too big, output array would be bigger than Integer.MAX_VALUE=" + Integer.MAX_VALUE);
+ }
+ int encodedDataLength = (int) encodedDataLengthLong;
+ byte encodedData[] = new byte[encodedDataLength];
+
+ byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
+
+ int encodedIndex = 0;
+ int dataIndex = 0;
+ int i = 0;
+ int nextSeparatorIndex = CHUNK_SIZE;
+ int chunksSoFar = 0;
+
+ // log.debug("number of triplets = " + numberTriplets);
+ for (i = 0; i < tripletCount; i++) {
+ dataIndex = i * 3;
+ b1 = binaryData[dataIndex];
+ b2 = binaryData[dataIndex + 1];
+ b3 = binaryData[dataIndex + 2];
+
+ // log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
+
+ l = (byte) (b2 & 0x0f);
+ k = (byte) (b1 & 0x03);
+
+ byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+ byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+ byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
+
+ encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+ // log.debug( "val2 = " + val2 );
+ // log.debug( "k4 = " + (k<<4) );
+ // log.debug( "vak = " + (val2 | (k<<4)) );
+ encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
+ encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3];
+ encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
+
+ encodedIndex += 4;
+
+ // If we are chunking, let's put a chunk separator down.
+ if (isChunked) {
+ // this assumes that CHUNK_SIZE % 4 == 0
+ if (encodedIndex == nextSeparatorIndex) {
+ System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length);
+ chunksSoFar++;
+ nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length);
+ encodedIndex += CHUNK_SEPARATOR.length;
+ }
+ }
+ }
+
+ // form integral number of 6-bit groups
+ dataIndex = i * 3;
+
+ if (fewerThan24bits == EIGHTBIT) {
+ b1 = binaryData[dataIndex];
+ k = (byte) (b1 & 0x03);
+ // log.debug("b1=" + b1);
+ // log.debug("b1<<2 = " + (b1>>2) );
+ byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+ encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+ encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
+ encodedData[encodedIndex + 2] = PAD;
+ encodedData[encodedIndex + 3] = PAD;
+ } else if (fewerThan24bits == SIXTEENBIT) {
+
+ b1 = binaryData[dataIndex];
+ b2 = binaryData[dataIndex + 1];
+ l = (byte) (b2 & 0x0f);
+ k = (byte) (b1 & 0x03);
+
+ byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+ byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+
+ encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+ encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)];
+ encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
+ encodedData[encodedIndex + 3] = PAD;
+ }
+
+ if (isChunked) {
+ // we also add a separator to the end of the final chunk.
+ if (chunksSoFar < chunckCount) {
+ System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length,
+ CHUNK_SEPARATOR.length);
+ }
+ }
+
+ return encodedData;
+ }
+
+ /**
+ * Converts the specified UTF-8 Base64 encoded String and decodes it to a resultant UTF-8 encoded string.
+ *
+ * @param base64Encoded a UTF-8 Base64 encoded String
+ * @return the decoded String, UTF-8 encoded.
+ */
+ public static String decodeToString(String base64Encoded) {
+ byte[] encodedBytes = CodecSupport.toBytes(base64Encoded);
+ return decodeToString(encodedBytes);
+ }
+
+ /**
+ * Decodes the specified Base64 encoded byte array and returns the decoded result as a UTF-8 encoded.
+ *
+ * @param base64Encoded a Base64 encoded byte array
+ * @return the decoded String, UTF-8 encoded.
+ */
+ public static String decodeToString(byte[] base64Encoded) {
+ byte[] decoded = decode(base64Encoded);
+ return CodecSupport.toString(decoded);
+ }
+
+ /**
+ * Converts the specified UTF-8 Base64 encoded String and decodes it to a raw Base64 decoded byte array.
+ *
+ * @param base64Encoded a UTF-8 Base64 encoded String
+ * @return the raw Base64 decoded byte array.
+ */
+ public static byte[] decode(String base64Encoded) {
+ byte[] bytes = CodecSupport.toBytes(base64Encoded);
+ return decode(bytes);
+ }
+
+ /**
+ * Decodes Base64 data into octects
+ *
+ * @param base64Data Byte array containing Base64 data
+ * @return Array containing decoded data.
+ */
+ public static byte[] decode(byte[] base64Data) {
+ // RFC 2045 requires that we discard ALL non-Base64 characters
+ base64Data = discardNonBase64(base64Data);
+
+ // handle the edge case, so we don't have to worry about it later
+ if (base64Data.length == 0) {
+ return new byte[0];
+ }
+
+ int numberQuadruple = base64Data.length / FOURBYTE;
+ byte decodedData[] = null;
+ byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
+
+ // Throw away anything not in base64Data
+
+ int encodedIndex = 0;
+ int dataIndex = 0;
+ {
+ // this sizes the output array properly - rlw
+ int lastData = base64Data.length;
+ // ignore the '=' padding
+ while (base64Data[lastData - 1] == PAD) {
+ if (--lastData == 0) {
+ return new byte[0];
+ }
+ }
+ decodedData = new byte[lastData - numberQuadruple];
+ }
+
+ for (int i = 0; i < numberQuadruple; i++) {
+ dataIndex = i * 4;
+ marker0 = base64Data[dataIndex + 2];
+ marker1 = base64Data[dataIndex + 3];
+
+ b1 = base64Alphabet[base64Data[dataIndex]];
+ b2 = base64Alphabet[base64Data[dataIndex + 1]];
+
+ if (marker0 != PAD && marker1 != PAD) {
+ // No PAD e.g 3cQl
+ b3 = base64Alphabet[marker0];
+ b4 = base64Alphabet[marker1];
+
+ decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+ decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+ decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
+ } else if (marker0 == PAD) {
+ // Two PAD e.g. 3c[Pad][Pad]
+ decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+ } else if (marker1 == PAD) {
+ // One PAD e.g. 3cQ[Pad]
+ b3 = base64Alphabet[marker0];
+ decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+ decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+ }
+ encodedIndex += 3;
+ }
+ return decodedData;
+ }
+
+ /**
+ * Discards any characters outside of the base64 alphabet, per the requirements on page 25 of RFC 2045 - "Any
+ * characters outside of the base64 alphabet are to be ignored in base64 encoded data."
+ *
+ * @param data The base-64 encoded data to groom
+ * @return The data, less non-base64 characters (see RFC 2045).
+ */
+ static byte[] discardNonBase64(byte[] data) {
+ byte groomedData[] = new byte[data.length];
+ int bytesCopied = 0;
+
+ for (byte aByte : data) {
+ if (isBase64(aByte)) {
+ groomedData[bytesCopied++] = aByte;
+ }
+ }
+
+ byte packedData[] = new byte[bytesCopied];
+
+ System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+ return packedData;
+ }
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/codec/CodecException.java b/core/src/org/jsecurity/codec/CodecException.java
new file mode 100644
index 0000000..2f46bc5
--- /dev/null
+++ b/core/src/org/jsecurity/codec/CodecException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.codec;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * Root exception related to issues during encoding or decoding.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class CodecException extends JSecurityException {
+
+ /**
+ * Creates a new <code>CodecException</code>.
+ */
+ public CodecException() {
+ super();
+ }
+
+ /**
+ * Creates a new <code>CodecException</code>.
+ *
+ * @param message the reason for the exception.
+ */
+ public CodecException(String message) {
+ super(message);
+ }
+
+ /**
+ * Creates a new <code>CodecException</code>.
+ *
+ * @param cause the underlying cause of the exception.
+ */
+ public CodecException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Creates a new <code>CodecException</code>.
+ *
+ * @param message the reason for the exception.
+ * @param cause the underlying cause of the exception.
+ */
+ public CodecException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/codec/CodecSupport.java b/core/src/org/jsecurity/codec/CodecSupport.java
new file mode 100644
index 0000000..17846bf
--- /dev/null
+++ b/core/src/org/jsecurity/codec/CodecSupport.java
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.codec;
+
+import java.io.UnsupportedEncodingException;
+
+/**
+ * Base abstract class that provides useful encoding and decoding operations, especially for character data.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class CodecSupport {
+
+ /**
+ * JSecurity's default preferred Character encoding, equal to <b><code>UTF-8</code></b>.
+ */
+ public static final String PREFERRED_ENCODING = "UTF-8";
+
+ /**
+ * Converts the specified character array to a byte array using the JSecurity's preferred encoding (UTF-8).
+ * <p/>
+ * This is a convenience method equivalent to calling the {@link #toBytes(String,String)} method with a
+ * a wrapping String and {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}, i.e.
+ * <p/>
+ * <code>toBytes( new String(chars), {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING} );</code>
+ *
+ * @param chars the character array to be converted to a byte array.
+ * @return the byte array of the UTF-8 encoded character array.
+ */
+ public static byte[] toBytes(char[] chars) {
+ return toBytes(new String(chars), PREFERRED_ENCODING);
+ }
+
+ /**
+ * Converts the specified character array into a byte array using the specified character encoding.
+ * <p/>
+ * This is a convenience method equivalent to calling the {@link #toBytes(String,String)} method with a
+ * a wrapping String and the specified encoding, i.e.
+ * <p/>
+ * <code>toBytes( new String(chars), encoding );</code>
+ *
+ * @param chars the character array to be converted to a byte array
+ * @param encoding the character encoding to use to when converting to bytes.
+ * @return the bytes of the specified character array under the specified encoding.
+ * @throws CodecException if the JVM does not support the specified encoding.
+ */
+ public static byte[] toBytes(char[] chars, String encoding) throws CodecException {
+ return toBytes(new String(chars), encoding);
+ }
+
+ /**
+ * Converts the specified source argument to a byte array with JSecurity's
+ * {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.
+ *
+ * @param source the string to convert to a byte array.
+ * @return the bytes representing the specified string under JSecurity's {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.
+ */
+ public static byte[] toBytes(String source) {
+ return toBytes(source, PREFERRED_ENCODING);
+ }
+
+ /**
+ * Converts the specified source to a byte array via the specified encoding, throwing a
+ * {@link CodecException CodecException} if the encoding fails.
+ *
+ * @param source the source string to convert to a byte array.
+ * @param encoding the encoding to use to use.
+ * @return the byte array of the specified source with the given encoding.
+ * @throws CodecException if the JVM does not support the specified encoding.
+ */
+ public static byte[] toBytes(String source, String encoding) throws CodecException {
+ try {
+ return source.getBytes(encoding);
+ } catch (UnsupportedEncodingException e) {
+ String msg = "Unable to convert source [" + source + "] to byte array using " +
+ "encoding '" + encoding + "'";
+ throw new CodecException(msg, e);
+ }
+ }
+
+ /**
+ * Converts the specified byte array to a string using JSecurity's {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.
+ *
+ * @param bytes the byte array to turn into a String.
+ * @return the specified byte array as an encoded String ({@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}).
+ */
+ public static String toString(byte[] bytes) {
+ return toString(bytes, PREFERRED_ENCODING);
+ }
+
+ /**
+ * Converts the specified byte array to a String using the specified character encoding.
+ *
+ * @param bytes the byte array to convert to a String
+ * @param encoding the character encoding used to encode the String.
+ * @return the specified byte array as an encoded String
+ * @throws CodecException if the JVM does not support the specified encoding.
+ */
+ public static String toString(byte[] bytes, String encoding) throws CodecException {
+ try {
+ return new String(bytes, encoding);
+ } catch (UnsupportedEncodingException e) {
+ String msg = "Unable to convert byte array to String with encoding '" + encoding + "'.";
+ throw new CodecException(msg, e);
+ }
+ }
+
+ /**
+ * Returns the specified byte array as a character array using JSecurity's {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.
+ *
+ * @param bytes the byte array to convert to a char array
+ * @return the specified byte array encoded as a character array ({@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}).
+ */
+ public static char[] toChars(byte[] bytes) {
+ return toChars(bytes, PREFERRED_ENCODING);
+ }
+
+ /**
+ * Converts the specified byte array to a character array using the specified character encoding.
+ *
+ * @param bytes the byte array to convert to a String
+ * @param encoding the character encoding used to encode the bytes.
+ * @return the specified byte array as an encoded char array
+ * @throws CodecException if the JVM does not support the specified encoding.
+ */
+ public static char[] toChars(byte[] bytes, String encoding) throws CodecException {
+ return toString(bytes, encoding).toCharArray();
+ }
+
+ /**
+ * Converts the specified Object into a byte array.
+ *
+ * <p>If the argument is a <tt>byte[]</tt>, <tt>char[]</tt>, or <tt>String</tt> it will be converted
+ * automatically and returned.</tt>
+ *
+ * <p>If the argument is anything other than these three types, it is passed to the
+ * {@link #objectToBytes(Object) objectToBytes} method which must be overridden by subclasses.
+ *
+ * @param o the Object to convert into a byte array
+ * @return a byte array representation of the Object argument.
+ */
+ protected byte[] toBytes(Object o) {
+ if (o == null) {
+ String msg = "Argument for byte conversion cannot be null.";
+ throw new IllegalArgumentException(msg);
+ }
+ if (o instanceof byte[]) {
+ return (byte[]) o;
+ } else if (o instanceof char[]) {
+ return toBytes((char[]) o);
+ } else if (o instanceof String) {
+ return toBytes((String) o);
+ } else {
+ return objectToBytes(o);
+ }
+ }
+
+ /**
+ * Converts the specified Object into a String.
+ *
+ * <p>If the argument is a <tt>byte[]</tt>, <tt>char[]</tt>, or <tt>String</tt> it will be converted
+ * automatically and returned.</tt>
+ *
+ * <p>If the argument is anything other than these three types, it is passed to the
+ * {@link #objectToString(Object) objectToString} method which must be overridden by subclasses.
+ *
+ * @param o the Object to convert into a byte array
+ * @return a byte array representation of the Object argument.
+ */
+ protected String toString(Object o) {
+ if (o == null) {
+ String msg = "Argument for String conversion cannot be null.";
+ throw new IllegalArgumentException(msg);
+ }
+ if (o instanceof byte[]) {
+ return toString((byte[]) o);
+ } else if (o instanceof char[]) {
+ return new String((char[]) o);
+ } else if (o instanceof String) {
+ return (String) o;
+ } else {
+ return objectToString(o);
+ }
+ }
+
+ /**
+ * Default implementation throws a CodecException immediately since it can't infer how to convert the Object
+ * to a byte array. This method must be overridden by subclasses if anything other than the three default
+ * types (listed in the {@link #toBytes(Object) toBytes(Object)} JavaDoc) are to be converted to a byte array.
+ *
+ * @param o the Object to convert to a byte array.
+ * @return a byte array representation of the Object argument.
+ */
+ protected byte[] objectToBytes(Object o) {
+ String msg = "The " + getClass().getName() + " implementation only supports conversion to " +
+ "byte[] if the source is of type byte[], char[] or String. The instance provided as a method " +
+ "argument is of type [" + o.getClass().getName() + "]. If you would like to convert " +
+ "this argument type to a byte[], you can 1) convert the argument to a byte[], char[] or String " +
+ "yourself and then use that as the method argument or 2) subclass " + getClass().getName() +
+ " and override the objectToBytes(Object o) method.";
+ throw new CodecException(msg);
+ }
+
+ /**
+ * Default implementation merely returns <code>objectArgument.toString()</code>. Subclasses can override this
+ * method for different mechanisms of converting an object to a String.
+ *
+ * @param o the Object to convert to a byte array.
+ * @return a String representation of the Object argument.
+ */
+ protected String objectToString(Object o) {
+ return o.toString();
+ }
+}
diff --git a/core/src/org/jsecurity/codec/Hex.java b/core/src/org/jsecurity/codec/Hex.java
new file mode 100644
index 0000000..85502fd
--- /dev/null
+++ b/core/src/org/jsecurity/codec/Hex.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.codec;
+
+/**
+ * Hex encoder and decoder.
+ *
+ * <p>This class was borrowed from Apache Commons Codec SVN repository (rev. 560660 ) with modifications
+ * to enable Hex conversion without a full dependency on Commons Codec. We didn't want to reinvent the wheel of
+ * great work they've done, but also didn't want to force every JSecurity user to depend on the commons-codec.jar</p>
+ *
+ * <p>As per the Apache 2.0 license, the original copyright notice and all author and copyright information have
+ * remained in tact.</p>
+ *
+ * @author Apache Software Foundation
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Hex {
+
+ /**
+ * Used to build output as Hex
+ */
+ private static final char[] DIGITS = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
+ };
+
+ /**
+ * Encodes the specifed byte array to a character array and then returns that character array
+ * as a String.
+ *
+ * @param bytes the byte array to Hex-encode.
+ * @return A String representation of the resultant hex-encoded char array.
+ */
+ public static String encodeToString(byte[] bytes) {
+ char[] encodedChars = encode(bytes);
+ return new String(encodedChars);
+ }
+
+ /**
+ * Converts an array of bytes into an array of characters representing the hexidecimal values of each byte in order.
+ * The returned array will be double the length of the passed array, as it takes two characters to represent any
+ * given byte.
+ *
+ * @param data byte[] to convert to Hex characters
+ * @return A char[] containing hexidecimal characters
+ */
+ public static char[] encode(byte[] data) {
+
+ int l = data.length;
+
+ char[] out = new char[l << 1];
+
+ // two characters form the hex value.
+ for (int i = 0, j = 0; i < l; i++) {
+ out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
+ out[j++] = DIGITS[0x0F & data[i]];
+ }
+
+ return out;
+ }
+
+ /**
+ * Converts an array of character bytes representing hexidecimal values into an
+ * array of bytes of those same values. The returned array will be half the
+ * length of the passed array, as it takes two characters to represent any
+ * given byte. An exception is thrown if the passed char array has an odd
+ * number of elements.
+ *
+ * @param array An array of character bytes containing hexidecimal digits
+ * @return A byte array containing binary data decoded from
+ * the supplied byte array (representing characters).
+ * @throws IllegalArgumentException Thrown if an odd number of characters is supplied
+ * to this function
+ * @see #decode(char[])
+ */
+ public static byte[] decode(byte[] array) throws IllegalArgumentException {
+ String s = CodecSupport.toString(array);
+ return decode(s);
+ }
+
+ /**
+ * Converts the specified Hex-encoded String into a raw byte array. This is a
+ * convenience method that merely delegates to {@link #decode(char[])} using the
+ * argument's hex.toCharArray() value.
+ *
+ * @param hex a Hex-encoded String.
+ * @return A byte array containing binary data decoded from the supplied String's char array.
+ */
+ public static byte[] decode(String hex) {
+ return decode(hex.toCharArray());
+ }
+
+ /**
+ * Converts an array of characters representing hexidecimal values into an
+ * array of bytes of those same values. The returned array will be half the
+ * length of the passed array, as it takes two characters to represent any
+ * given byte. An exception is thrown if the passed char array has an odd
+ * number of elements.
+ *
+ * @param data An array of characters containing hexidecimal digits
+ * @return A byte array containing binary data decoded from
+ * the supplied char array.
+ * @throws IllegalArgumentException if an odd number or illegal of characters
+ * is supplied
+ */
+ public static byte[] decode(char[] data) throws IllegalArgumentException {
+
+ int len = data.length;
+
+ if ((len & 0x01) != 0) {
+ throw new IllegalArgumentException("Odd number of characters.");
+ }
+
+ byte[] out = new byte[len >> 1];
+
+ // two characters form the hex value.
+ for (int i = 0, j = 0; j < len; i++) {
+ int f = toDigit(data[j], j) << 4;
+ j++;
+ f = f | toDigit(data[j], j);
+ j++;
+ out[i] = (byte) (f & 0xFF);
+ }
+
+ return out;
+ }
+
+ /**
+ * Converts a hexadecimal character to an integer.
+ *
+ * @param ch A character to convert to an integer digit
+ * @param index The index of the character in the source
+ * @return An integer
+ * @throws IllegalArgumentException if ch is an illegal hex character
+ */
+ protected static int toDigit(char ch, int index) throws IllegalArgumentException {
+ int digit = Character.digit(ch, 16);
+ if (digit == -1) {
+ throw new IllegalArgumentException("Illegal hexadecimal charcter " + ch + " at index " + index);
+ }
+ return digit;
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/crypto/BlowfishCipher.java b/core/src/org/jsecurity/crypto/BlowfishCipher.java
new file mode 100644
index 0000000..38fa956
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/BlowfishCipher.java
@@ -0,0 +1,276 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.CodecSupport;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+
+/**
+ * JSecurity's default symmetric block Cipher using the Blowfish algorithm. As it is a symmetric Cipher, it uses the
+ * same <tt>Key</tt> to both encrypt and decrypt data. If one is not provided via the {@link #setKey setKey} method,
+ * a default one will be used, BUT NOTE:
+ *
+ * <p>Because JSecurity is an open-source project, if anyone knew that you were using JSecurity's default
+ * <code>Key</code>, they could download/view the source, and with enough effort, reconstruct the <code>Key</code>
+ * and decode encrypted data at will.
+ *
+ * <p>JSecurity only really uses Ciphers to encrypt user ids and session ids, so if that information is not critical
+ * to you and you think the default key still makes things 'sufficiently difficult', then you can ignore this issue.
+ *
+ * <p>However, if you do feel this constitutes sensitive information, it is recommended that you provide your own
+ * <tt>Key</tt> via the {@link #setKey setKey} method to a Key known only to your application,
+ * guaranteeing that no third party can decrypt your data. If you want to know how to do this, you can browse this
+ * class's source code for the {@link #generateNewKey()} method to see how we created our default. Then you can
+ * duplicate the same in your environment and set the result on an instance of this class via the
+ * <code>setKey</code> method.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public class BlowfishCipher implements Cipher {
+
+ /**
+ * The JDK Crypto Cipher algorithm to use for this class, equal to "Blowfish".
+ */
+ private static final String ALGORITHM = "Blowfish";
+
+ /**
+ * The JDK Crypto Transformation string to use for this class, equal to {@link #ALGORITHM ALGORITHM} + "/ECB/PKCS5Padding";
+ */
+ private static final String TRANSFORMATION_STRING = ALGORITHM + "/ECB/PKCS5Padding";
+
+ //The following KEY_BYTES String was created by running
+ //System.out.println( Base64.encode( generateNewKey().getEncoded() ) ); and copying-n-pasting the output here.
+ //You should run the same and set the resulting output as a property of this class instead of using
+ //JSecurity's default Key for proper security.
+ private static final byte[] KEY_BYTES = Base64.decode("jJ9Kg1BAevbvhSg3vBfwfQ==");
+ private static final Key DEFAULT_CIPHER_KEY = new SecretKeySpec(KEY_BYTES, ALGORITHM);
+
+ /**
+ * Internal private log instance.
+ */
+ private static final Log log = LogFactory.getLog(BlowfishCipher.class);
+
+ /**
+ * The key to use by default, can be overridden by calling {@link #setKey(java.security.Key)}.
+ */
+ private Key key = DEFAULT_CIPHER_KEY;
+
+ /**
+ * Default no argument constructor that uses an internal default {@link #getKey() key} to use during
+ * encryption and decryption. For propery security, you should definitely supply your own key by using the
+ * {@link #setKey(java.security.Key) setKey(Key)} method.
+ */
+ public BlowfishCipher() {
+ }
+
+ /**
+ * Returns the default {@link Key Key} to use for symmetric encryption and decryption if one is not specified during
+ * encryption/decryption. For truly secure applications,
+ * you should always specify your own key via the {@link #setKey(java.security.Key) setKey} method.
+ * @return the {@link Key Key} to use for symmetric encryption and decryption.
+ * @see #encrypt(byte[], byte[])
+ * @see #decrypt(byte[], byte[])
+ */
+ public Key getKey() {
+ return key;
+ }
+
+ /**
+ * Sets the internal default {@link Key Key} to use for symmetric encryption and decryption if one is not
+ * specified during encryption/decryption. For truly secure applications, you should always specify your own
+ * key via this method.
+ * @param key the key to use for symmetric encryption and decryption.
+ * @see #encrypt(byte[], byte[])
+ * @see #decrypt(byte[], byte[])
+ */
+ public void setKey(Key key) {
+ this.key = key;
+ }
+
+ /**
+ * Encrypts the specified raw byte array. If the <code>key</code> argument is null, the internal default
+ * {@link #getKey() key} will be used to encrypt the byte array.
+ */
+ public byte[] encrypt(byte[] raw, byte[] key) {
+ byte[] encrypted = crypt(raw, javax.crypto.Cipher.ENCRYPT_MODE, key);
+ if (log.isTraceEnabled()) {
+ log.trace("Incoming byte array of size " + (raw != null ? raw.length : 0) + ". Encrypted " +
+ "byte array is size " + (encrypted != null ? encrypted.length : 0));
+ }
+ return encrypted;
+ }
+
+ /**
+ * Decrypts the specified already-encrypted byte array. If the <code>key</code> argument is null, the internal default
+ * {@link #getKey() key} will be used to encrypt the byte array.
+ */
+ public byte[] decrypt(byte[] encrypted, byte[] key) {
+ if (log.isTraceEnabled()) {
+ log.trace("Attempting to decrypt incoming byte array of length " +
+ (encrypted != null ? encrypted.length : 0));
+ }
+ return crypt(encrypted, javax.crypto.Cipher.DECRYPT_MODE, key);
+ }
+
+ /**
+ * Returns a new {@link javax.crypto.Cipher Cipher} instance to use for encryption/decryption operations, based on
+ * the {@link #TRANSFORMATION_STRING TRANSFORMATION_STRING} constant.
+ * @return a new Cipher instance.
+ * @throws IllegalStateException if a new Cipher instance cannot be constructed based on the
+ * {@link #TRANSFORMATION_STRING TRANSFORMATION_STRING} constant.
+ */
+ protected javax.crypto.Cipher newCipherInstance() throws IllegalStateException {
+ try {
+ return javax.crypto.Cipher.getInstance(TRANSFORMATION_STRING);
+ } catch (Exception e) {
+ String msg = "Unable to acquire a Java JCE Cipher instance using " +
+ javax.crypto.Cipher.class.getName() + ".getInstance( \"" + TRANSFORMATION_STRING + "\" ). " +
+ "Blowfish under this configuration is required for the " +
+ getClass().getName() + " instance to function.";
+ throw new IllegalStateException(msg, e);
+ }
+ }
+
+ /**
+ * Initializes the JDK Cipher with the specified mode and key. This is primarily a utility method to catch any
+ * potential {@link InvalidKeyException InvalidKeyException} that might arise.
+ *
+ * @param cipher the JDK Cipher to {@link javax.crypto.Cipher#init(int, java.security.Key) init}.
+ * @param mode the Cipher mode
+ * @param key the Cipher's Key
+ */
+ protected void init(javax.crypto.Cipher cipher, int mode, java.security.Key key) {
+ try {
+ cipher.init(mode, key);
+ } catch (InvalidKeyException e) {
+ String msg = "Unable to init cipher.";
+ throw new IllegalStateException(msg, e);
+ }
+ }
+
+ /**
+ * Calls the {@link javax.crypto.Cipher#doFinal(byte[]) doFinal(bytes)} method, propagating any exception that
+ * might arise in an {@link IllegalStateException IllegalStateException}
+ * @param cipher the JDK Cipher to finalize (perform the actual cryption)
+ * @param bytes the bytes to crypt
+ * @return the resulting crypted byte array.
+ */
+ protected byte[] crypt(javax.crypto.Cipher cipher, byte[] bytes) {
+ try {
+ return cipher.doFinal(bytes);
+ } catch (Exception e) {
+ String msg = "Unable to crypt bytes with cipher [" + cipher + "].";
+ throw new IllegalStateException(msg, e);
+ }
+ }
+
+ /**
+ * Calls the {@link #init(javax.crypto.Cipher, int, java.security.Key)} and then
+ * {@link #crypt(javax.crypto.Cipher, byte[])}. Ensures that the key is never null by using the
+ * {@link #getKey() default key} if the method argument key is <code>null</code>.
+ * @param bytes the bytes to crypt
+ * @param mode the JDK Cipher mode
+ * @param key the key to use to do the cryption. If <code>null</code> the {@link #getKey() default key} will be used.
+ * @return the resulting crypted byte array
+ */
+ protected byte[] crypt(byte[] bytes, int mode, byte[] key) {
+ javax.crypto.Cipher cipher = newCipherInstance();
+
+ java.security.Key jdkKey;
+ if (key == null) {
+ jdkKey = getKey();
+ } else {
+ jdkKey = new SecretKeySpec(key, ALGORITHM);
+ }
+
+ init(cipher, mode, jdkKey);
+ return crypt(cipher, bytes);
+ }
+
+ /**
+ * Generates a new {@link Key Key} suitable for this Cipher by calling
+ * {@link #generateNewKey() generateNewKey(128)} (uses a 128 bit size by default).
+ * @return a new {@link Key Key}, 128 bits in length.
+ */
+ public static Key generateNewKey() {
+ return generateNewKey(128);
+ }
+
+ /**
+ * Generates a new {@link Key Key} of the specified size suitable for this Cipher
+ * (based on the {@link #ALGORITHM ALGORITHM} using the JDK {@link KeyGenerator KeyGenerator}.
+ * @param keyBitSize the bit size of the key to create
+ * @return the created key suitable for use with this Cipher.
+ */
+ public static Key generateNewKey(int keyBitSize) {
+ KeyGenerator kg;
+ try {
+ kg = KeyGenerator.getInstance(ALGORITHM);
+ } catch (NoSuchAlgorithmException e) {
+ String msg = "Unable to acquire " + ALGORITHM + " algorithm. This is required to function.";
+ throw new IllegalStateException(msg, e);
+ }
+ kg.init(keyBitSize);
+ return kg.generateKey();
+ }
+
+ /**
+ * Simple test main method to ensure functionality is correct. Should really be moved to a proper test case.
+ * @param unused ignored
+ * @throws Exception if anything unexpected happens.
+ */
+ public static void main(String[] unused) throws Exception {
+
+ Cipher cipher = new BlowfishCipher();
+
+ String[] cleartext = new String[]{
+ "Hello, this is a test.",
+ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
+ };
+
+ for (String clear : cleartext) {
+ byte[] cleartextBytes = CodecSupport.toBytes(clear);
+ System.out.println("Clear text: [" + clear + "]");
+ System.out.println("Clear text base64: [" + Base64.encodeToString(cleartextBytes) + "]");
+
+ byte[] encrypted = cipher.encrypt(cleartextBytes, null);
+ String encryptedBase64 = Base64.encodeToString(encrypted);
+ System.out.println("Encrypted base64: [" + encryptedBase64 + "]");
+
+ byte[] decrypted = cipher.decrypt(Base64.decode(encryptedBase64), null);
+ String decryptedString = CodecSupport.toString(decrypted);
+
+ System.out.println("Arrays equal? " + Arrays.equals(cleartextBytes, decrypted));
+
+ System.out.println("Decrypted text: [" + decryptedString + "]");
+ System.out.println("Decrypted text base64: [" + Base64.encodeToString(decrypted) + "]");
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/crypto/Cipher.java b/core/src/org/jsecurity/crypto/Cipher.java
new file mode 100644
index 0000000..96af814
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/Cipher.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto;
+
+/**
+ * A <tt>Cipher</tt> is an algorithm used in cryptography that converts an original input source using a <tt>Key</tt> to
+ * an uninterpretable format. The resulting encrypted output is only able to be converted back to original form with
+ * a <tt>Key</tt> as well.
+ *
+ * <p>In what is known as <em>Symmetric</em> <tt>Cipher</tt>s, the <tt>Key</tt> used to encrypt the source is the same
+ * as (or trivially similar to) the <tt>Key</tt> used to decrypt it.
+ *
+ * <p>In <em>Assymetric</em> <tt>Cipher</tt>s, the encryption <tt>Key</tt> is not the same as the decryption <tt>Key</tt>.
+ * The most common type of Assymetric Ciphers are based on what is called public/private key pairs:
+ *
+ * <p>A <em>private</em> key is known only to a single party, and as its name implies, is supposed be kept very private
+ * and secure. A <em>public</em> key that is associated with the private key can be disseminated freely to anyone.
+ * Then data encrypted by the public key can only be decrypted by the private key and vice versa, but neither party
+ * need share their private key with anyone else. By not sharing a private key, you can guarantee no 3rd party can
+ * intercept the key and therefore use it to decrypt a message.
+ *
+ * <p>This assymetric key technology was created as a
+ * more secure alternative to symmetric ciphers that sometimes suffer from man-in-the-middle attacks since, for
+ * data shared between two parties, the same Key must also be shared and may be compromised.
+ *
+ * <p>Note that a symmetric cipher is perfectly fine to use if you just want to encode data in a format no one else
+ * can understand and you never give away the key. JSecurity uses a symmetric cipher when using certain
+ * HTTP Cookies for example - because it is often undesireable to have user's identity stored in a plain-text cookie,
+ * that identity can be converted via a symmetric cipher. Since the the same exact JSecurity application will receive
+ * the cookie, it can decrypt it via the same <tt>Key</tt> and there is no potential for discovery since that Key
+ * is never shared with anyone.
+ *
+ * @author Les Hazlewood
+ * @see BlowfishCipher
+ * @since 0.9
+ */
+public interface Cipher {
+
+ /**
+ * Encrypts data via the specified Cipher key. Note that the key must be in a format understood by
+ * the Cipher implementation.
+ *
+ * @param raw the data to encrypt
+ * @param encryptionKey the Cipher key used during encryption.
+ * @return an encrypted representation of the specified raw data.
+ */
+ byte[] encrypt(byte[] raw, byte[] encryptionKey);
+
+ /**
+ * Decrypts encrypted data via the specified Cipher key and returns the original (pre-encrypted) data.
+ * Note that the key must be in a format understood by the Cipher implementation.
+ *
+ * @param encrypted the previously encrypted data to decrypt
+ * @param decryptionKey the Cipher key used during decryption.
+ * @return the original form of the specified encrypted data.
+ */
+ byte[] decrypt(byte[] encrypted, byte[] decryptionKey);
+
+}
diff --git a/core/src/org/jsecurity/crypto/hash/AbstractHash.java b/core/src/org/jsecurity/crypto/hash/AbstractHash.java
new file mode 100644
index 0000000..7475b70
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/AbstractHash.java
@@ -0,0 +1,280 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.CodecException;
+import org.jsecurity.codec.CodecSupport;
+import org.jsecurity.codec.Hex;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+
+/**
+ * Provides a base for all JSecurity Hash algorithms with support for salts and multiple hash iterations.
+ *
+ * <p>Read <a href="http://www.owasp.org/index.php/Hashing_Java" target="blank">http://www.owasp.org/index.php/Hashing_Java</a> for a
+ * good article on the benefits of hashing, including what a 'salt' is as well as why it and multiple hash iterations
+ * can be useful.
+ *
+ * <p>This class and its subclasses support hashing with additional capabilities of salting and multiple iterations via
+ * overloaded constructors</p>.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AbstractHash extends CodecSupport implements Hash {
+
+ /** The hashed data */
+ private byte[] bytes = null;
+
+ /** Cached value of the {@link #toHex() toHex()} call so multiple calls won't incur repeated overhead. */
+ private String hexEncoded = null;
+ /** Cached value of the {@link #toBase64() toBase64()} call so multiple calls won't incur repeated overhead. */
+ private String base64Encoded = null;
+
+ /**
+ * Creates an new instance without any of its properties set (no hashing is performed).
+ *
+ * <p>Because all constructors in this class
+ * (except this one) hash the <tt>source</tt> constructor argument, this default, no-arg constructor is useful in
+ * scenarios whenyou have a byte array that you know is already hashed and just want to set the bytes in their
+ * raw form directly on an instance. After instantiating the instance with this default, no-arg constructor, you
+ * can then immediately call {@link #setBytes setBytes} to have a fully-initiallized instance.
+ */
+ public AbstractHash() {
+ }
+
+ /**
+ * Creates a hash of the specified <tt>source</tt> with no <tt>salt</tt> using a single hash iteration.
+ *
+ * <p>It is a convenience constructor that merely executes <code>this( source, null, 1);</code>.
+ *
+ * <p>Please see the
+ * {@link #AbstractHash(Object source, Object salt, int numIterations) AbstractHash(Object,Object,int)}
+ * constructor for the types of Objects that may be passed into this constructor, as well as how to support further
+ * types.
+ *
+ * @param source the object to be hashed.
+ * @throws CodecException if the specified <tt>source</tt> cannot be converted into a byte array (byte[]).
+ */
+ public AbstractHash(Object source) throws CodecException {
+ this(source, null, 1);
+ }
+
+ /**
+ * Creates a hash of the specified <tt>source</tt> using the given <tt>salt</tt> using a single hash iteration.
+ *
+ * <p>It is a convenience constructor that merely executes <code>this( source, salt, 1);</code>.
+ *
+ * <p>Please see the
+ * {@link #AbstractHash(Object source, Object salt, int numIterations) AbstractHash(Object,Object,int)}
+ * constructor for the types of Objects that may be passed into this constructor, as well as how to support further
+ * types.
+ *
+ * @param source the source object to be hashed.
+ * @param salt the salt to use for the hash
+ * @throws CodecException if either constructor argument cannot be converted into a byte array.
+ */
+ public AbstractHash(Object source, Object salt) throws CodecException {
+ this(source, salt, 1);
+ }
+
+ /**
+ * Creates a hash of the specified <tt>source</tt> using the given <tt>salt</tt> a total of
+ * <tt>hashIterations</tt> times.
+ *
+ * <p>By default, this class only supports Object method arguments of
+ * type <tt>byte[]</tt>, <tt>char[]</tt> and <tt>String</tt>. If either argument is anything other than these
+ * types a {@link org.jsecurity.codec.CodecException CodecException} will be thrown.
+ *
+ * <p>If you want to be able to hash other object types, or use other salt types, you need to override the
+ * {@link #toBytes(Object) toBytes(Object)} method to support those specific types. Your other option is to
+ * convert your arguments to one of the default three supported types first before passing them in to this
+ * constructor</tt>.
+ *
+ * @param source the source object to be hashed.
+ * @param salt the salt to use for the hash
+ * @param hashIterations the number of times the <tt>source</tt> argument hashed for attack resiliency.
+ * @throws CodecException if either Object constructor argument cannot be converted into a byte array.
+ */
+ public AbstractHash(Object source, Object salt, int hashIterations) throws CodecException {
+ byte[] sourceBytes = toBytes(source);
+ byte[] saltBytes = null;
+ if (salt != null) {
+ saltBytes = toBytes(salt);
+ }
+ byte[] hashedBytes = hash(sourceBytes, saltBytes, hashIterations);
+ setBytes(hashedBytes);
+ }
+
+ /**
+ * Implemented by subclasses, this specifies the name of the {@link MessageDigest MessageDigest} algorithm
+ * to use when performing the hash.
+ *
+ * @return the {@link MessageDigest MessageDigest} algorithm to use when performing the hash.
+ */
+ protected abstract String getAlgorithmName();
+
+ public byte[] getBytes() {
+ return this.bytes;
+ }
+
+ /**
+ * Sets the raw bytes stored by this hash instance.
+ *
+ * <p>The bytes are kept in raw form - they will not be hashed/changed. This is primarily a utility method for
+ * constructing a Hash instance when the hashed value is already known.
+ *
+ * @param alreadyHashedBytes the raw already-hashed bytes to store in this instance.
+ */
+ public void setBytes(byte[] alreadyHashedBytes) {
+ this.bytes = alreadyHashedBytes;
+ this.hexEncoded = null;
+ this.base64Encoded = null;
+ }
+
+ /**
+ * Returns the JDK MessageDigest instance to use for executing the hash.
+ *
+ * @param algorithmName the algorithm to use for the hash, provided by subclasses.
+ * @return the MessageDigest object for the specfied <tt>algorithm</tt>.
+ */
+ protected MessageDigest getDigest(String algorithmName) {
+ try {
+ return MessageDigest.getInstance(algorithmName);
+ } catch (NoSuchAlgorithmException e) {
+ String msg = "No native '" + algorithmName + "' MessageDigest instance available on the current JVM.";
+ throw new IllegalStateException(msg, e);
+ }
+ }
+
+ /**
+ * Hashes the specified byte array without a salt for a single iteration.
+ *
+ * @param bytes the bytes to hash.
+ * @return the hashed bytes.
+ */
+ protected byte[] hash(byte[] bytes) {
+ return hash(bytes, null, 1);
+ }
+
+ /**
+ * Hashes the specified byte array using the given <tt>salt</tt> for a single iteration.
+ *
+ * @param bytes the bytes to hash
+ * @param salt the salt to use for the initial hash
+ * @return the hashed bytes
+ */
+ protected byte[] hash(byte[] bytes, byte[] salt) {
+ return hash(bytes, salt, 1);
+ }
+
+ /**
+ * Hashes the specified byte array using the given <tt>salt</tt> for the specified number of iterations.
+ *
+ * @param bytes the bytes to hash
+ * @param salt the salt to use for the initial hash
+ * @param hashIterations the number of times the the <tt>bytes</tt> will be hashed (for attack resiliency).
+ * @return the hashed bytes.
+ */
+ protected byte[] hash(byte[] bytes, byte[] salt, int hashIterations) {
+ MessageDigest md = getDigest(getAlgorithmName());
+ if (salt != null) {
+ md.reset();
+ md.update(salt);
+ }
+ byte[] hashed = md.digest(bytes);
+ int iterations = hashIterations - 1; //already hashed once above
+ //iterate remaining number:
+ for (int i = 0; i < iterations; i++) {
+ md.reset();
+ hashed = md.digest(hashed);
+ }
+ return hashed;
+ }
+
+ /**
+ * Returns a hex-encoded string of the underlying {@link #getBytes byte array}.
+ *
+ * <p>This implementation caches the resulting hex string so multiple calls to this method remain performant.
+ * However, calling {@link #setBytes setBytes} will null the cached value, forcing it to be recalculated the
+ * next time this method is called.
+ *
+ * @return a hex-encoded string of the underlying {@link #getBytes byte array}.
+ */
+ public String toHex() {
+ if (this.hexEncoded == null) {
+ this.hexEncoded = Hex.encodeToString(getBytes());
+ }
+ return this.hexEncoded;
+ }
+
+ /**
+ * Returns a Base64-encoded string of the underlying {@link #getBytes byte array}.
+ *
+ * <p>This implementation caches the resulting Base64 string so multiple calls to this method remain performant.
+ * However, calling {@link #setBytes setBytes} will null the cached value, forcing it to be recalculated the
+ * next time this method is called.
+ *
+ * @return a Base64-encoded string of the underlying {@link #getBytes byte array}.
+ */
+ public String toBase64() {
+ if (this.base64Encoded == null) {
+ //cache result in case this method is called multiple times.
+ this.base64Encoded = Base64.encodeToString(getBytes());
+ }
+ return this.base64Encoded;
+ }
+
+ /**
+ * Simple implementation that merely returns {@link #toHex() toHex()}.
+ *
+ * @return the {@link #toHex() toHex()} value.
+ */
+ public String toString() {
+ return toHex();
+ }
+
+ /**
+ * Returns <tt>true</tt> if the specified object is a Hash and its {@link #getBytes byte array} is identical to
+ * this Hash's byte array, <tt>false</tt> otherwise.
+ *
+ * @param o the object (Hash) to check for equality.
+ * @return <tt>true</tt> if the specified object is a Hash and its {@link #getBytes byte array} is identical to
+ * this Hash's byte array, <tt>false</tt> otherwise.
+ */
+ public boolean equals(Object o) {
+ if (o instanceof Hash) {
+ Hash other = (Hash) o;
+ return Arrays.equals(getBytes(), other.getBytes());
+ }
+ return false;
+ }
+
+ /**
+ * Simply returns toHex().hashCode();
+ *
+ * @return toHex().hashCode()
+ */
+ public int hashCode() {
+ return toHex().hashCode();
+ }
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Hash.java b/core/src/org/jsecurity/crypto/hash/Hash.java
new file mode 100644
index 0000000..455f040
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Hash.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+/**
+ * A Cryptoraphic <tt>Hash</tt> represents a one-way conversion algorithm that transforms an input source to an underlying
+ * byte array.
+ *
+ * @author Les Hazlewood
+ * @see AbstractHash
+ * @see Md2Hash
+ * @see Md5Hash
+ * @see Sha1Hash
+ * @see Sha256Hash
+ * @see Sha384Hash
+ * @see Sha512Hash
+ * @since 0.9
+ */
+public interface Hash {
+
+ /**
+ * Returns this Hash's byte array, that is, the hashed value of the original input source.
+ *
+ * @return this Hash's byte array, that is, the hashed value of the original input source.
+ * @see #toHex
+ * @see #toBase64
+ */
+ byte[] getBytes();
+
+ /**
+ * Returns a Hex encoding of this Hash's {@link #getBytes byte array}.
+ *
+ * @return a Hex encoding of this Hash's {@link #getBytes byte array}.
+ */
+ String toHex();
+
+ /**
+ * Returns a Base64 encoding of this Hash's {@link #getBytes byte array}.
+ *
+ * @return a Base64 encoding of this Hash's {@link #getBytes byte array}.
+ */
+ String toBase64();
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Md2Hash.java b/core/src/org/jsecurity/crypto/hash/Md2Hash.java
new file mode 100644
index 0000000..4dec59e
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Md2Hash.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+
+/**
+ * Generates an MD2 Hash (RFC 1319) from a given input <tt>source</tt> with an optional <tt>salt</tt> and
+ * hash iterations.
+ *
+ * <p>See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
+ * techniques and how the overloaded constructors function.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Md2Hash extends AbstractHash {
+
+ //TODO - complete JavaDoc
+
+ public static final String ALGORITHM_NAME = "MD2";
+
+ public Md2Hash() {
+ }
+
+ public Md2Hash(Object source) {
+ super(source);
+ }
+
+ public Md2Hash(Object source, Object salt) {
+ super(source, salt);
+ }
+
+ public Md2Hash(Object source, Object salt, int hashIterations) {
+ super(source, salt, hashIterations);
+ }
+
+ protected String getAlgorithmName() {
+ return ALGORITHM_NAME;
+ }
+
+ public static Md2Hash fromHexString(String hex) {
+ Md2Hash hash = new Md2Hash();
+ hash.setBytes(Hex.decode(hex));
+ return hash;
+ }
+
+ public static Md2Hash fromBase64String(String base64) {
+ Md2Hash hash = new Md2Hash();
+ hash.setBytes(Base64.decode(base64));
+ return hash;
+ }
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Md5Hash.java b/core/src/org/jsecurity/crypto/hash/Md5Hash.java
new file mode 100644
index 0000000..c6ecbd5
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Md5Hash.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+
+/**
+ * Generates an MD5 Hash (RFC 1321) from a given input <tt>source</tt> with an optional <tt>salt</tt> and
+ * hash iterations.
+ *
+ * <p>See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
+ * techniques and how the overloaded constructors function.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Md5Hash extends AbstractHash {
+
+ //TODO - complete JavaDoc
+
+ public static final String ALGORITHM_NAME = "MD5";
+
+ public Md5Hash() {
+ }
+
+ public Md5Hash(Object source) {
+ super(source);
+ }
+
+ public Md5Hash(Object source, Object salt) {
+ super(source, salt);
+ }
+
+ public Md5Hash(Object source, Object salt, int hashIterations) {
+ super(source, salt, hashIterations);
+ }
+
+ protected String getAlgorithmName() {
+ return ALGORITHM_NAME;
+ }
+
+ public static Md5Hash fromHexString(String hex) {
+ Md5Hash hash = new Md5Hash();
+ hash.setBytes(Hex.decode(hex));
+ return hash;
+ }
+
+ public static Md5Hash fromBase64String(String base64) {
+ Md5Hash hash = new Md5Hash();
+ hash.setBytes(Base64.decode(base64));
+ return hash;
+ }
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Sha1Hash.java b/core/src/org/jsecurity/crypto/hash/Sha1Hash.java
new file mode 100644
index 0000000..eb9ee7a
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Sha1Hash.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+
+/**
+ * Generates an SHA-1 Hash (Secure Hash Standard, NIST FIPS 180-1) from a given input <tt>source</tt> with an
+ * optional <tt>salt</tt> and hash iterations.
+ *
+ * <p>See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
+ * techniques and how the overloaded constructors function.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha1Hash extends AbstractHash {
+
+ //TODO - complete JavaDoc
+
+ public static final String ALGORITHM_NAME = "SHA-1";
+
+ public Sha1Hash() {
+ }
+
+ public Sha1Hash(Object source) {
+ super(source);
+ }
+
+ public Sha1Hash(Object source, Object salt) {
+ super(source, salt);
+ }
+
+ public Sha1Hash(Object source, Object salt, int hashIterations) {
+ super(source, salt, hashIterations);
+ }
+
+ protected String getAlgorithmName() {
+ return ALGORITHM_NAME;
+ }
+
+ public static Sha1Hash fromHexString(String hex) {
+ Sha1Hash hash = new Sha1Hash();
+ hash.setBytes(Hex.decode(hex));
+ return hash;
+ }
+
+ public static Sha1Hash fromBase64String(String base64) {
+ Sha1Hash hash = new Sha1Hash();
+ hash.setBytes(Base64.decode(base64));
+ return hash;
+ }
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Sha256Hash.java b/core/src/org/jsecurity/crypto/hash/Sha256Hash.java
new file mode 100644
index 0000000..dd46c93
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Sha256Hash.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+
+/**
+ * Generates an SHA-256 Hash from a given input <tt>source</tt> with an optional <tt>salt</tt> and hash iterations.
+ *
+ * <p>See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
+ * techniques and how the overloaded constructors function.
+ *
+ * <p><b>JDK Version Note</b> - Attempting to instantiate this class on JREs prior to version 1.4.0 will throw
+ * an {@link IllegalStateException IllegalStateException}
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha256Hash extends AbstractHash {
+
+ //TODO - complete JavaDoc
+
+ public static final String ALGORITHM_NAME = "SHA-256";
+
+ public Sha256Hash() {
+ }
+
+ public Sha256Hash(Object source) {
+ super(source);
+ }
+
+ public Sha256Hash(Object source, Object salt) {
+ super(source, salt);
+ }
+
+ public Sha256Hash(Object source, Object salt, int hashIterations) {
+ super(source, salt, hashIterations);
+ }
+
+ protected String getAlgorithmName() {
+ return ALGORITHM_NAME;
+ }
+
+ public static Sha256Hash fromHexString(String hex) {
+ Sha256Hash hash = new Sha256Hash();
+ hash.setBytes(Hex.decode(hex));
+ return hash;
+ }
+
+ public static Sha256Hash fromBase64String(String base64) {
+ Sha256Hash hash = new Sha256Hash();
+ hash.setBytes(Base64.decode(base64));
+ return hash;
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Sha384Hash.java b/core/src/org/jsecurity/crypto/hash/Sha384Hash.java
new file mode 100644
index 0000000..3e681b7
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Sha384Hash.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+
+/**
+ * Generates an SHA-384 Hash from a given input <tt>source</tt> with an optional <tt>salt</tt> and hash iterations.
+ *
+ * <p>See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
+ * techniques and how the overloaded constructors function.
+ *
+ * <p><b>JDK Version Note</b> - Attempting to instantiate this class on JREs prior to version 1.4.0 will throw
+ * an {@link IllegalStateException IllegalStateException}
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha384Hash extends AbstractHash {
+
+ //TODO - complete JavaDoc
+
+ public static final String ALGORITHM_NAME = "SHA-384";
+
+ public Sha384Hash() {
+ }
+
+ public Sha384Hash(Object source) {
+ super(source);
+ }
+
+ public Sha384Hash(Object source, Object salt) {
+ super(source, salt);
+ }
+
+ public Sha384Hash(Object source, Object salt, int hashIterations) {
+ super(source, salt, hashIterations);
+ }
+
+ protected String getAlgorithmName() {
+ return ALGORITHM_NAME;
+ }
+
+ public static Sha384Hash fromHexString(String hex) {
+ Sha384Hash hash = new Sha384Hash();
+ hash.setBytes(Hex.decode(hex));
+ return hash;
+ }
+
+ public static Sha384Hash fromBase64String(String base64) {
+ Sha384Hash hash = new Sha384Hash();
+ hash.setBytes(Base64.decode(base64));
+ return hash;
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/crypto/hash/Sha512Hash.java b/core/src/org/jsecurity/crypto/hash/Sha512Hash.java
new file mode 100644
index 0000000..98ca46d
--- /dev/null
+++ b/core/src/org/jsecurity/crypto/hash/Sha512Hash.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.crypto.hash;
+
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+
+/**
+ * Generates an SHA-512 Hash from a given input <tt>source</tt> with an optional <tt>salt</tt> and hash iterations.
+ *
+ * <p>See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
+ * techniques and how the overloaded constructors function.
+ *
+ * <p><b>JDK Version Note</b> - Attempting to instantiate this class on JREs prior to version 1.4.0 will throw
+ * an {@link IllegalStateException IllegalStateException}
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class Sha512Hash extends AbstractHash {
+
+ //TODO - complete JavaDoc
+
+ public static final String ALGORITHM_NAME = "SHA-512";
+
+ public Sha512Hash() {
+ }
+
+ public Sha512Hash(Object source) {
+ super(source);
+ }
+
+ public Sha512Hash(Object source, Object salt) {
+ super(source, salt);
+ }
+
+ public Sha512Hash(Object source, Object salt, int hashIterations) {
+ super(source, salt, hashIterations);
+ }
+
+ protected String getAlgorithmName() {
+ return ALGORITHM_NAME;
+ }
+
+ public static Sha512Hash fromHexString(String hex) {
+ Sha512Hash hash = new Sha512Hash();
+ hash.setBytes(Hex.decode(hex));
+ return hash;
+ }
+
+ public static Sha512Hash fromBase64String(String base64) {
+ Sha512Hash hash = new Sha512Hash();
+ hash.setBytes(Base64.decode(base64));
+ return hash;
+ }
+
+
+}
+
diff --git a/core/src/org/jsecurity/jndi/JndiCallback.java b/core/src/org/jsecurity/jndi/JndiCallback.java
new file mode 100644
index 0000000..83fe52f
--- /dev/null
+++ b/core/src/org/jsecurity/jndi/JndiCallback.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.jndi;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+
+/**
+ * Callback interface to be implemented by classes that need to perform an
+ * operation (such as a lookup) in a JNDI context. This callback approach
+ * is valuable in simplifying error handling, which is performed by the
+ * JndiTemplate class. This is a similar to JdbcTemplate's approach.
+ *
+ * <p>Note that there is hardly any need to implement this callback
+ * interface, as JndiTemplate provides all usual JNDI operations via
+ * convenience methods.
+ *
+ * <p>Note that this interface is an exact copy of the Spring Framework's identically named interface from
+ * their 2.5.4 distribution - we didn't want to re-invent the wheel, but not require a full dependency on the
+ * Spring framework, nor does Spring make available only its JNDI classes in a small jar, or we would have used that.
+ * Since JSecurity is also Apache 2.0 licensed, all regular licenses and conditions and authors have remained in tact.
+ *
+ * @author Rod Johnson
+ * @see JndiTemplate
+ * @see org.springframework.jdbc.core.JdbcTemplate
+ */
+public interface JndiCallback {
+
+ /**
+ * Do something with the given JNDI context.
+ * Implementations don't need to worry about error handling
+ * or cleanup, as the JndiTemplate class will handle this.
+ *
+ * @param ctx the current JNDI context
+ * @return a result object, or <code>null</code>
+ * @throws NamingException if thrown by JNDI methods
+ */
+ Object doInContext(Context ctx) throws NamingException;
+
+}
diff --git a/core/src/org/jsecurity/jndi/JndiLocator.java b/core/src/org/jsecurity/jndi/JndiLocator.java
new file mode 100644
index 0000000..c0d16bd
--- /dev/null
+++ b/core/src/org/jsecurity/jndi/JndiLocator.java
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.jndi;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.naming.NamingException;
+import java.util.Properties;
+
+/**
+ * Convenient superclass for JNDI accessors, providing "jndiTemplate"
+ * and "jndiEnvironment" bean properties.
+ *
+ * <p>Note that this implementation is an almost exact combined copy of the Spring Framework's 'JndiAccessor' and
+ * 'JndiLocatorSupport' classes from their 2.5.4 distribution - we didn't want to re-invent the wheel, but not require
+ * a full dependency on the Spring framework, nor does Spring make available only its JNDI classes in a small jar, or
+ * we would have used that. Since JSecurity is also Apache 2.0 licensed, all regular licenses and conditions and
+ * authors have remained in tact.
+ *
+ * @author Juergen Hoeller
+ * @see #setJndiTemplate
+ * @see #setJndiEnvironment
+ * @see #setResourceRef
+ * @since 1.1
+ */
+public class JndiLocator {
+
+ /**
+ * Private class log.
+ */
+ private static final Log log = LogFactory.getLog(JndiLocator.class);
+
+ /**
+ * JNDI prefix used in a J2EE container
+ */
+ public static final String CONTAINER_PREFIX = "java:comp/env/";
+
+ private boolean resourceRef = false;
+
+ private JndiTemplate jndiTemplate = new JndiTemplate();
+
+
+ /**
+ * Set the JNDI template to use for JNDI lookups.
+ * <p>You can also specify JNDI environment settings via "jndiEnvironment".
+ *
+ * @see #setJndiEnvironment
+ */
+ public void setJndiTemplate(JndiTemplate jndiTemplate) {
+ this.jndiTemplate = (jndiTemplate != null ? jndiTemplate : new JndiTemplate());
+ }
+
+ /**
+ * Return the JNDI template to use for JNDI lookups.
+ */
+ public JndiTemplate getJndiTemplate() {
+ return this.jndiTemplate;
+ }
+
+ /**
+ * Set the JNDI environment to use for JNDI lookups.
+ * <p>Creates a JndiTemplate with the given environment settings.
+ *
+ * @see #setJndiTemplate
+ */
+ public void setJndiEnvironment(Properties jndiEnvironment) {
+ this.jndiTemplate = new JndiTemplate(jndiEnvironment);
+ }
+
+ /**
+ * Return the JNDI environment to use for JNDI lookups.
+ */
+ public Properties getJndiEnvironment() {
+ return this.jndiTemplate.getEnvironment();
+ }
+
+ /**
+ * Set whether the lookup occurs in a J2EE container, i.e. if the prefix
+ * "java:comp/env/" needs to be added if the JNDI name doesn't already
+ * contain it. Default is "false".
+ * <p>Note: Will only get applied if no other scheme (e.g. "java:") is given.
+ */
+ public void setResourceRef(boolean resourceRef) {
+ this.resourceRef = resourceRef;
+ }
+
+ /**
+ * Return whether the lookup occurs in a J2EE container.
+ */
+ public boolean isResourceRef() {
+ return this.resourceRef;
+ }
+
+
+ /**
+ * Perform an actual JNDI lookup for the given name via the JndiTemplate.
+ * <p>If the name doesn't begin with "java:comp/env/", this prefix is added
+ * if "resourceRef" is set to "true".
+ *
+ * @param jndiName the JNDI name to look up
+ * @return the obtained object
+ * @throws javax.naming.NamingException if the JNDI lookup failed
+ * @see #setResourceRef
+ */
+ protected Object lookup(String jndiName) throws NamingException {
+ return lookup(jndiName, null);
+ }
+
+ /**
+ * Perform an actual JNDI lookup for the given name via the JndiTemplate.
+ * <p>If the name doesn't begin with "java:comp/env/", this prefix is added
+ * if "resourceRef" is set to "true".
+ *
+ * @param jndiName the JNDI name to look up
+ * @param requiredType the required type of the object
+ * @return the obtained object
+ * @throws NamingException if the JNDI lookup failed
+ * @see #setResourceRef
+ */
+ protected Object lookup(String jndiName, Class requiredType) throws NamingException {
+ if (jndiName == null) {
+ throw new IllegalArgumentException("jndiName argument must not be null");
+ }
+ String convertedName = convertJndiName(jndiName);
+ Object jndiObject;
+ try {
+ jndiObject = getJndiTemplate().lookup(convertedName, requiredType);
+ }
+ catch (NamingException ex) {
+ if (!convertedName.equals(jndiName)) {
+ // Try fallback to originally specified name...
+ if (log.isDebugEnabled()) {
+ log.debug("Converted JNDI name [" + convertedName +
+ "] not found - trying original name [" + jndiName + "]. " + ex);
+ }
+ jndiObject = getJndiTemplate().lookup(jndiName, requiredType);
+ } else {
+ throw ex;
+ }
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("Located object with JNDI name [" + convertedName + "]");
+ }
+ return jndiObject;
+ }
+
+ /**
+ * Convert the given JNDI name into the actual JNDI name to use.
+ * <p>The default implementation applies the "java:comp/env/" prefix if
+ * "resourceRef" is "true" and no other scheme (e.g. "java:") is given.
+ *
+ * @param jndiName the original JNDI name
+ * @return the JNDI name to use
+ * @see #CONTAINER_PREFIX
+ * @see #setResourceRef
+ */
+ protected String convertJndiName(String jndiName) {
+ // Prepend container prefix if not already specified and no other scheme given.
+ if (isResourceRef() && !jndiName.startsWith(CONTAINER_PREFIX) && jndiName.indexOf(':') == -1) {
+ jndiName = CONTAINER_PREFIX + jndiName;
+ }
+ return jndiName;
+ }
+
+}
diff --git a/core/src/org/jsecurity/jndi/JndiTemplate.java b/core/src/org/jsecurity/jndi/JndiTemplate.java
new file mode 100644
index 0000000..5a4610a
--- /dev/null
+++ b/core/src/org/jsecurity/jndi/JndiTemplate.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.jndi;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NameNotFoundException;
+import javax.naming.NamingException;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Properties;
+
+/**
+ * Helper class that simplifies JNDI operations. It provides methods to lookup and
+ * bind objects, and allows implementations of the {@link JndiCallback} interface
+ * to perform any operation they like with a JNDI naming context provided.
+ *
+ * <p>Note that this implementation is an almost exact copy of the Spring Framework's identically named class from
+ * their 2.5.4 distribution - we didn't want to re-invent the wheel, but not require a full dependency on the
+ * Spring framework, nor does Spring make available only its JNDI classes in a small jar, or we would have used that.
+ * Since JSecurity is also Apache 2.0 licensed, all regular licenses and conditions and authors have remained in tact.
+ *
+ * @author Rod Johnson
+ * @author Juergen Hoeller
+ * @see JndiCallback
+ * @see #execute
+ */
+public class JndiTemplate {
+
+ private static final Log log = LogFactory.getLog(JndiTemplate.class);
+
+ private Properties environment;
+
+ /**
+ * Create a new JndiTemplate instance.
+ */
+ public JndiTemplate() {
+ }
+
+ /**
+ * Create a new JndiTemplate instance, using the given environment.
+ *
+ * @param environment the Properties to initialize with
+ */
+ public JndiTemplate(Properties environment) {
+ this.environment = environment;
+ }
+
+ /**
+ * Set the environment for the JNDI InitialContext.
+ *
+ * @param environment the Properties to initialize with
+ */
+ public void setEnvironment(Properties environment) {
+ this.environment = environment;
+ }
+
+ /**
+ * Return the environment for the JNDI InitialContext, or <code>null</code> if none should be used.
+ *
+ * @return the environment for the JNDI InitialContext, or <code>null</code> if none should be used.
+ */
+ public Properties getEnvironment() {
+ return this.environment;
+ }
+
+ /**
+ * Execute the given JNDI context callback implementation.
+ *
+ * @param contextCallback JndiCallback implementation
+ * @return a result object returned by the callback, or <code>null</code>
+ * @throws NamingException thrown by the callback implementation
+ * @see #createInitialContext
+ */
+ public Object execute(JndiCallback contextCallback) throws NamingException {
+ Context ctx = createInitialContext();
+ try {
+ return contextCallback.doInContext(ctx);
+ }
+ finally {
+ try {
+ ctx.close();
+ }
+ catch (NamingException ex) {
+ log.debug("Could not close JNDI InitialContext", ex);
+ }
+ }
+ }
+
+ /**
+ * Create a new JNDI initial context. Invoked by {@link #execute}.
+ * <p>The default implementation use this template's environment settings.
+ * Can be subclassed for custom contexts, e.g. for testing.
+ *
+ * @return the initial Context instance
+ * @throws NamingException in case of initialization errors
+ */
+ @SuppressWarnings({"unchecked"})
+ protected Context createInitialContext() throws NamingException {
+ Properties env = getEnvironment();
+ Hashtable icEnv = null;
+ if (env != null) {
+ icEnv = new Hashtable(env.size());
+ for (Enumeration en = env.propertyNames(); en.hasMoreElements();) {
+ String key = (String) en.nextElement();
+ icEnv.put(key, env.getProperty(key));
+ }
+ }
+ return new InitialContext(icEnv);
+ }
+
+ /**
+ * Look up the object with the given name in the current JNDI context.
+ *
+ * @param name the JNDI name of the object
+ * @return object found (cannot be <code>null</code>; if a not so well-behaved
+ * JNDI implementations returns null, a NamingException gets thrown)
+ * @throws NamingException if there is no object with the given
+ * name bound to JNDI
+ */
+ public Object lookup(final String name) throws NamingException {
+ if (log.isDebugEnabled()) {
+ log.debug("Looking up JNDI object with name [" + name + "]");
+ }
+ return execute(new JndiCallback() {
+ public Object doInContext(Context ctx) throws NamingException {
+ Object located = ctx.lookup(name);
+ if (located == null) {
+ throw new NameNotFoundException(
+ "JNDI object with [" + name + "] not found: JNDI implementation returned null");
+ }
+ return located;
+ }
+ });
+ }
+
+ /**
+ * Look up the object with the given name in the current JNDI context.
+ *
+ * @param name the JNDI name of the object
+ * @param requiredType type the JNDI object must match. Can be an interface or
+ * superclass of the actual class, or <code>null</code> for any match. For example,
+ * if the value is <code>Object.class</code>, this method will succeed whatever
+ * the class of the returned instance.
+ * @return object found (cannot be <code>null</code>; if a not so well-behaved
+ * JNDI implementations returns null, a NamingException gets thrown)
+ * @throws NamingException if there is no object with the given
+ * name bound to JNDI
+ */
+ public Object lookup(String name, Class requiredType) throws NamingException {
+ Object jndiObject = lookup(name);
+ if (requiredType != null && !requiredType.isInstance(jndiObject)) {
+ String msg = "Jndi object acquired under name '" + name + "' is of type [" +
+ jndiObject.getClass().getName() + "] and not assignable to the required type [" +
+ requiredType.getName() + "].";
+ throw new NamingException(msg);
+ }
+ return jndiObject;
+ }
+
+ /**
+ * Bind the given object to the current JNDI context, using the given name.
+ *
+ * @param name the JNDI name of the object
+ * @param object the object to bind
+ * @throws NamingException thrown by JNDI, mostly name already bound
+ */
+ public void bind(final String name, final Object object) throws NamingException {
+ if (log.isDebugEnabled()) {
+ log.debug("Binding JNDI object with name [" + name + "]");
+ }
+ execute(new JndiCallback() {
+ public Object doInContext(Context ctx) throws NamingException {
+ ctx.bind(name, object);
+ return null;
+ }
+ });
+ }
+
+ /**
+ * Rebind the given object to the current JNDI context, using the given name.
+ * Overwrites any existing binding.
+ *
+ * @param name the JNDI name of the object
+ * @param object the object to rebind
+ * @throws NamingException thrown by JNDI
+ */
+ public void rebind(final String name, final Object object) throws NamingException {
+ if (log.isDebugEnabled()) {
+ log.debug("Rebinding JNDI object with name [" + name + "]");
+ }
+ execute(new JndiCallback() {
+ public Object doInContext(Context ctx) throws NamingException {
+ ctx.rebind(name, object);
+ return null;
+ }
+ });
+ }
+
+ /**
+ * Remove the binding for the given name from the current JNDI context.
+ *
+ * @param name the JNDI name of the object
+ * @throws NamingException thrown by JNDI, mostly name not found
+ */
+ public void unbind(final String name) throws NamingException {
+ if (log.isDebugEnabled()) {
+ log.debug("Unbinding JNDI object with name [" + name + "]");
+ }
+ execute(new JndiCallback() {
+ public Object doInContext(Context ctx) throws NamingException {
+ ctx.unbind(name);
+ return null;
+ }
+ });
+ }
+
+}
diff --git a/core/src/org/jsecurity/mgt/AuthenticatingSecurityManager.java b/core/src/org/jsecurity/mgt/AuthenticatingSecurityManager.java
new file mode 100644
index 0000000..a7c6aef
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/AuthenticatingSecurityManager.java
@@ -0,0 +1,211 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.jsecurity.authc.*;
+import org.jsecurity.authc.pam.ModularAuthenticationStrategy;
+import org.jsecurity.authc.pam.ModularRealmAuthenticator;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.util.LifecycleUtils;
+
+import java.util.Collection;
+
+/**
+ * JSecurity support of a {@link SecurityManager} class hierarchy that delegates all
+ * authentication operations to a wrapped {@link Authenticator Authenticator} instance. That is, this class
+ * implements all the <tt>Authenticator</tt> methods in the {@link SecurityManager SecurityManager}
+ * interface, but in reality, those methods are merely passthrough calls to the underlying 'real'
+ * <tt>Authenticator</tt> instance.
+ *
+ * <p>All other <tt>SecurityManager</tt> (authorization, session, etc) methods are left to be implemented by subclasses.
+ *
+ * <p>In keeping with the other classes in this hierarchy and JSecurity's desire to minimize configuration whenever
+ * possible, suitable default instances for all dependencies are created upon instantiation.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AuthenticatingSecurityManager extends RealmSecurityManager
+ implements AuthenticationListenerRegistrar {
+
+ /**
+ * The internal <code>Authenticator</code> delegate instance that this SecurityManager instance will use
+ * to perform all authentication operations.
+ */
+ private Authenticator authenticator;
+
+ /**
+ * Default no-arg constructor that initializes its internal
+ * <code>authenticator</code> instance to be a {@link ModularRealmAuthenticator ModularRealmAuthenticator}.
+ */
+ public AuthenticatingSecurityManager() {
+ this.authenticator = new ModularRealmAuthenticator();
+ }
+
+ /**
+ * Returns the delegate <code>Authenticator</code> instance that this SecurityManager uses to perform all
+ * authentication operations. Unless overridden by the
+ * {@link #setAuthenticator(org.jsecurity.authc.Authenticator) setAuthenticator}, the default instance is a
+ * {@link org.jsecurity.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator}.
+ * @return the delegate <code>Authenticator</code> instance that this SecurityManager uses to perform all
+ * authentication operations.
+ */
+ public Authenticator getAuthenticator() {
+ return authenticator;
+ }
+
+ /**
+ * Sets the delegate <code>Authenticator</code> instance that this SecurityManager uses to perform all
+ * authentication operations. Unless overridden by this method, the default instance is a
+ * {@link org.jsecurity.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator}.
+ * @param authenticator the delegate <code>Authenticator</code> instance that this SecurityManager will use to
+ * perform all authentication operations.
+ * @throws IllegalArgumentException if the argument is <code>null</code>.
+ */
+ public void setAuthenticator(Authenticator authenticator) throws IllegalArgumentException {
+ if (authenticator == null) {
+ String msg = "Authenticator argument cannot be null.";
+ throw new IllegalArgumentException(msg);
+ }
+ this.authenticator = authenticator;
+ }
+
+ /**
+ * Sets the {@link org.jsecurity.authc.pam.ModularAuthenticationStrategy ModularAuthenticationStrategy} to use
+ * in multi-realm environments.
+ *
+ * @param strategy the <code>ModularAuthenticationStrategy</code> to use in multi-realm environments.
+ */
+ public void setModularAuthenticationStrategy(ModularAuthenticationStrategy strategy) {
+ if (!(this.authenticator instanceof ModularRealmAuthenticator)) {
+ String msg = "Configuring a ModularAuthenticationStrategy is only applicable when the underlying " +
+ "Authenticator implementation is a " + ModularRealmAuthenticator.class.getName() +
+ " implementation. This SecurityManager has been configured with an Authenticator of type " +
+ this.authenticator.getClass().getName();
+ throw new IllegalStateException(msg);
+ }
+ ((ModularRealmAuthenticator) this.authenticator).setModularAuthenticationStrategy(strategy);
+ }
+
+ /**
+ * This is a convenience method that allows registration of AuthenticationListeners with the underlying
+ * delegate Authenticator instance.
+ *
+ * <p>This is more convenient than having to configure your own Authenticator instance, inject the listeners on
+ * it, and then set that Authenticator instance as an attribute of this class. Instead, you can just rely
+ * on the <tt>SecurityManager</tt>'s default initialization logic to create the Authenticator instance for you
+ * and then apply these <tt>AuthenticationListener</tt>s on your behalf.
+ *
+ * <p>One notice however: The underlying Authenticator delegate must implement the
+ * {@link org.jsecurity.authc.AuthenticationListenerRegistrar AuthenticationListenerRegistrar}
+ * interface in order for these listeners to be applied. If it does not implement this interface, it is
+ * considered a configuration error and an exception will be thrown.
+ *
+ * <p>All of JSecurity's <tt>Authenticator</tt> implementations implement the
+ * <tt>AuthenticationListenerRegistrar</tt> interface, so you would only need
+ * to worry about an exception being thrown if you provided your own Authenticator instance and did not
+ * implement it.
+ *
+ * @param listeners the <tt>AuthenticationListener</tt>s to register with the underlying delegate
+ * <tt>Authenticator</tt>.
+ */
+ public void setAuthenticationListeners(Collection<AuthenticationListener> listeners) {
+ assertAuthenticatorListenerSupport();
+ if (!(this.authenticator instanceof AuthenticationListenerRegistrar)) {
+ String msg = "Configuring a ModularAuthenticationStrategy is only applicable when the underlying " +
+ "Authenticator implementation is a " + AuthenticationListenerRegistrar.class.getName() +
+ " implementation. This SecurityManager has been configured with an Authenticator of type " +
+ this.authenticator.getClass().getName() + ", which does not implement that interface.";
+ throw new IllegalStateException(msg);
+ }
+ ((AuthenticationListenerRegistrar) this.authenticator).setAuthenticationListeners(listeners);
+ }
+
+ /**
+ * Ensures that <code>this.authenticator</code> implements the
+ * {@link org.jsecurity.authc.AuthenticationListenerRegistrar AuthenticationListenerRegistrar} interface to ensure
+ * listeners can be registered.
+ */
+ private void assertAuthenticatorListenerSupport() {
+ if (!(this.authenticator instanceof AuthenticationListenerRegistrar)) {
+ String msg = "AuthenticationListener registration failed: The underlying Authenticator instance of " +
+ "type [" + this.authenticator.getClass().getName() + "] does not implement the " +
+ AuthenticationListenerRegistrar.class.getName() + " interface and therefore cannot support " +
+ "runtime registration of AuthenticationListeners.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ public void add(AuthenticationListener listener) {
+ assertAuthenticatorListenerSupport();
+ Authenticator authc = getAuthenticator();
+ ((AuthenticationListenerRegistrar) authc).add(listener);
+ }
+
+ public boolean remove(AuthenticationListener listener) {
+ Authenticator authc = getAuthenticator();
+ return (authc instanceof AuthenticationListenerRegistrar) &&
+ ((AuthenticationListenerRegistrar) authc).remove(listener);
+ }
+
+ /**
+ * Immediately calls {@link RealmSecurityManager#setRealms(java.util.Collection) super.setRealms} and then
+ * additionally passes on those realms to the internal delegate <code>Authenticator</code> instance so
+ * that it may use them during authentication attempts.
+ * @param realms realms the realms managed by this <tt>SecurityManager</tt> instance and subsequently the internal
+ * delegate <code>Authenticator</code> instance.
+ */
+ public void setRealms(Collection<Realm> realms) {
+ super.setRealms(realms);
+ if (this.authenticator instanceof ModularRealmAuthenticator) {
+ ((ModularRealmAuthenticator) this.authenticator).setRealms(realms);
+ }
+ }
+
+ /**
+ * Lifecycle cleanup method that first calls {@link #beforeAuthenticatorDestroyed() beforeAuthenticatorDestroyed()}
+ * to allow subclass cleanup and then calls {@link #destroyAuthenticator() destroyAuthenticator()} to actually
+ * clean up the internal delegate instance.
+ */
+ protected void beforeRealmsDestroyed() {
+ beforeAuthenticatorDestroyed();
+ destroyAuthenticator();
+ }
+
+ /**
+ * Template hook to allow subclass cleanup when the SecurityManager is being shut down.
+ */
+ protected void beforeAuthenticatorDestroyed() {
+ }
+
+ /**
+ * Cleans up ('destroys') the internal delegate <code>Authenticator</code> instance. Called during shut down.
+ */
+ protected void destroyAuthenticator() {
+ LifecycleUtils.destroy(getAuthenticator());
+ }
+
+ /**
+ * Delegates to the wrapped {@link Authenticator Authenticator} for authentication.
+ */
+ public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
+ ensureRealms();
+ return this.authenticator.authenticate(token);
+ }
+}
diff --git a/core/src/org/jsecurity/mgt/AuthorizingSecurityManager.java b/core/src/org/jsecurity/mgt/AuthorizingSecurityManager.java
new file mode 100644
index 0000000..dc5eae8
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/AuthorizingSecurityManager.java
@@ -0,0 +1,262 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.Authorizer;
+import org.jsecurity.authz.ModularRealmAuthorizer;
+import org.jsecurity.authz.Permission;
+import org.jsecurity.authz.permission.PermissionResolver;
+import org.jsecurity.authz.permission.PermissionResolverAware;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.subject.PrincipalCollection;
+import org.jsecurity.util.LifecycleUtils;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * JSecurity support of a {@link SecurityManager} class hierarchy that delegates all
+ * authorization (access control) operations to a wrapped {@link Authorizer Authorizer} instance. That is,
+ * this class implements all the <tt>Authorizer</tt> methods in the {@link SecurityManager SecurityManager}
+ * interface, but in reality, those methods are merely passthrough calls to the underlying 'real'
+ * <tt>Authorizer</tt> instance.
+ *
+ * <p>All remaining <tt>SecurityManager</tt> methods not covered by this class or its parents (mostly Session support)
+ * are left to be implemented by subclasses.
+ *
+ * <p>In keeping with the other classes in this hierarchy and JSecurity's desire to minimize configuration whenever
+ * possible, suitable default instances for all dependencies will be created upon instantiation.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AuthorizingSecurityManager extends AuthenticatingSecurityManager implements PermissionResolverAware {
+
+ /**
+ * The wrapped instance to which all of this <tt>SecurityManager</tt> authorization calls are delegated.
+ */
+ protected Authorizer authorizer;
+
+ /**
+ * Default no-arg constructor.
+ */
+ public AuthorizingSecurityManager() {
+ ensureAuthorizer();
+ }
+
+ /**
+ * Returns the underlying wrapped <tt>Authorizer</tt> instance to which this <tt>SecurityManager</tt>
+ * implementation delegates all of its authorization calls.
+ *
+ * @return the wrapped <tt>Authorizer</tt> used by this <tt>SecurityManager</tt> implementation.
+ */
+ public Authorizer getAuthorizer() {
+ return authorizer;
+ }
+
+ /**
+ * Sets the underlying <tt>Authorizer</tt> instance to which this <tt>SecurityManager</tt> implementation will
+ * delegate all of its authorization calls.
+ *
+ * @param authorizer the <tt>Authorizer</tt> this <tt>SecurityManager</tt> should wrap and delegate all of its
+ * authorization calls to.
+ */
+ public void setAuthorizer(Authorizer authorizer) {
+ if (authorizer == null) {
+ String msg = "Authorizer argument cannot be null.";
+ throw new IllegalArgumentException(msg);
+ }
+ this.authorizer = authorizer;
+ }
+
+ /**
+ * Ensures that this instance's {@link Authorizer Authorizer} has been
+ * set, and if not, lazily creates one via the {@link #createAuthorizer() createAuthorizer()} method and then
+ * immediately sets it via the {@link #setAuthorizer(org.jsecurity.authz.Authorizer) setAuthorizer} method.
+ */
+ protected void ensureAuthorizer() {
+ Authorizer authorizer = getAuthorizer();
+ if (authorizer == null) {
+ authorizer = createAuthorizer();
+ setAuthorizer(authorizer);
+ }
+ }
+
+ /**
+ * Creates a new {@link Authorizer Authorizer} instance to be used by this <code>AuthorizingSecurityManager</code> instance.
+ * <p/>
+ * This default implementation merely returns
+ * <code>new {@link org.jsecurity.authz.ModularRealmAuthorizer ModularRealmAuthorizer}()</code>
+ * @return a new {@link Authorizer Authorizer} instance to be used by this <code>AuthorizingSecurityManager</code> instance.
+ */
+ protected Authorizer createAuthorizer() {
+ return new ModularRealmAuthorizer();
+ }
+
+ /**
+ * Sets the <tt>PermissionResolver</tt> instance that will be passed on to the underlying default wrapped
+ * {@link Authorizer Authorizer}.
+ *
+ * <p>This is a convenience method: it allows you to configure an application-wide
+ * <tt>PermissionResolver</tt> on the <tt>SecurityManager</tt> instance, and it will trickle its way down to the
+ * 'real' authorizer and/or underlying Realms. This is easier to configure at the <tt>SecurityManager</tt> level
+ * than constructing your own object graph just to configure a <tt>PermissionResolver</tt> instance on objects
+ * deep in the graph.
+ *
+ * @param permissionResolver the <tt>PermissionResolver</tt> instance to set on the wrapped <tt>Authorizer</tt>
+ * @throws IllegalStateException if the underlying <code>Authorizer</code> does not implement the
+ * {@link PermissionResolverAware PermissionResolverAware} interface, which ensures that the resolver can be registered.
+ */
+ public void setPermissionResolver(PermissionResolver permissionResolver) {
+ Authorizer authz = getAuthorizer();
+ if (authz instanceof PermissionResolverAware) {
+ ((PermissionResolverAware) authz).setPermissionResolver(permissionResolver);
+ } else {
+ String msg = "Underlying Authorizer instance does not implement the " +
+ PermissionResolverAware.class.getName() + " interface. This is required to support " +
+ "passthrough configuration of a PermissionResolver.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ /**
+ * First calls <code>super.realms</code> and then sets these same <code>Realm</code> objects on this instance's
+ * {@link Authorizer Authorizer}.
+ * <p/>
+ * The setting on the Authorizer will only occur if it is an instance of
+ * {@link org.jsecurity.authz.ModularRealmAuthorizer ModularRealmAuthorizer}, that is:
+ * <pre> Authorizer authz = getAuthorizer();
+ * if ( authz instanceof ModularRealmAuthorizer ) {
+ * ((ModularRealmAuthorizer)authz).setRealms(realms);
+ * }</pre>
+ * @param realms the realms managed by this <tt>SecurityManager</tt> instance.
+ */
+ public void setRealms(Collection<Realm> realms) {
+ super.setRealms(realms);
+ Authorizer authz = getAuthorizer();
+ if (authz instanceof ModularRealmAuthorizer) {
+ ((ModularRealmAuthorizer) authz).setRealms(realms);
+ }
+ }
+
+ /**
+ * Template hook for subclasses to implement destruction/cleanup logic. This will be called before this
+ * instance's <tt>Authorizer</tt> instance will be cleaned up.
+ */
+ protected void beforeAuthorizerDestroyed() {
+ }
+
+ /**
+ * Cleanup method that destroys/cleans up the wrapped {@link #getAuthorizer Authorizer} instance.
+ * <p/>
+ * The default implementation merely delegates to
+ * <code>{@link LifecycleUtils#destroy LifecycleUtils.destroy}({@link #getAuthorizer getAuthorizer()})</code>.
+ */
+ protected void destroyAuthorizer() {
+ LifecycleUtils.destroy(getAuthorizer());
+ }
+
+ /**
+ * Implementation of parent class's template hook for destruction/cleanup logic.
+ *
+ * <p>This implementation ensures subclasses are cleaned up first by calling
+ * {@link #beforeAuthorizerDestroyed() beforeAuthorizerDestroyed()} and then actually cleans up the
+ * wrapped <tt>Authorizer</tt> via the {@link #destroyAuthorizer() desroyAuthorizer()} method.
+ */
+ protected void beforeAuthenticatorDestroyed() {
+ beforeAuthorizerDestroyed();
+ destroyAuthorizer();
+ }
+
+ public boolean isPermitted(PrincipalCollection principals, String permissionString) {
+ ensureRealms();
+ return getAuthorizer().isPermitted(principals, permissionString);
+ }
+
+ public boolean isPermitted(PrincipalCollection principals, Permission permission) {
+ ensureRealms();
+ return getAuthorizer().isPermitted(principals, permission);
+ }
+
+ public boolean[] isPermitted(PrincipalCollection principals, String... permissions) {
+ ensureRealms();
+ return getAuthorizer().isPermitted(principals, permissions);
+ }
+
+ public boolean[] isPermitted(PrincipalCollection principals, List<Permission> permissions) {
+ ensureRealms();
+ return getAuthorizer().isPermitted(principals, permissions);
+ }
+
+ public boolean isPermittedAll(PrincipalCollection principals, String... permissions) {
+ ensureRealms();
+ return getAuthorizer().isPermittedAll(principals, permissions);
+ }
+
+ public boolean isPermittedAll(PrincipalCollection principals, Collection<Permission> permissions) {
+ ensureRealms();
+ return getAuthorizer().isPermittedAll(principals, permissions);
+ }
+
+ public void checkPermission(PrincipalCollection principals, String permission) throws AuthorizationException {
+ ensureRealms();
+ getAuthorizer().checkPermission(principals, permission);
+ }
+
+ public void checkPermission(PrincipalCollection principals, Permission permission) throws AuthorizationException {
+ ensureRealms();
+ getAuthorizer().checkPermission(principals, permission);
+ }
+
+ public void checkPermissions(PrincipalCollection principals, String... permissions) throws AuthorizationException {
+ ensureRealms();
+ getAuthorizer().checkPermissions(principals, permissions);
+ }
+
+ public void checkPermissions(PrincipalCollection principals, Collection<Permission> permissions) throws AuthorizationException {
+ ensureRealms();
+ getAuthorizer().checkPermissions(principals, permissions);
+ }
+
+ public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {
+ ensureRealms();
+ return getAuthorizer().hasRole(principals, roleIdentifier);
+ }
+
+ public boolean[] hasRoles(PrincipalCollection principals, List<String> roleIdentifiers) {
+ ensureRealms();
+ return getAuthorizer().hasRoles(principals, roleIdentifiers);
+ }
+
+ public boolean hasAllRoles(PrincipalCollection principals, Collection<String> roleIdentifiers) {
+ ensureRealms();
+ return getAuthorizer().hasAllRoles(principals, roleIdentifiers);
+ }
+
+ public void checkRole(PrincipalCollection principals, String role) throws AuthorizationException {
+ ensureRealms();
+ getAuthorizer().checkRole(principals, role);
+ }
+
+ public void checkRoles(PrincipalCollection principals, Collection<String> roles) throws AuthorizationException {
+ ensureRealms();
+ getAuthorizer().checkRoles(principals, roles);
+ }
+}
diff --git a/core/src/org/jsecurity/mgt/CachingSecurityManager.java b/core/src/org/jsecurity/mgt/CachingSecurityManager.java
new file mode 100644
index 0000000..847fb16
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/CachingSecurityManager.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.cache.CacheManager;
+import org.jsecurity.cache.CacheManagerAware;
+import org.jsecurity.cache.ehcache.EhCacheManager;
+import org.jsecurity.util.Destroyable;
+import org.jsecurity.util.LifecycleUtils;
+
+/**
+ * A very basic extension point for the SecurityManager interface that merely provides logging and caching
+ * support. All <tt>SecurityManager</tt> method implementations are left to subclasses.
+ *
+ * <p>Upon instantiation, a sensible default {@link CacheManager CacheManager} will be attempt to be created
+ * automatically by the {@link #ensureCacheManager() ensureCacheManager()} method. This <code>CacheManager</code>
+ * can then be used by subclass implementations and children components for use to achieve better application
+ * performance.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public abstract class CachingSecurityManager implements SecurityManager, Destroyable, CacheManagerAware {
+
+ /**
+ * Internal private static log instance.
+ */
+ private static final Log log = LogFactory.getLog(CachingSecurityManager.class);
+
+ /**
+ * The CacheManager to use to perform caching operations to enhance performance. Can be null.
+ */
+ protected CacheManager cacheManager;
+
+ /**
+ * Default no-arg constructor that will automatically attempt to initialize a default cacheManager
+ */
+ public CachingSecurityManager() {
+ ensureCacheManager();
+ }
+
+ /**
+ * Returns the CacheManager used by this SecurityManager.
+ *
+ * @return the cacheManager used by this SecurityManager
+ */
+ public CacheManager getCacheManager() {
+ return cacheManager;
+ }
+
+ /**
+ * Sets the CacheManager used by this <code>SecurityManager</code> and potentially any of its
+ * children components.
+ * <p/>
+ * After the cacheManager attribute has been set, the template method
+ * {@link #afterCacheManagerSet afterCacheManagerSet()} is executed to allow subclasses to adjust when a
+ * cacheManager is available.
+ *
+ * @param cacheManager the CacheManager used by this <code>SecurityManager</code> and potentially any of its
+ * children components.
+ */
+ public void setCacheManager(CacheManager cacheManager) {
+ this.cacheManager = cacheManager;
+ afterCacheManagerSet();
+ }
+
+ /**
+ * Simple lazy-initialization method that checks to see if a
+ * {@link #setCacheManager(org.jsecurity.cache.CacheManager) cacheManager} has been set, and if not,
+ * attempts to {@link #createCacheManager() create one} and uses that to set the class attribute.
+ * <p/>
+ * The default implementation functions as follows:
+ * <pre><code>
+ * CacheManager cm = getCacheManager();
+ * if (cm == null) {
+ * cm = createCacheManager();
+ * if (cm != null) {
+ * setCacheManager(cm);
+ * }
+ * }</code></pre>
+ */
+ protected void ensureCacheManager() {
+ CacheManager cm = getCacheManager();
+ if (cm == null) {
+ cm = createCacheManager();
+ if (cm != null) {
+ setCacheManager(cm);
+ }
+ }
+ }
+
+ /**
+ * Template callback to notify subclasses that a
+ * {@link CacheManager CacheManager} has been set and is available for use via the
+ * {@link #getCacheManager getCacheManager()} method.
+ */
+ protected void afterCacheManagerSet() {
+ }
+
+ /**
+ * Creates a {@link CacheManager CacheManager} instance to be used by this <code>SecurityManager</code>
+ * and potentially any of its children components.
+ * <p/>
+ * This default implementation attempts to create an {@link org.jsecurity.cache.ehcache.EhCacheManager EhCacheManager}, assuming that
+ * ehcache is in the classpath. If Ehcache is not in the classpath, no cache manager will be created and this
+ * method does nothing.
+ * <p/>
+ * This can be overridden by subclasses for a different implementation, but it is often easier to set a
+ * different implementation via the {@link #setCacheManager(org.jsecurity.cache.CacheManager) setCacheManager}
+ * method, for example in code or Dependency Injection frameworks (a la Spring or JEE 3).
+ *
+ * @return a newly created <code>CacheManager</code> instance.
+ * @see #ensureCacheManager() ensureCacheManager()
+ */
+ protected CacheManager createCacheManager() {
+ CacheManager manager = null;
+
+ if (log.isDebugEnabled()) {
+ log.debug("Attempting to initialize default CacheManager using EhCache...");
+ }
+
+ try {
+ EhCacheManager ehCacheManager = new EhCacheManager();
+ ehCacheManager.init();
+ manager = ehCacheManager;
+ } catch (NoClassDefFoundError e) {
+ if (log.isDebugEnabled()) {
+ log.debug("Ehcache was not found in the classpath. A default EhCacheManager cannot be created.");
+ }
+ }
+
+ return manager;
+ }
+
+ /**
+ * First calls {@link #beforeCacheManagerDestroyed() beforeCacheManagerDestroyed()} to allow subclasses to clean up
+ * first, then calls {@link #destroyCacheManager() destroyCacheManager()} to clean up the internal
+ * {@link CacheManager CacheManager}.
+ */
+ public void destroy() {
+ beforeCacheManagerDestroyed();
+ destroyCacheManager();
+ }
+
+ /**
+ * Template hook for subclasses to perform cleanup behavior during shutdown.
+ */
+ protected void beforeCacheManagerDestroyed() {
+ }
+
+ /**
+ * Cleans up the internal <code>CacheManager</code> instance during shutdown.
+ */
+ protected void destroyCacheManager() {
+ LifecycleUtils.destroy(getCacheManager());
+ }
+}
diff --git a/core/src/org/jsecurity/mgt/DefaultSecurityManager.java b/core/src/org/jsecurity/mgt/DefaultSecurityManager.java
new file mode 100644
index 0000000..c9adf89
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/DefaultSecurityManager.java
@@ -0,0 +1,428 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.*;
+import org.jsecurity.authz.Authorizer;
+import org.jsecurity.crypto.Cipher;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.subject.*;
+import org.jsecurity.util.ThreadContext;
+
+import java.net.InetAddress;
+import java.util.Collection;
+
+/**
+ * <p>The JSecurity framework's default concrete implementation of the {@link SecurityManager} interface,
+ * based around a collection of {@link org.jsecurity.realm.Realm}s. This implementation delegates its
+ * authentication, authorization, and session operations to wrapped {@link Authenticator}, {@link Authorizer}, and
+ * {@link org.jsecurity.session.mgt.SessionManager SessionManager} instances respectively via superclass
+ * implementation.</p>
+ *
+ * <p>To greatly reduce and simplify configuration, this implementation (and its superclasses) will
+ * create suitable defaults for <em>all</em> of its required dependencies. Therefore, you only need to override
+ * attributes for custom behavior. But, note the following:</p>
+ *
+ * <p>Unless you're happy with the default simple {@link org.jsecurity.realm.text.PropertiesRealm properties file}-based realm, which may or
+ * may not be flexible enough for enterprise applications, you might want to specify at least one custom
+ * <tt>Realm</tt> implementation that 'knows' about your application's data/security model
+ * (via {@link #setRealm} or one of the overloaded constructors). All other attributes in this class hierarchy
+ * will have suitable defaults for most enterprise applications.</p>
+ *
+ * <p><b>RememberMe notice</b>: This class supports the ability to configure a
+ * {@link #setRememberMeManager RememberMeManager}
+ * for <tt>RememberMe</tt> identity services for login/logout, BUT, a default instance <em>will not</em> be created
+ * for this attribute at startup.
+ *
+ * <p>Because RememberMe services are inherently client tier-specific and
+ * therefore aplication-dependent, if you want <tt>RememberMe</tt> services enabled, you will have to specify an
+ * instance yourself via the {@link #setRememberMeManager(org.jsecurity.subject.RememberMeManager) setRememberMeManager}
+ * mutator. However if you're reading this JavaDoc with the
+ * expectation of operating in a Web environment, take a look at the
+ * {@link org.jsecurity.web.DefaultWebSecurityManager DefaultWebSecurityManager} implementation, which
+ * <em>does</em> support <tt>RememberMe</tt> services by default at startup.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @see org.jsecurity.web.DefaultWebSecurityManager
+ * @since 0.2
+ */
+public class DefaultSecurityManager extends SessionsSecurityManager {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(DefaultSecurityManager.class);
+
+ protected RememberMeManager rememberMeManager;
+
+ /**
+ * Default no-arg constructor.
+ */
+ public DefaultSecurityManager() {
+ }
+
+ /**
+ * Supporting constructor for a single-realm application.
+ *
+ * @param singleRealm the single realm used by this SecurityManager.
+ */
+ public DefaultSecurityManager(Realm singleRealm) {
+ setRealm(singleRealm);
+ }
+
+ /**
+ * Supporting constructor for multiple {@link #setRealms realms}.
+ *
+ * @param realms the realm instances backing this SecurityManager.
+ */
+ public DefaultSecurityManager(Collection<Realm> realms) {
+ setRealms(realms);
+ }
+
+ public RememberMeManager getRememberMeManager() {
+ return rememberMeManager;
+ }
+
+ public void setRememberMeManager(RememberMeManager rememberMeManager) {
+ this.rememberMeManager = rememberMeManager;
+ }
+
+ private AbstractRememberMeManager getRememberMeManagerForCipherAttributes() {
+ RememberMeManager rmm = getRememberMeManager();
+ if (!(rmm instanceof AbstractRememberMeManager)) {
+ String msg = "The convenience passthrough methods for setting remember me cipher attributes " +
+ "are only available when the underlying RememberMeManager implementation is a subclass of " +
+ AbstractRememberMeManager.class.getName() + ".";
+ throw new IllegalStateException(msg);
+ }
+ return (AbstractRememberMeManager) rmm;
+ }
+
+ public void setRememberMeCipher(Cipher cipher) {
+ getRememberMeManagerForCipherAttributes().setCipher(cipher);
+ }
+
+ public void setRememberMeCipherKey(byte[] bytes) {
+ getRememberMeManagerForCipherAttributes().setCipherKey(bytes);
+ }
+
+ public void setRememberMeCipherKeyHex(String hex) {
+ getRememberMeManagerForCipherAttributes().setCipherKeyHex(hex);
+ }
+
+ public void setRememberMeCipherKeyBase64(String base64) {
+ getRememberMeManagerForCipherAttributes().setCipherKeyBase64(base64);
+ }
+
+ public void setRememberMeEncryptionCipherKey(byte[] bytes) {
+ getRememberMeManagerForCipherAttributes().setEncryptionCipherKey(bytes);
+ }
+
+ public void setRememberMeEncryptionCipherKeyHex(String hex) {
+ getRememberMeManagerForCipherAttributes().setEncryptionCipherKeyHex(hex);
+ }
+
+ public void setRememberMeEncryptionCipherKeyBase64(String base64) {
+ getRememberMeManagerForCipherAttributes().setEncryptionCipherKeyBase64(base64);
+ }
+
+ public void setRememberMeDecryptionCipherKey(byte[] bytes) {
+ getRememberMeManagerForCipherAttributes().setDecryptionCipherKey(bytes);
+ }
+
+ public void setRememberMeDecryptionCipherKeyHex(String hex) {
+ getRememberMeManagerForCipherAttributes().setDecryptionCipherKeyHex(hex);
+ }
+
+ public void setRememberMeDecryptionCipherKeyBase64(String base64) {
+ getRememberMeManagerForCipherAttributes().setDecryptionCipherKeyBase64(base64);
+ }
+
+ private void assertPrincipals(AuthenticationInfo info) {
+ PrincipalCollection principals = info.getPrincipals();
+ if (principals == null || principals.isEmpty()) {
+ String msg = "Authentication info returned from Authenticator must have non null and non empty principals.";
+ throw new IllegalArgumentException(msg);
+ }
+ }
+
+ protected Subject createSubject() {
+ PrincipalCollection principals = getRememberedIdentity();
+ return createSubject(principals);
+ }
+
+ protected Subject createSubject(PrincipalCollection subjectPrincipals) {
+ return createSubject(subjectPrincipals, null);
+ }
+
+ protected Subject createSubject(PrincipalCollection principals, Session existing) {
+ return createSubject(principals, existing, false);
+ }
+
+ protected Subject createSubject(PrincipalCollection principals, Session existing, boolean authenticated) {
+ return createSubject(principals, existing, authenticated, null);
+ }
+
+ protected Subject createSubject(PrincipalCollection principals, Session existing,
+ boolean authenticated, InetAddress inetAddress) {
+ return new DelegatingSubject(principals, authenticated, inetAddress, existing, this);
+ }
+
+ /**
+ * Creates a <tt>Subject</tt> instance for the user represented by the given method arguments.
+ *
+ * @param token the <tt>AuthenticationToken</tt> submitted for the successful authentication.
+ * @param info the <tt>AuthenticationInfo</tt> of a newly authenticated user.
+ * @return the <tt>Subject</tt> instance that represents the user and session data for the newly
+ * authenticated user.
+ */
+ protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info) {
+ assertPrincipals(info);
+
+ //get any existing session that may exist - we don't want to lose it:
+ Subject subject = getSubject(false);
+ Session session = null;
+ if (subject != null) {
+ session = subject.getSession(false);
+ }
+
+ InetAddress authcSourceIP = null;
+ if (token instanceof InetAuthenticationToken) {
+ authcSourceIP = ((InetAuthenticationToken) token).getInetAddress();
+ }
+ if (authcSourceIP == null) {
+ //try the thread local:
+ authcSourceIP = ThreadContext.getInetAddress();
+ }
+
+ return createSubject(info.getPrincipals(), session, true, authcSourceIP);
+ }
+
+ /**
+ * Binds a <tt>Subject</tt> instance created after authentication to the application for later use.
+ *
+ * <p>The default implementation merely binds the argument to the thread local via the {@link ThreadContext}.
+ * Should be overridden by subclasses for environment-specific binding (e.g. web environment, etc).
+ *
+ * @param subject the <tt>Subject</tt> instance created after authentication to be bound to the application
+ * for later use.
+ */
+ protected void bind(Subject subject) {
+ if (log.isTraceEnabled()) {
+ log.trace("Binding Subject [" + subject + "] to a thread local...");
+ }
+ ThreadContext.bind(subject);
+ }
+
+ private void assertCreation(Subject subject) throws IllegalStateException {
+ if (subject == null) {
+ String msg = "Programming error - please verify that you have overridden the " +
+ getClass().getName() + ".createSubject( AuthenticationInfo info ) method to return " +
+ "a non-null Subject instance";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ protected void rememberMeSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info) {
+ RememberMeManager rmm = getRememberMeManager();
+ if (rmm != null) {
+ try {
+ rmm.onSuccessfulLogin(token, info);
+ } catch (Exception e) {
+ if (log.isWarnEnabled()) {
+ String msg = "Delegate RememberMeManager instance of type [" + rmm.getClass().getName() +
+ "] threw an exception during onSuccessfulLogin. RememberMe services will not be " +
+ "performed for account [" + info + "].";
+ log.warn(msg, e);
+ }
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("This " + getClass().getName() + " instance does not have a " +
+ "[" + RememberMeManager.class.getName() + "] instance configured. RememberMe services " +
+ "will not be performed for account [" + info + "].");
+ }
+ }
+ }
+
+ protected void rememberMeFailedLogin(AuthenticationToken token, AuthenticationException ex) {
+ RememberMeManager rmm = getRememberMeManager();
+ if (rmm != null) {
+ try {
+ rmm.onFailedLogin(token, ex);
+ } catch (Exception e) {
+ if (log.isWarnEnabled()) {
+ String msg = "Delegate RememberMeManager instance of type [" + rmm.getClass().getName() +
+ "] threw an exception during onFailedLogin for AuthenticationToken [" +
+ token + "].";
+ log.warn(msg, e);
+ }
+ }
+ }
+ }
+
+ protected void rememberMeLogout(PrincipalCollection subjectPrincipals) {
+ RememberMeManager rmm = getRememberMeManager();
+ if (rmm != null) {
+ try {
+ rmm.onLogout(subjectPrincipals);
+ } catch (Exception e) {
+ if (log.isWarnEnabled()) {
+ String msg = "Delegate RememberMeManager instance of type [" + rmm.getClass().getName() +
+ "] threw an exception during onLogout for subject with principals [" +
+ subjectPrincipals + "]";
+ log.warn(msg, e);
+ }
+ }
+ }
+ }
+
+ /**
+ * First authenticates the <tt>AuthenticationToken</tt> argument, and if successful, constructs a
+ * <tt>Subject</tt> instance representing the authenticated account's identity.
+ *
+ * <p>Once constructed, the <tt>Subject</tt> instance is then {@link #bind bound} to the application for
+ * subsequent access before being returned to the caller.
+ *
+ * @param token the authenticationToken to process for the login attempt.
+ * @return a Subject representing the authenticated user.
+ * @throws AuthenticationException if there is a problem authenticating the specified <tt>token</tt>.
+ */
+ public Subject login(AuthenticationToken token) throws AuthenticationException {
+ AuthenticationInfo info;
+ try {
+ info = authenticate(token);
+ onSuccessfulLogin(token, info);
+ } catch (AuthenticationException ae) {
+ try {
+ onFailedLogin(token, ae);
+ } catch (Exception e) {
+ if (log.isInfoEnabled()) {
+ log.info("onFailedLogin(AuthenticationToken,AuthenticationException) method threw an " +
+ "exception. Logging and propagating original AuthenticationException.", e);
+ }
+ }
+ throw ae; //propagate
+ }
+ Subject subject = createSubject(token, info);
+ assertCreation(subject);
+ bind(subject);
+ return subject;
+ }
+
+ protected void onSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info) {
+ rememberMeSuccessfulLogin(token, info);
+ }
+
+ protected void onFailedLogin(AuthenticationToken token, AuthenticationException ae) {
+ rememberMeFailedLogin(token, ae);
+ }
+
+ protected void beforeLogout(PrincipalCollection subjectIdentifier) {
+ rememberMeLogout(subjectIdentifier);
+ }
+
+ public void logout(PrincipalCollection principals) {
+
+ if (principals != null) {
+
+ beforeLogout(principals);
+
+ Authenticator authc = getAuthenticator();
+ if (authc instanceof LogoutAware) {
+ ((LogoutAware) authc).onLogout(principals);
+ }
+ }
+
+ //Method arg is ignored - get the Subject from the environment if it exists:
+ Subject subject = getSubject(false);
+ if (subject != null) {
+ try {
+ stopSession(subject);
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ String msg = "Unable to cleanly stop Session for Subject [" + subject.getPrincipal() + "] " +
+ "Ignoring (logging out).";
+ log.debug(msg, e);
+ }
+ }
+ try {
+ unbind(subject);
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ String msg = "Unable to cleanly unbind Subject. Ignoring (logging out).";
+ log.debug(msg, e);
+ }
+ }
+ }
+ }
+
+ protected void stopSession(Subject subject) {
+ Session s = subject.getSession(false);
+ if (s != null) {
+ try {
+ s.stop();
+ } catch (InvalidSessionException ise) {
+ //ignored - we're invalidating, and have no further need of the session anyway
+ //log just in case someone wants to know:
+ if (log.isTraceEnabled()) {
+ log.trace("Session has already been invalidated for subject [" +
+ subject.getPrincipal() + "]. Ignoring and continuing logout ...", ise);
+ }
+ }
+ }
+ }
+
+ protected void unbind(Subject subject) {
+ ThreadContext.unbindSubject();
+ }
+
+ protected PrincipalCollection getRememberedIdentity() {
+ RememberMeManager rmm = getRememberMeManager();
+ if (rmm != null) {
+ try {
+ return rmm.getRememberedPrincipals();
+ } catch (Exception e) {
+ if (log.isWarnEnabled()) {
+ String msg = "Delegate RememberMeManager instance of type [" + rmm.getClass().getName() +
+ "] threw an exception during getRememberedPrincipals().";
+ log.warn(msg, e);
+ }
+ }
+ }
+ return null;
+ }
+
+ protected Subject getSubject(boolean create) {
+ Subject subject = ThreadContext.getSubject();
+ if (subject == null && create) {
+ subject = createSubject();
+ bind(subject);
+ }
+ return subject;
+ }
+
+ public Subject getSubject() {
+ return getSubject(true);
+ }
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/mgt/RealmSecurityManager.java b/core/src/org/jsecurity/mgt/RealmSecurityManager.java
new file mode 100644
index 0000000..efc1cb5
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/RealmSecurityManager.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.cache.CacheManager;
+import org.jsecurity.cache.CacheManagerAware;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.realm.text.PropertiesRealm;
+import org.jsecurity.util.LifecycleUtils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * JSecurity support of a {@link SecurityManager} class hierarchy based around a collection of
+ * {@link org.jsecurity.realm.Realm}s. All actual <tt>SecurityManager</tt> method implementations are left to
+ * subclasses.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class RealmSecurityManager extends CachingSecurityManager {
+
+ /**
+ * Internal private log instance.
+ */
+ private static final Log log = LogFactory.getLog(RealmSecurityManager.class);
+
+ /**
+ * Internal collection of <code>Realm</code>s used for all authentication and authorization operations.
+ */
+ protected Collection<Realm> realms;
+
+ /**
+ * Default no-arg constructor.
+ */
+ public RealmSecurityManager() {
+ }
+
+ /**
+ * Convenience method for applications using a single realm that merely wraps the realm in a list and then invokes
+ * the {@link #setRealms} method.
+ *
+ * @param realm the realm to set for a single-realm application.
+ * @since 0.2
+ */
+ public void setRealm(Realm realm) {
+ if (realm == null) {
+ throw new IllegalArgumentException("Realm argument cannot be null");
+ }
+ Collection<Realm> realms = new ArrayList<Realm>(1);
+ realms.add(realm);
+ setRealms(realms);
+ }
+
+ /**
+ * Sets the realms managed by this <tt>SecurityManager</tt> instance.
+ *
+ * @param realms the realms managed by this <tt>SecurityManager</tt> instance.
+ */
+ public void setRealms(Collection<Realm> realms) {
+ if (realms == null) {
+ throw new IllegalArgumentException("Realms collection argument cannot be null.");
+ }
+ if (realms.isEmpty()) {
+ throw new IllegalArgumentException("Realms collection argument cannot be empty.");
+ }
+ this.realms = realms;
+ applyCacheManagerToRealms();
+ }
+
+ /**
+ * Ensures at least one realm exists, and if not calls {@link #createDefaultRealm() createDefaultRealm()} and sets
+ * it on this instance via the {@link #setRealm(Realm) setRealm} method.
+ * <p/>
+ * This method is used to lazily ensure at least one default Realm exists in all environments, even if it is just
+ * with demo data, to ensure that JSecurity is usuable with the smallest (even no) configuration.
+ */
+ protected void ensureRealms() {
+ Collection<Realm> realms = getRealms();
+ if (realms == null || realms.isEmpty()) {
+ if (log.isInfoEnabled()) {
+ log.info("No Realms configured. Defaulting to failsafe PropertiesRealm.");
+ }
+ Realm realm = createDefaultRealm();
+ setRealm(realm);
+ }
+ }
+
+ /**
+ * Creates a default Realm implementation to use in lazy-initialization use cases.
+ * <p/>
+ * The implementation returned is a {@link PropertiesRealm PropertiesRealm}, which supports very simple
+ * properties-based user/role/permission configuration in testing, sample, and simple applications.
+ * @return the default Realm implementation (a {@link PropertiesRealm PropertiesRealm} to use in lazy-init use cases.
+ */
+ protected Realm createDefaultRealm() {
+ PropertiesRealm realm;
+ CacheManager cacheManager = getCacheManager();
+ if (cacheManager != null) {
+ realm = new PropertiesRealm(cacheManager);
+ } else {
+ realm = new PropertiesRealm();
+ }
+ return realm;
+ }
+
+ /**
+ * Returns the {@link Realm Realm}s managed by this SecurityManager instance.
+ *
+ * @return the {@link Realm Realm}s managed by this SecurityManager instance.
+ */
+ public Collection<Realm> getRealms() {
+ return realms;
+ }
+
+ /**
+ * Sets the internal {@link #getCacheManager CacheManager} on any internal configured
+ * {@link #getRealms Realms} that implement the {@link CacheManagerAware CacheManagerAware} interface.
+ * <p/>
+ * This method is called after setting a cacheManager on this securityManager via the
+ * {@link #setCacheManager(org.jsecurity.cache.CacheManager) setCacheManager} method to allow it to be propagated
+ * down to all the internal Realms that would need to use it.
+ * <p/>
+ * It is also called after setting one or more realms via the {@link #setRealm setRealm} or
+ * {@link #setRealms setRealms} methods to allow these newly available realms to be given the cache manager
+ * already in use.
+ */
+ protected void applyCacheManagerToRealms() {
+ CacheManager cacheManager = getCacheManager();
+ Collection<Realm> realms = getRealms();
+ if (cacheManager != null && realms != null && !realms.isEmpty()) {
+ for (Realm realm : realms) {
+ if (realm instanceof CacheManagerAware) {
+ ((CacheManagerAware) realm).setCacheManager(cacheManager);
+ }
+ }
+ }
+ }
+
+ /**
+ * Simply calls {@link #applyCacheManagerToRealms() applyCacheManagerToRealms()} to allow the
+ * newly set {@link CacheManager CacheManager} to be propagated to the internal collection of <code>Realm</code>
+ * that would need to use it.
+ *
+ */
+ protected void afterCacheManagerSet() {
+ applyCacheManagerToRealms();
+ }
+
+ /**
+ * First calls {@link #beforeRealmsDestroyed() beforeRealmsDestroyed()} to allow subclasses to clean up
+ * first, then calls {@link #destroyRealms() destroyRealms()} to clean up the internal <code>Realm</code>s
+ * collection.
+ */
+ protected void beforeCacheManagerDestroyed() {
+ beforeRealmsDestroyed();
+ destroyRealms();
+ }
+
+ /**
+ * Template hook for subclasses to perform clean up logic during shut-down.
+ */
+ protected void beforeRealmsDestroyed() {
+ }
+
+ /**
+ * Cleans up ('destroys') the internal collection of Realms by calling
+ * {@link LifecycleUtils#destroy(Collection) LifecycleUtils.destroy(getRealms())}.
+ */
+ protected void destroyRealms() {
+ LifecycleUtils.destroy(getRealms());
+ this.realms = null;
+ }
+
+}
diff --git a/core/src/org/jsecurity/mgt/SecurityManager.java b/core/src/org/jsecurity/mgt/SecurityManager.java
new file mode 100644
index 0000000..5a23e7d
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/SecurityManager.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.Authenticator;
+import org.jsecurity.authz.Authorizer;
+import org.jsecurity.session.SessionFactory;
+import org.jsecurity.subject.PrincipalCollection;
+import org.jsecurity.subject.Subject;
+
+/**
+ * A <tt>SecurityManager</tt> executes all security operations for <em>all</em> Subjects (aka users) across a
+ * single application.
+ *
+ * <p>The interface itself primarily exists as a convenience - it extends the {@link Authenticator},
+ * {@link Authorizer}, and {@link SessionFactory} interfaces, thereby consolidating
+ * these behaviors into a single point of reference. For most JSecurity usages, this simplifies configuration and
+ * tends to be a more convenient approach than referencing <code>Authenticator</code>, <code>Authorizer</code>, and
+ * <code>SessionFactory</code> instances seperately; instead one only needs to interact with a
+ * single <tt>SecurityManager</tt> instance.</p>
+ *
+ * <p>In addition to the above three interfaces, three unique methods are provided by this interface by itself,
+ * {@link #login}, {@link #logout} and {@link #getSubject}. A {@link Subject Subject} executes
+ * authentication, authorization, and session operations for a <em>single</em> user, and as such can only be
+ * managed by <tt>A SecurityManager</tt> which is aware of all three functions. The three parent interfaces on the
+ * other hand do not 'know' about <tt>Subject</tt>s to ensure a clean separation of concerns.
+ *
+ * <p><b>Usage Note</b>: In actuality the large majority of application programmers won't interact with a SecurityManager
+ * very often, if at all. <em>Most</em> application programmers only care about security operations for the currently
+ * executing user.
+ *
+ * <p>In that case, the application programmer can call the
+ * {@link #getSubject() getSubject()} method and then use that returned instance for continued interaction with
+ * JSecurity. If your application code does not have a direct handle to the application's
+ * <code>SecurityManager</code>, you can use {@link org.jsecurity.SecurityUtils SecurityUtils} anywhere in your code
+ * to achieve the same result.
+ *
+ * <p>Framework developers on the other hand might find working with an actual SecurityManager useful.
+ *
+ * @author Les Hazlewood
+ * @see DefaultSecurityManager
+ * @since 0.2
+ */
+public interface SecurityManager extends Authenticator, Authorizer, SessionFactory {
+
+ /**
+ * Logs in a user, returning a Subject instance if the authentication is successful or throwing an
+ * <code>AuthenticationException</code> if it is not.
+ * <p/>
+ * Note that most application developers should probably not call this method directly unless they have a good
+ * reason for doing so. The preferred way to log in a Subject is to call
+ * <code>{@link Subject#login Subject.login(authenticationToken)}</code> (usually after acquiring the
+ * Subject by calling {@link org.jsecurity.SecurityUtils#getSubject() SecurityUtils.getSubject()}).
+ * <p/>
+ * Framework developers on the other hand might find calling this method directly useful in certain cases.
+ *
+ * @param authenticationToken the token representing the Subject's principal(s) and credential(s)
+ * @return an authenticated Subject upon a successful attempt
+ * @throws AuthenticationException if the login attempt failed.
+ * @since 0.9
+ */
+ Subject login(AuthenticationToken authenticationToken) throws AuthenticationException;
+
+ /**
+ * Logs out the specified Subject from the system.
+ *
+ * <p>Note that most application developers should not call this method unless they have a good reason for doing
+ * so. The preferred way to logout a Subject is to call <code>{@link Subject#logout Subject.logout()}</code>, not
+ * the <code>SecurityManager</code> directly.
+ * <p/>
+ * Framework developers on the other hand might find calling this method directly useful in certain cases.
+ *
+ * @param subjectIdentifier the identifier of the subject/user to log out.
+ * @see #getSubject()
+ * @since 0.9
+ */
+ void logout(PrincipalCollection subjectIdentifier);
+
+ /**
+ * Returns the <tt>Subject</tt> instance representing the currently executing user.
+ *
+ * @return the <tt>Subject</tt> instance representing the currently executing user.
+ * @since 0.9
+ */
+ Subject getSubject();
+}
\ No newline at end of file
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/src/org/jsecurity/mgt/SecurityManagerFactory.java
similarity index 67%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/src/org/jsecurity/mgt/SecurityManagerFactory.java
index 8e597f2..56181c2 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/src/org/jsecurity/mgt/SecurityManagerFactory.java
@@ -1,23 +1,33 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+/**
+ * Allows implementations to create and return an application's SecurityManager instance in any manner necessary.
+ *
+ * @since 0.9
+ */
+public interface SecurityManagerFactory {
+
+ /**
+ * Returns a fully configured and initialized <code>SecurityManager</code>.
+ * @return a fully configured and initialized <code>SecurityManager</code>.
+ */
+ SecurityManager getSecurityManager();
+}
diff --git a/core/src/org/jsecurity/mgt/SessionsSecurityManager.java b/core/src/org/jsecurity/mgt/SessionsSecurityManager.java
new file mode 100644
index 0000000..59a5a9b
--- /dev/null
+++ b/core/src/org/jsecurity/mgt/SessionsSecurityManager.java
@@ -0,0 +1,268 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.HostUnauthorizedException;
+import org.jsecurity.cache.CacheManager;
+import org.jsecurity.cache.CacheManagerAware;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.SessionListener;
+import org.jsecurity.session.SessionListenerRegistrar;
+import org.jsecurity.session.mgt.DefaultSessionManager;
+import org.jsecurity.session.mgt.DelegatingSession;
+import org.jsecurity.session.mgt.SessionManager;
+import org.jsecurity.util.LifecycleUtils;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+
+/**
+ * JSecurity support of a {@link SecurityManager} class hierarchy that delegates all
+ * {@link org.jsecurity.session.Session session} operations to a wrapped {@link SessionManager SessionManager}
+ * instance. That is, this class implements the methods in the
+ * {@link SessionManager SessionManager} interface, but in reality, those methods are merely passthrough calls to
+ * the underlying 'real' <tt>SessionManager</tt> instance.
+ *
+ * <p>The remaining <tt>SecurityManager</tt> methods not implemented by this class or its parents are left to be
+ * implemented by subclasses.
+ *
+ * <p>In keeping with the other classes in this hierarchy and JSecurity's desire to minimize configuration whenever
+ * possible, suitable default instances for all dependencies will be created upon instantiation.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class SessionsSecurityManager extends AuthorizingSecurityManager implements SessionListenerRegistrar {
+
+ /**
+ * The internal delegate <code>SessionManager</code> used by this security manager that manages all the
+ * application's {@link Session Session}s.
+ */
+ protected SessionManager sessionManager;
+
+ /**
+ * Default no-arg constructor, internally creates a suitable default {@link SessionManager SessionManager} delegate
+ * instance via the {@link #ensureSessionManager() ensureSessionManager()} method.
+ */
+ public SessionsSecurityManager() {
+ ensureSessionManager();
+ }
+
+ /**
+ * Sets the underlying delegate {@link SessionManager} instance that will be used to support this implementation's
+ * <tt>SessionManager</tt> method calls.
+ *
+ * <p>This <tt>SecurityManager</tt> implementation does not provide logic to support the inherited
+ * <tt>SessionManager</tt> interface, but instead delegates these calls to an internal
+ * <tt>SessionManager</tt> instance.
+ *
+ * <p>If a <tt>SessionManager</tt> instance is not set, a default one will be automatically created and
+ * initialized appropriately for the the existing runtime environment.
+ *
+ * @param sessionManager delegate instance to use to support this manager's <tt>SessionManager</tt> method calls.
+ */
+ public void setSessionManager(SessionManager sessionManager) {
+ this.sessionManager = sessionManager;
+ }
+
+ /**
+ * Returns this security manager's internal delegate {@link SessionManager SessionManager}.
+ * @return this security manager's internal delegate {@link SessionManager SessionManager}.
+ * @see #setSessionManager(org.jsecurity.session.mgt.SessionManager) setSessionManager
+ */
+ public SessionManager getSessionManager() {
+ return this.sessionManager;
+ }
+
+ /**
+ * Ensures that the internal delegate <code>SessionManager</code> exists, and if not, calls
+ * {@link #createSessionManager createSessionManager} and sets the resulting instance via the
+ * {@link #setSessionManager(org.jsecurity.session.mgt.SessionManager) setSessionManager} method.
+ */
+ protected void ensureSessionManager() {
+ SessionManager sessionManager = getSessionManager();
+ if (sessionManager == null) {
+ sessionManager = createSessionManager();
+ setSessionManager(sessionManager);
+ }
+ }
+
+ /**
+ * Constructs a new <code>SessionManager</code> instance to be used as the internal delegate for this security
+ * manager. After creation via the {@link #newSessionManagerInstance() newSessionManagerInstance()} call, the
+ * internal {@link #getCacheManager CacheManager} is set on it if the session manager instance implements the
+ * {@link CacheManagerAware CacheManagerAware} interface to allow it to utilize the cache manager for its own
+ * internal caching needs.
+ *
+ * @return a new initialized {@link SessionManager SessionManager} to use as this security manager's internal
+ * delegate.
+ */
+ protected SessionManager createSessionManager() {
+ SessionManager sm = newSessionManagerInstance();
+ CacheManager cm = getCacheManager();
+ if (cm != null) {
+ if (sm instanceof CacheManagerAware) {
+ ((CacheManagerAware) sm).setCacheManager(cm);
+ }
+ }
+ return sm;
+ }
+
+ /**
+ * Merely instantiates (but does not initalize) the default <code>SessionManager</code> implementation. This method
+ * merely returns <code>new {@link DefaultSessionManager DefaultSessionManager}()</code>.
+ * @return a new, uninitialized {@link SessionManager SessionManager} instance.
+ */
+ protected SessionManager newSessionManagerInstance() {
+ return new DefaultSessionManager();
+ }
+
+ /**
+ * Calls {@link AuthorizingSecurityManager#afterCacheManagerSet() super.afterCacheManagerSet()} and then immediately calls
+ * {@link #applyCacheManagerToSessionManager() applyCacheManagerToSessionManager()} to ensure the
+ * <code>CacheManager</code> is applied to the SessionManager as necessary.
+ */
+ protected void afterCacheManagerSet() {
+ super.afterCacheManagerSet();
+ applyCacheManagerToSessionManager();
+ }
+
+ /**
+ * Ensures the internal delegate <code>SessionManager</code> is injected with the newly set
+ * {@link #setCacheManager CacheManager} so it may use it for its internal caching needs.
+ * <p/>
+ * Note: This implementation only injects the CacheManager into the SessionManager if the SessionManager
+ * instance implements the {@link CacheManagerAware CacheManagerAware} interface.
+ */
+ protected void applyCacheManagerToSessionManager() {
+ SessionManager sm = getSessionManager();
+ if (sm instanceof CacheManagerAware) {
+ ((CacheManagerAware) sm).setCacheManager(cacheManager);
+ }
+ }
+
+ /**
+ * This is a convenience method that allows registration of SessionListeners with the underlying delegate
+ * SessionManager at startup.
+ *
+ * <p>This is more convenient than having to configure your own SessionManager instance, inject the listeners on
+ * it, and then set that SessionManager instance as an attribute of this class. Instead, you can just rely
+ * on the <tt>SecurityManager</tt> to apply these <tt>SessionListener</tt>s on your behalf.
+ *
+ * <p>One notice however: The underlying SessionManager delegate must implement the
+ * {@link SessionListenerRegistrar SessionListenerRegistrar} interface in order for these listeners to
+ * be applied. If it does not implement this interface, it is considered a configuration error and an exception
+ * will be thrown.
+ *
+ * @param sessionListeners the <tt>SessionListener</tt>s to register with the underlying delegate
+ * <tt>SessionManager</tt> at startup.
+ */
+ public void setSessionListeners(Collection<SessionListener> sessionListeners) {
+ assertSessionListenerSupport();
+ ((SessionListenerRegistrar) this.sessionManager).setSessionListeners(sessionListeners);
+ }
+
+ /**
+ * Ensures the internal SessionManager instance is an <code>instanceof</code>
+ * {@link org.jsecurity.session.SessionListenerRegistrar SessionListenerRegistrar} to ensure that any
+ * listeners attempting to be registered can actually do so with the internal delegate instance.
+ * @throws IllegalStateException if the internal delegate SessionManager instance does not implement the
+ * <code>SessionListenerRegistrar</code> interface.
+ */
+ private void assertSessionListenerSupport() throws IllegalStateException {
+ if (!(this.sessionManager instanceof SessionListenerRegistrar)) {
+ String msg = "SessionListener registration failed: The underlying SessionManager instance of " +
+ "type [" + sessionManager.getClass().getName() + "] does not implement the " +
+ SessionListenerRegistrar.class.getName() + " interface and therefore cannot support " +
+ "session notifications.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ /**
+ * Asserts the internal delegate <code>SessionManager</code> instance
+ * {@link #assertSessionListenerSupport() supports session listener registration} and then
+ * {@link SessionListenerRegistrar#add adds} the listener to the
+ * delegate instance.
+ * @param listener the <code>SessionListener</code> to register for session events.
+ */
+ public void add(SessionListener listener) {
+ assertSessionListenerSupport();
+ SessionManager sm = getSessionManager();
+ ((SessionListenerRegistrar) sm).add(listener);
+ }
+
+ /**
+ * Removes the specified listener from receiving session events from the internal delegate
+ * {@link SessionManager} instance.
+ *
+ * @param listener the listener to remove that no longer wishes to be notified of session events.
+ * @return <code>true</code> if the listener was removed from the internal delegate <code>SessionManager</code>
+ * instance, <code>false</code> otherwise.
+ */
+ public boolean remove(SessionListener listener) {
+ SessionManager sm = getSessionManager();
+ return (sm instanceof SessionListenerRegistrar) &&
+ ((SessionListenerRegistrar) sm).remove(listener);
+ }
+
+ /**
+ * Template hook for subclasses that wish to perform clean up behavior during shutdown.
+ */
+ protected void beforeSessionManagerDestroyed() {
+ }
+
+ /**
+ * Cleans up ('destroys') the internal delegate <code>SessionManager</code> by calling
+ * {@link LifecycleUtils#destroy LifecycleUtils.destroy(getSessionManager())}.
+ */
+ protected void destroySessionManager() {
+ LifecycleUtils.destroy(getSessionManager());
+ }
+
+ /**
+ * Calls {@link #beforeSessionManagerDestroyed() beforeSessionManagerDestroyed()} to allow subclass clean up and
+ * then immediatley calls {@link #destroySessionManager() destroySessionManager()} to clean up the internal
+ * delegate instance.
+ */
+ protected void beforeAuthorizerDestroyed() {
+ beforeSessionManagerDestroyed();
+ destroySessionManager();
+ }
+
+ public Session start(InetAddress hostAddress) throws HostUnauthorizedException, IllegalArgumentException {
+ SessionManager sm = getSessionManager();
+ Serializable sessionId = sm.start(hostAddress);
+ return new DelegatingSession(sm, sessionId);
+ }
+
+ public Session getSession(Serializable sessionId) throws InvalidSessionException, AuthorizationException {
+ SessionManager sm = getSessionManager();
+ if (!sm.isValid(sessionId)) {
+ String msg = "Specified id [" + sessionId + "] does not correspond to a valid Session It either " +
+ "does not exist or the corresponding session has been stopped or expired.";
+ throw new InvalidSessionException(msg, sessionId);
+ }
+ return new DelegatingSession(sm, sessionId);
+ }
+
+}
diff --git a/core/src/org/jsecurity/realm/Realm.java b/core/src/org/jsecurity/realm/Realm.java
new file mode 100644
index 0000000..1b9dfae
--- /dev/null
+++ b/core/src/org/jsecurity/realm/Realm.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.realm;
+
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authz.Authorizer;
+
+/**
+ * A <tt>Realm</tt> is a security component that can access application-specific security entities
+ * such as users, roles, and permissions to determine authentication and authorization operations.
+ *
+ * <p><tt>Realm</tt>s usually have a 1-to-1 correspondance with a datasource such as a relational database,
+ * file sysetem, or other similar resource. As such, implementations of this interface use datasource-specific APIs to
+ * determine authorization data (roles, permissions, etc), such as JDBC, File IO, Hibernate or JPA, or any other
+ * Data Access API. They are essentially security-specific
+ * <a href="http://en.wikipedia.org/wiki/Data_Access_Object" target="_blank">DAO</a>s.
+ *
+ * <p>Because most of these datasources usually contain Subject (a.k.a. User) information such as usernames and
+ * passwords, a Realm can act as a pluggable authentication module in a
+ * <a href="http://en.wikipedia.org/wiki/Pluggable_Authentication_Modules">PAM</a> configuration. This allows a Realm to
+ * perform <i>both</i> authentication and authorization duties for a single datasource, which caters to the large
+ * majority of applications. If for some reason you don't want your Realm implementation to perform authentication
+ * duties, you should override the {@link #supports(org.jsecurity.authc.AuthenticationToken)} method to always
+ * return <tt>false</tt>.
+ *
+ * <p>Because every application is different, security data such as users and roles can be
+ * represented in any number of ways. JSecurity tries to maintain a non-intrusive development philosophy whenever
+ * possible - it does not require you to implement or extend any <tt>User</tt>, <tt>Group</tt> or <tt>Role</tt>
+ * interfaces or classes.
+ *
+ * <p>Instead, JSecurity allows applications to implement this interface to access environment-specific datasources
+ * and data model objects. The implementation can then be plugged in to the application's JSecurity configuration.
+ * This modular technique abstracts away any environment/modeling details and allows JSecurity to be deployed in
+ * practically any application environment.
+ *
+ * <p>Most users will not implement the <tt>Realm</tt> interface directly, but will extend one of the subclasses,
+ * {@link AuthenticatingRealm AuthenticatingRealm} or {@link AuthorizingRealm}, greatly reducing the effort requird
+ * to implement a <tt>Realm</tt> from scratch.</p>
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @see CachingRealm CachingRealm
+ * @see AuthenticatingRealm AuthenticatingRealm
+ * @see AuthorizingRealm AuthorizingRealm
+ * @see org.jsecurity.authc.pam.ModularRealmAuthenticator ModularRealmAuthenticator
+ * @since 0.1
+ */
+public interface Realm extends Authorizer {
+
+ /**
+ * Returns the (application-unique) name assigned to this <code>Realm</code>. All realms configured for a single
+ * application must have a unique name.
+ *
+ * @return the (application-unique) name assigned to this <code>Realm</code>.
+ */
+ String getName();
+
+ /**
+ * Returns <tt>true</tt> if this realm wishes to authenticate the Subject represented by the given
+ * {@link org.jsecurity.authc.AuthenticationToken AuthenticationToken} instance, <tt>false</tt> otherwise.
+ *
+ * <p>If this method returns <tt>false</tt>, it will not be called to authenticate the Subject represented by
+ * the token - more specifically, a <tt>false</tt> return value means this Realm instance's
+ * {@link #getAuthenticationInfo} method will not be invoked for that token.
+ *
+ * @param token the AuthenticationToken submitted for the authentication attempt
+ * @return <tt>true</tt> if this realm can/will authenticate Subjects represented by specified token,
+ * <tt>false</tt> otherwise.
+ */
+ boolean supports(AuthenticationToken token);
+
+ /**
+ * Returns an account's authentication-specific information for the specified <tt>token</tt>,
+ * or <tt>null</tt> if no account could be found based on the <tt>token</tt>.
+ *
+ * <p>This method effectively represents a login attempt for the corresponding user with the underlying EIS datasource.
+ * Most implementations merely just need to lookup and return the account data only (as the method name implies)
+ * and let JSecurity do the rest, but implementations may of course perform eis specific login operations if so
+ * desired.
+ *
+ * @param token the application-specific representation of an account principal and credentials.
+ * @return the authentication information for the account associated with the specified <tt>token</tt>,
+ * or <tt>null</tt> if no account could be found.
+ * @throws org.jsecurity.authc.AuthenticationException
+ * if there is an error obtaining or constructing an AuthenticationInfo object based on the
+ * specified <tt>token</tt> or implementation-specifc login behavior fails.
+ */
+ AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/realm/SimpleAccountRealm.java b/core/src/org/jsecurity/realm/SimpleAccountRealm.java
new file mode 100644
index 0000000..fdc262a
--- /dev/null
+++ b/core/src/org/jsecurity/realm/SimpleAccountRealm.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.realm;
+
+import org.jsecurity.authc.*;
+import org.jsecurity.authz.AuthorizationInfo;
+import org.jsecurity.authz.SimpleAuthorizingAccount;
+import org.jsecurity.authz.SimpleRole;
+import org.jsecurity.cache.Cache;
+import org.jsecurity.subject.PrincipalCollection;
+import org.jsecurity.util.CollectionUtils;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * <p>A simple implementation of the {@link org.jsecurity.realm.Realm Realm} interface that
+ * uses a set of configured user accounts and roles to support authentication and authorization. Each account entry
+ * specifies the username, password, and roles for a user. Roles can also be mapped
+ * to permissions and associated with users.</p>
+ *
+ * <p>User accounts and roles are stored in two {@link Cache cache}s, so it is the Cache manager implementation that
+ * determines if this class stores all data in memory or spools to disk or clusters it, etc based on the
+ * Caches it creates.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class SimpleAccountRealm extends AuthorizingRealm {
+
+ //TODO - complete JavaDoc
+
+ protected Map<String, SimpleRole> roles = null;
+
+ public SimpleAccountRealm() {
+ init();
+ }
+
+ public SimpleAccountRealm(String name) {
+ setName(name);
+ init();
+ }
+
+ public void afterAuthorizationCacheSet() {
+ initRoleCache();
+ afterRoleCacheSet();
+ }
+
+ public void afterRoleCacheSet() {
+ }
+
+ protected void initRoleCache() {
+ if (getAuthorizationCache() == null) {
+ initAuthorizationCache();
+ }
+
+ this.roles = new HashMap<String, SimpleRole>();
+ accountAndRoleCachesCreated();
+ }
+
+ protected SimpleAccount getUser(String username) {
+ return (SimpleAccount) getAuthorizationCache().get(username);
+ }
+
+ public boolean accountExists(String username) {
+ return getUser(username) != null;
+ }
+
+ public void addAccount(String username, String password) {
+ addAccount(username, password, (String[])null);
+ }
+
+ public void addAccount(String username, String password, String... roles) {
+ Set<String> roleNames = CollectionUtils.asSet(roles);
+ SimpleAccount account = new SimpleAuthorizingAccount(username, password, getName(), roleNames, null);
+ add(account);
+ }
+
+ protected void add(SimpleAccount account) {
+ Object key = getAuthorizationCacheKey(account.getPrincipals());
+ getAuthorizationCache().put(key, account);
+ }
+
+ protected SimpleRole getRole(String rolename) {
+ return roles.get(rolename);
+ }
+
+ public boolean roleExists(String name) {
+ return getRole(name) != null;
+ }
+
+ public void addRole(String name) {
+ add(new SimpleRole(name));
+ }
+
+ protected void add(SimpleRole role) {
+ roles.put(role.getName(), role);
+ }
+
+ protected static Set<String> toSet(String delimited, String delimiter) {
+ if (delimited == null || delimited.trim().equals("")) {
+ return null;
+ }
+
+ Set<String> values = new HashSet<String>();
+ String[] rolenamesArray = delimited.split(delimiter);
+ for (String s : rolenamesArray) {
+ String trimmed = s.trim();
+ if (trimmed.length() > 0) {
+ values.add(trimmed);
+ }
+ }
+
+ return values;
+ }
+
+ protected void accountAndRoleCachesCreated() {
+ }
+
+ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
+ UsernamePasswordToken upToken = (UsernamePasswordToken) token;
+ SimpleAccount account = (SimpleAccount) getAuthorizationCache().get(upToken.getUsername());
+
+ if (account.isLocked()) {
+ throw new LockedAccountException("Account [" + account + "] is locked.");
+ }
+ if (account.isCredentialsExpired()) {
+ String msg = "The credentials for account [" + account + "] are expired";
+ throw new ExpiredCredentialsException(msg);
+ }
+
+ return account;
+ }
+
+ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
+ return (Account) getAuthorizationCache().get(getAuthorizationCacheKey(principals));
+ }
+
+ protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
+ return principals.fromRealm(getName()).iterator().next(); //returns the username
+ }
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/realm/activedirectory/ActiveDirectoryRealm.java b/core/src/org/jsecurity/realm/activedirectory/ActiveDirectoryRealm.java
new file mode 100644
index 0000000..89d3c7d
--- /dev/null
+++ b/core/src/org/jsecurity/realm/activedirectory/ActiveDirectoryRealm.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.realm.activedirectory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.SimpleAuthenticationInfo;
+import org.jsecurity.authc.UsernamePasswordToken;
+import org.jsecurity.authz.AuthorizationInfo;
+import org.jsecurity.authz.SimpleAuthorizationInfo;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.realm.ldap.AbstractLdapRealm;
+import org.jsecurity.realm.ldap.LdapContextFactory;
+import org.jsecurity.realm.ldap.LdapUtils;
+import org.jsecurity.subject.PrincipalCollection;
+
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.LdapContext;
+import java.util.*;
+
+/**
+ * <p>An {@link Realm} that authenticates with an active directory LDAP
+ * server to determine the roles for a particular user. This implementation
+ * queries for the user's groups and then maps the group names to roles using the
+ * {@link #groupRolesMap}.</p>
+ *
+ * @author Tim Veil
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public class ActiveDirectoryRealm extends AbstractLdapRealm {
+
+ //TODO - complete JavaDoc
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+
+ private static final Log log = LogFactory.getLog(ActiveDirectoryRealm.class);
+
+ private static final String ROLE_NAMES_DELIMETER = ",";
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+
+ /**
+ * Mapping from fully qualified active directory
+ * group names (e.g. CN=Group,OU=Company,DC=MyDomain,DC=local)
+ * as returned by the active directory LDAP server to role names.
+ */
+ private Map<String, String> groupRolesMap;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+
+ public void setGroupRolesMap(Map<String, String> groupRolesMap) {
+ this.groupRolesMap = groupRolesMap;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+
+
+ /**
+ * <p>Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the
+ * specified username. This method binds to the LDAP server using the provided username and password -
+ * which if successful, indicates that the password is correct.</p>
+ *
+ * <p>This method can be overridden by subclasses to query the LDAP server in a more complex way.</p>
+ *
+ * @param token the authentication token provided by the user.
+ * @param ldapContextFactory the factory used to build connections to the LDAP server.
+ * @return an {@link AuthenticationInfo} instance containing information retrieved from LDAP.
+ * @throws NamingException if any LDAP errors occur during the search.
+ */
+ protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
+
+ UsernamePasswordToken upToken = (UsernamePasswordToken) token;
+
+ // Binds using the username and password provided by the user.
+ LdapContext ctx = null;
+ try {
+ ctx = ldapContextFactory.getLdapContext(upToken.getUsername(), String.valueOf(upToken.getPassword()));
+ } finally {
+ LdapUtils.closeContext(ctx);
+ }
+
+ return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
+ }
+
+ protected AuthenticationInfo buildAuthenticationInfo(String username, char[] password) {
+ return new SimpleAuthenticationInfo(username, password, getName());
+ }
+
+
+ /**
+ * <p>Builds an {@link AuthorizationInfo} object by querying the active directory LDAP context for the
+ * groups that a user is a member of. The groups are then translated to role names by using the
+ * configured {@link #groupRolesMap}.</p>
+ *
+ * <p>This implementation expects the <tt>principal</tt> argument to be a String username.
+ *
+ * <p>Subclasses can override this method to determine authorization data (roles, permissions, etc) in a more
+ * complex way. Note that this default implementation does not support permissions, only roles.</p>
+ *
+ * @param principals the principal of the Subject whose account is being retrieved.
+ * @param ldapContextFactory the factory used to create LDAP connections.
+ * @return the AuthorizationInfo for the given Subject principal.
+ * @throws NamingException if an error occurs when searching the LDAP server.
+ */
+ protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException {
+
+ String username;
+
+
+ username = (String) principals.fromRealm(getName()).iterator().next();
+
+ // Perform context search
+ LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
+
+ Set<String> roleNames;
+
+ try {
+ roleNames = getRoleNamesForUser(username, ldapContext);
+ } finally {
+ LdapUtils.closeContext(ldapContext);
+ }
+
+ return buildAuthorizationInfo(roleNames);
+ }
+
+ protected AuthorizationInfo buildAuthorizationInfo(Set<String> roleNames) {
+ return new SimpleAuthorizationInfo(roleNames);
+ }
+
+ private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
+ Set<String> roleNames;
+ roleNames = new LinkedHashSet<String>();
+
+ SearchControls searchCtls = new SearchControls();
+ searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
+
+ String userPrincipalName = username;
+ if( principalSuffix != null ) {
+ userPrincipalName += principalSuffix;
+ }
+
+ String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
+
+ NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchCtls);
+
+ while (answer.hasMoreElements()) {
+ SearchResult sr = (SearchResult) answer.next();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Retrieving group names for user [" + sr.getName() + "]");
+ }
+
+ Attributes attrs = sr.getAttributes();
+
+ if (attrs != null) {
+ NamingEnumeration ae = attrs.getAll();
+ while (ae.hasMore()) {
+ Attribute attr = (Attribute) ae.next();
+
+ if (attr.getID().equals("memberOf")) {
+
+ Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Groups found for user [" + username + "]: " + groupNames);
+ }
+
+ Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
+ roleNames.addAll(rolesForGroups);
+ }
+ }
+ }
+ }
+ return roleNames;
+ }
+
+ /**
+ * This method is called by the default implementation to translate Active Directory group names
+ * to role names. This implementation uses the {@link #groupRolesMap} to map group names to role names.
+ *
+ * @param groupNames the group names that apply to the current user.
+ * @return a collection of roles that are implied by the given role names.
+ */
+ protected Collection<String> getRoleNamesForGroups(Collection<String> groupNames) {
+ Set<String> roleNames = new HashSet<String>(groupNames.size());
+
+ if (groupRolesMap != null) {
+ for (String groupName : groupNames) {
+ String strRoleNames = groupRolesMap.get(groupName);
+ if (strRoleNames != null) {
+ for (String roleName : strRoleNames.split(ROLE_NAMES_DELIMETER)) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("User is member of group [" + groupName + "] so adding role [" + roleName + "]");
+ }
+
+ roleNames.add(roleName);
+
+ }
+ }
+ }
+ }
+ return roleNames;
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/realm/ldap/AbstractLdapRealm.java b/core/src/org/jsecurity/realm/ldap/AbstractLdapRealm.java
new file mode 100644
index 0000000..d615294
--- /dev/null
+++ b/core/src/org/jsecurity/realm/ldap/AbstractLdapRealm.java
@@ -0,0 +1,240 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.realm.ldap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authz.AuthorizationInfo;
+import org.jsecurity.realm.AuthorizingRealm;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.subject.PrincipalCollection;
+
+import javax.naming.NamingException;
+
+/**
+ * <p>A {@link Realm} that authenticates with an LDAP
+ * server to build the Subject for a user. This implementation only returns roles for a
+ * particular user, and not permissions - but it can be subclassed to build a permission
+ * list as well.</p>
+ *
+ * <p>Implementations would need to implement the
+ * {@link #queryForAuthenticationInfo(org.jsecurity.authc.AuthenticationToken,LdapContextFactory)} and
+ * {@link #queryForAuthorizationInfo(PrincipalCollection,LdapContextFactory)} abstract methods.</p>
+ *
+ * <p>By default, this implementation will create an instance of {@link DefaultLdapContextFactory} to use for
+ * creating LDAP connections using the principalSuffix, searchBase, url, systemUsername, and systemPassword properties
+ * specified on the realm. The remaining settings use the defaults of {@link DefaultLdapContextFactory}, which are usually
+ * sufficient. If more customized connections are needed, you should inject a custom {@link LdapContextFactory}, which
+ * will cause these properties specified on the realm to be ignored.</p>
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see #queryForAuthenticationInfo(org.jsecurity.authc.AuthenticationToken, LdapContextFactory)
+ * @see #queryForAuthorizationInfo(PrincipalCollection, LdapContextFactory)
+ * @since 0.1
+ */
+public abstract class AbstractLdapRealm extends AuthorizingRealm {
+
+ //TODO - complete JavaDoc
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+
+ private static final Log log = LogFactory.getLog(AbstractLdapRealm.class);
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ protected String principalSuffix = null;
+
+ protected String searchBase = null;
+
+ protected String url = null;
+
+ protected String systemUsername = null;
+
+ protected String systemPassword = null;
+
+ private LdapContextFactory ldapContextFactory = null;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+
+
+ /**
+ * Used when initializing the default {@link LdapContextFactory}. This property is ignored if a custom
+ * <tt>LdapContextFactory</tt> is specified.
+ *
+ * @param principalSuffix the suffix.
+ * @see DefaultLdapContextFactory#setPrincipalSuffix(String)
+ */
+ public void setPrincipalSuffix(String principalSuffix) {
+ this.principalSuffix = principalSuffix;
+ }
+
+ /**
+ * Used when initializing the default {@link LdapContextFactory}. This property is ignored if a custom
+ * <tt>LdapContextFactory</tt> is specified.
+ *
+ * @param searchBase the search base.
+ * @see DefaultLdapContextFactory#setSearchBase(String)
+ */
+ public void setSearchBase(String searchBase) {
+ this.searchBase = searchBase;
+ }
+
+ /**
+ * Used when initializing the default {@link LdapContextFactory}. This property is ignored if a custom
+ * <tt>LdapContextFactory</tt> is specified.
+ *
+ * @param url the LDAP url.
+ * @see DefaultLdapContextFactory#setUrl(String)
+ */
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ /**
+ * Used when initializing the default {@link LdapContextFactory}. This property is ignored if a custom
+ * <tt>LdapContextFactory</tt> is specified.
+ *
+ * @param systemUsername the username to use when logging into the LDAP server for authorization.
+ * @see DefaultLdapContextFactory#setSystemUsername(String)
+ */
+ public void setSystemUsername(String systemUsername) {
+ this.systemUsername = systemUsername;
+ }
+
+
+ /**
+ * Used when initializing the default {@link LdapContextFactory}. This property is ignored if a custom
+ * <tt>LdapContextFactory</tt> is specified.
+ *
+ * @param systemPassword the password to use when logging into the LDAP server for authorization.
+ * @see DefaultLdapContextFactory#setSystemPassword(String)
+ */
+ public void setSystemPassword(String systemPassword) {
+ this.systemPassword = systemPassword;
+ }
+
+
+ /**
+ * Configures the {@link LdapContextFactory} implementation that is used to create LDAP connections for
+ * authentication and authorization. If this is set, the {@link LdapContextFactory} provided will be used.
+ * Otherwise, a {@link DefaultLdapContextFactory} instance will be created based on the properties specified
+ * in this realm.
+ *
+ * @param ldapContextFactory the factory to use - if not specified, a default factory will be created automatically.
+ */
+ public void setLdapContextFactory(LdapContextFactory ldapContextFactory) {
+ this.ldapContextFactory = ldapContextFactory;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+
+ protected void afterAuthorizationCacheSet() {
+ if (ldapContextFactory == null) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("No LdapContextFactory is specified, so a default instance is being created.");
+ }
+
+ DefaultLdapContextFactory defaultFactory = new DefaultLdapContextFactory();
+ defaultFactory.setPrincipalSuffix(this.principalSuffix);
+ defaultFactory.setSearchBase(this.searchBase);
+ defaultFactory.setUrl(this.url);
+ defaultFactory.setSystemUsername(this.systemUsername);
+ defaultFactory.setSystemPassword(this.systemPassword);
+
+ ldapContextFactory = defaultFactory;
+ }
+ }
+
+
+ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
+ AuthenticationInfo info = null;
+ try {
+ info = queryForAuthenticationInfo(token, this.ldapContextFactory);
+ } catch (NamingException e) {
+ if (log.isErrorEnabled()) {
+ final String message = "LDAP naming error while attempting to authenticate user.";
+ log.error(message, e);
+ }
+ }
+
+ return info;
+ }
+
+
+ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
+ AuthorizationInfo info = null;
+ try {
+ info = queryForAuthorizationInfo(principals, this.ldapContextFactory);
+ } catch (NamingException e) {
+ if (log.isErrorEnabled()) {
+ final String message = "LDAP naming error while attempting to retrieve authorization for user [" + principals + "].";
+ log.error(message, e);
+ }
+ }
+
+ return info;
+ }
+
+
+ /**
+ * <p>Abstract method that should be implemented by subclasses to builds an
+ * {@link AuthenticationInfo} object by querying the LDAP context for the
+ * specified username.</p>
+ *
+ * @param token the authentication token given during authentication.
+ * @param ldapContextFactory factory used to retrieve LDAP connections.
+ * @return an {@link AuthenticationInfo} instance containing information retrieved from the LDAP server.
+ * @throws NamingException if any LDAP errors occur during the search.
+ */
+ protected abstract AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException;
+
+
+ /**
+ * <p>Abstract method that should be implemented by subclasses to builds an
+ * {@link AuthorizationInfo} object by querying the LDAP context for the
+ * specified principal.</p>
+ *
+ * @param principal the principal of the Subject whose AuthenticationInfo should be queried from the LDAP server.
+ * @param ldapContextFactory factory used to retrieve LDAP connections.
+ * @return an {@link AuthorizationInfo} instance containing information retrieved from the LDAP server.
+ * @throws NamingException if any LDAP errors occur during the search.
+ */
+ protected abstract AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principal, LdapContextFactory ldapContextFactory) throws NamingException;
+
+}
diff --git a/core/src/org/jsecurity/realm/text/PropertiesRealm.java b/core/src/org/jsecurity/realm/text/PropertiesRealm.java
new file mode 100644
index 0000000..64e231a
--- /dev/null
+++ b/core/src/org/jsecurity/realm/text/PropertiesRealm.java
@@ -0,0 +1,366 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.realm.text;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.JSecurityException;
+import org.jsecurity.cache.CacheManager;
+import org.jsecurity.io.ResourceUtils;
+import org.jsecurity.util.Destroyable;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Enumeration;
+import java.util.Properties;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A subclass of <tt>SimpleAccountRealm</tt> that defers all logic to the parent class, but just enables
+ * {@link java.util.Properties Properties} based configuration in addition to the parent class's String configuration.
+ *
+ * <p>This class allows processing of a single .properties file for user, role, and
+ * permission configuration.
+ *
+ * <p>For convenience, if the {@link #setResourcePath resourcePath} attribute is not set, this class defaults to lookup
+ * the properties file definition from <tt>classpath:jsecurity-users.properties</tt> (root of the classpath).
+ * This allows you to use this implementation by simply defining this file at the classpath root, instantiating this
+ * class, and then calling {@link #init init()}.
+ *
+ * <p>Or, you may of course specify any other file path using the <tt>url:</tt>, <tt>file:</tt>, or <tt>classpath:</tt>
+ * prefixes.</p>
+ *
+ * <p>If none of these are specified, and the jsecurity-users.properties is not included at the root of the classpath,
+ * a default failsafe configuration will be used. This is not recommended as it only contains a few simple users and
+ * roles which are probably of little value to production applications.</p>
+ *
+ * <p>The Properties format understood by this implementation must be written as follows:
+ *
+ * <p>Each line's key/value pair represents either a user-to-role(s) mapping <em>or</em> a role-to-permission(s)
+ * mapping.
+ *
+ * <p>The user-to-role(s) lines have this format:</p>
+ *
+ * <p><code><b>user.</b><em>username</em> = <em>password</em>,role1,role2,...</code></p>
+ *
+ * <p>Note that each key is prefixed with the token <tt><b>user.</b></tt> Each value must adhere to the
+ * the {@link #setUserDefinitions(String) setUserDefinitions(String)} JavaDoc.</p>
+ *
+ * <p>The role-to-permission(s) lines have this format:</p>
+ *
+ * <p><code><b>role.</b><em>rolename</em> = <em>permissionDefinition1</em>, <em>permissionDefinition2</em>, ...</code></p>
+ *
+ * <p>where each key is prefixed with the token <tt><b>role.</b></tt> and the value adheres to the format specified in
+ * the {@link #setRoleDefinitions(String) setRoleDefinitions(String)} JavaDoc.
+ *
+ * <p>Here is an example of a very simple properties definition that conforms to the above format rules and corresponding
+ * method JavaDocs:
+ *
+ * <code>user.root = <em>rootPassword</em>,administrator<br/>
+ * user.jsmith = <em>jsmithPassword</em>,manager,engineer,employee<br/>
+ * user.abrown = <em>abrownPassword</em>,qa,employee<br/>
+ * user.djones = <em>djonesPassword</em>,qa,contractor<br/>
+ * <br/>
+ * role.administrator = org.jsecurity.authz.support.AllPermission<br/>
+ * role.manager = com.domain.UserPermission,*,read,write;com.domain.FilePermission,/usr/local/emailManagers.sh,execute<br/>
+ * role.engineer = com.domain.FilePermission,/usr/local/tomcat/bin/startup.sh,read,execute<br/>
+ * role.employee = com.domain.IntranetPermission,useWiki<br/>
+ * role.qa = com.domain.QAServerPermission,*,view,start,shutdown,restart;com.domain.ProductionServerPermission,*,view<br/>
+ * role.contractor = com.domain.IntranetPermission,useTimesheet</code>
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.2
+ */
+public class PropertiesRealm extends TextConfigurationRealm implements Destroyable, Runnable {
+
+ //TODO - complete JavaDoc
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+ private static final int DEFAULT_RELOAD_INTERVAL_SECONDS = 10;
+ private static final String USERNAME_PREFIX = "user.";
+ private static final String ROLENAME_PREFIX = "role.";
+ private static final String DEFAULT_RESOURCE_PATH = "classpath:jsecurity-users.properties";
+ private static final String FAILSAFE_RESOURCE_PATH = "classpath:org/jsecurity/realm/text/default-jsecurity-users.properties";
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ private static final Log log = LogFactory.getLog(PropertiesRealm.class);
+
+ protected ExecutorService scheduler = null;
+ protected boolean useXmlFormat = false;
+ protected String resourcePath = DEFAULT_RESOURCE_PATH;
+ protected long fileLastModified;
+ protected int reloadIntervalSeconds = DEFAULT_RELOAD_INTERVAL_SECONDS;
+
+ public PropertiesRealm() {
+ init();
+ }
+
+ public PropertiesRealm( CacheManager cacheManager ) {
+ if ( cacheManager == null ) {
+ throw new IllegalArgumentException( "cacheManager argument cannot be null." );
+ }
+ setCacheManager(cacheManager);
+ init();
+ }
+
+ public void afterRoleCacheSet() {
+ try {
+ loadProperties();
+ } catch (Exception e) {
+ if (log.isInfoEnabled()) {
+ log.info("Unable to find a jsecurity-users.properties file at location [" + this.resourcePath + "]. " +
+ "Defaulting to JSecurity's failsafe properties file (demo use only).");
+ }
+ this.resourcePath = FAILSAFE_RESOURCE_PATH;
+ loadProperties();
+ }
+ //we can only determine if files have been modified at runtime (not classpath entries or urls), so only
+ //start the thread in this case:
+ if (this.resourcePath.startsWith(ResourceUtils.FILE_PREFIX) && scheduler != null) {
+ startReloadThread();
+ }
+ }
+
+ public void destroy() {
+ try {
+ if (scheduler != null) {
+ scheduler.shutdown();
+ }
+ } catch (Exception e) {
+ if (log.isInfoEnabled()) {
+ log.info("Unable to cleanly shutdown Scheduler. Ignoring (shutting down)...", e);
+ }
+ }
+ }
+
+ protected void startReloadThread() {
+ if (this.reloadIntervalSeconds > 0) {
+ this.scheduler = Executors.newSingleThreadScheduledExecutor();
+ ((ScheduledExecutorService) this.scheduler).scheduleAtFixedRate(this, reloadIntervalSeconds, reloadIntervalSeconds, TimeUnit.SECONDS);
+ }
+ }
+
+ public void run() {
+ try {
+ reloadPropertiesIfNecessary();
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("Error while reloading property files for realm.", e);
+ }
+ }
+ }
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+
+ /**
+ * Determines whether or not the properties XML format should be used. For more information, see
+ * {@link Properties#loadFromXML(java.io.InputStream)}
+ *
+ * @param useXmlFormat true to use XML or false to use the normal format. Defaults to false.
+ */
+ public void setUseXmlFormat(boolean useXmlFormat) {
+ this.useXmlFormat = useXmlFormat;
+ }
+
+ /**
+ * Sets the path of the properties file to load user, role, and permission information from. The properties
+ * file will be loaded using {@link ResourceUtils#getInputStreamForPath(String)} so any convention recongized
+ * by that method is accepted here. For example, to load a file from the classpath use
+ * <tt>classpath:myfile.properties</tt>; to load a file from disk simply specify the full path; to load
+ * a file from a URL use <tt>url:www.mysite.com/myfile.properties</tt>.
+ *
+ * @param resourcePath the path to load the properties file from. This is a required property.
+ */
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * Sets the interval in seconds at which the property file will be checked for changes and reloaded. If this is
+ * set to zero or less, property file reloading will be disabled. If it is set to 1 or greater, then a
+ * separate thread will be created to monitor the propery file for changes and reload the file if it is updated.
+ *
+ * @param reloadIntervalSeconds the interval in seconds at which the property file should be examined for changes.
+ * If set to zero or less, reloading is disabled.
+ */
+ public void setReloadIntervalSeconds(int reloadIntervalSeconds) {
+ this.reloadIntervalSeconds = reloadIntervalSeconds;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+ private void loadProperties() {
+ if (resourcePath == null || resourcePath.length() == 0) {
+ throw new IllegalStateException("The resourcePath property is not set. " +
+ "It must be set prior to this realm being initialized.");
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("Loading user security information from file [" + resourcePath + "]...");
+ }
+
+ Properties properties = loadProperties(resourcePath);
+ createRealmEntitiesFromProperties(properties);
+ }
+
+ private Properties loadProperties(String resourcePath) {
+ Properties props = new Properties();
+
+ InputStream is = null;
+ try {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Opening input stream for path [" + resourcePath + "]...");
+ }
+
+ is = ResourceUtils.getInputStreamForPath(resourcePath);
+ if (useXmlFormat) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Loading properties from path [" + resourcePath + "] in XML format...");
+ }
+
+ props.loadFromXML(is);
+ } else {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Loading properties from path [" + resourcePath + "]...");
+ }
+
+ props.load(is);
+ }
+
+ } catch (IOException e) {
+ throw new JSecurityException("Error reading properties path [" + resourcePath + "]. " +
+ "Initializing of the realm from this file failed.", e);
+ } finally {
+ ResourceUtils.close(is);
+ }
+
+ return props;
+ }
+
+
+ private void reloadPropertiesIfNecessary() {
+ if (isSourceModified()) {
+ restart();
+ }
+ }
+
+ private boolean isSourceModified() {
+ //we can only check last modified times on files - classpath and URL entries can't tell us modification times
+ return this.resourcePath.startsWith(ResourceUtils.FILE_PREFIX) && isFileModified();
+ }
+
+ private boolean isFileModified() {
+ File propertyFile = new File(this.resourcePath);
+ long currentLastModified = propertyFile.lastModified();
+ if (currentLastModified > this.fileLastModified) {
+ this.fileLastModified = currentLastModified;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void restart() {
+ if (resourcePath == null || resourcePath.length() == 0) {
+ throw new IllegalStateException("The resourcePath property is not set. " +
+ "It must be set prior to this realm being initialized.");
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("Loading user security information from file [" + resourcePath + "]...");
+ }
+
+ try {
+ destroy();
+ } catch (Exception e) {
+ //ignored
+ }
+ init();
+ }
+
+ @SuppressWarnings("unchecked")
+ private void createRealmEntitiesFromProperties(Properties properties) {
+
+ StringBuffer userDefs = new StringBuffer();
+ StringBuffer roleDefs = new StringBuffer();
+
+ Enumeration<String> propNames = (Enumeration<String>) properties.propertyNames();
+
+ while (propNames.hasMoreElements()) {
+
+ String key = propNames.nextElement().trim();
+ String value = properties.getProperty(key).trim();
+ if (log.isTraceEnabled()) {
+ log.trace("Processing properties line - key: [" + key + "], value: [" + value + "].");
+ }
+
+ if (isUsername(key)) {
+ String username = getUsername(key);
+ userDefs.append(username).append(" = ").append(value).append("\n");
+ } else if (isRolename(key)) {
+ String rolename = getRolename(key);
+ roleDefs.append(rolename).append(" = ").append(value).append("\n");
+ } else {
+ String msg = "Encountered unexpected key/value pair. All keys must be prefixed with either '" +
+ USERNAME_PREFIX + "' or '" + ROLENAME_PREFIX + "'.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ setUserDefinitions(userDefs.toString());
+ setRoleDefinitions(roleDefs.toString());
+ processDefinitions();
+ }
+
+ protected String getName(String key, String prefix) {
+ return key.substring(prefix.length(), key.length());
+ }
+
+ protected boolean isUsername(String key) {
+ return key != null && key.startsWith(USERNAME_PREFIX);
+ }
+
+ protected boolean isRolename(String key) {
+ return key != null && key.startsWith(ROLENAME_PREFIX);
+ }
+
+ protected String getUsername(String key) {
+ return getName(key, USERNAME_PREFIX);
+ }
+
+ protected String getRolename(String key) {
+ return getName(key, ROLENAME_PREFIX);
+ }
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/realm/text/TextConfigurationRealm.java b/core/src/org/jsecurity/realm/text/TextConfigurationRealm.java
new file mode 100644
index 0000000..5762897
--- /dev/null
+++ b/core/src/org/jsecurity/realm/text/TextConfigurationRealm.java
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.realm.text;
+
+import org.jsecurity.authc.SimpleAccount;
+import org.jsecurity.authz.Permission;
+import org.jsecurity.authz.SimpleRole;
+import org.jsecurity.realm.SimpleAccountRealm;
+import org.jsecurity.subject.PrincipalCollection;
+import org.jsecurity.util.PermissionUtils;
+import org.jsecurity.util.StringUtils;
+
+import java.text.ParseException;
+import java.util.*;
+
+/**
+ * <p>a SimpleAccountRealm that enables text-based configuration of the initial User, Role, and Permission objects
+ * created at startup.
+ *
+ * <p>Each User account definition specifies the username, password, and roles for a user. Each Role definition
+ * specifies a name and an optional collection of assigned Permissions. Users can be assigned Roles, and Roles can be
+ * assigned Permissions. By transitive association, each User 'has' all of their Role's Permissions.</p>
+ *
+ * <p>User and user-to-role definitinos are specified via the {@link #setUserDefinitions} method and
+ * Role-to-permission definitions are specified via the {@link #setRoleDefinitions} method.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class TextConfigurationRealm extends SimpleAccountRealm {
+
+ //TODO - complete JavaDoc
+
+ private String userDefinitions;
+ private String roleDefinitions;
+
+ public TextConfigurationRealm() {
+ }
+
+ public String getUserDefinitions() {
+ return userDefinitions;
+ }
+
+ /**
+ * <p>Sets a newline (\n) delimited String that defines user-to-password-and-role(s) key/value pairs according
+ * to the following format:
+ *
+ * <p><code><em>username</em> = <em>password</em>, role1, role2,...</code></p>
+ *
+ * <p>Here are some examples of what these lines might look like:</p>
+ *
+ * <p><code>root = <em>reallyHardToGuessPassword</em>, administrator<br/>
+ * jsmith = <em>jsmithsPassword</em>, manager, engineer, employee<br/>
+ * abrown = <em>abrownsPassword</em>, qa, employee<br/>
+ * djones = <em>djonesPassword</em>, qa, contractor<br/>
+ * guest = <em>guestPassword</em></code></p>
+ *
+ * @param userDefinitions the user definitions to be parsed and converted to Map.Entry elements
+ */
+ public void setUserDefinitions(String userDefinitions) {
+ this.userDefinitions = userDefinitions;
+ }
+
+ public String getRoleDefinitions() {
+ return roleDefinitions;
+ }
+
+ /**
+ * Sets a newline (\n) delimited String that defines role-to-permission definitions.
+ *
+ * <p>Each line within the string must define a role-to-permission(s) key/value mapping with the
+ * equals character signifies the key/value separation, like so:</p>
+ *
+ * <p><code><em>rolename</em> = <em>permissionDefinition1</em>, <em>permissionDefinition2</em>, ...</code></p>
+ *
+ * <p>where <em>permissionDefinition</em> is an arbitrary String, but must people will want to use
+ * Strings that conform to the {@link org.jsecurity.authz.permission.WildcardPermission WildcardPermission}
+ * format for ease of use and flexibility. Note that if an individual <em>permissionDefnition</em> needs to
+ * be internally comma-delimited (e.g. <code>printer:5thFloor:print,info</code>), you will need to surround that
+ * definition with double quotes (") to avoid parsing errors (e.g.
+ * <code>"printer:5thFloor:print,info"</code>).
+ *
+ * <p><b>NOTE:</b> if you have roles that don't require permission associations, don't include them in this
+ * definition - just defining the role name in the {@link #setUserDefinitions(String) userDefinitions} is
+ * enough to create the role if it does not yet exist. This property is really only for configuring realms that
+ * have one or more assigned Permission.
+ *
+ * @param roleDefinitions the role definitions to be parsed at initialization
+ */
+ public void setRoleDefinitions(String roleDefinitions) {
+ this.roleDefinitions = roleDefinitions;
+ }
+
+ protected void accountAndRoleCachesCreated() {
+ processDefinitions();
+ }
+
+ protected void processDefinitions() {
+ try {
+ processRoleDefinitions();
+ processUserDefinitions();
+ } catch (ParseException e) {
+ String msg = "Unable to parse user and/or role definitions.";
+ throw new IllegalStateException(msg, e);
+ }
+ }
+
+ protected void processRoleDefinitions() throws ParseException {
+ String roleDefinitions = getRoleDefinitions();
+ if (roleDefinitions == null) {
+ return;
+ }
+ Map<String, String> roleDefs = toMap(toLines(roleDefinitions));
+ if (roleDefs == null || roleDefs.isEmpty()) {
+ return;
+ }
+
+ for (String rolename : roleDefs.keySet()) {
+ String value = roleDefs.get(rolename);
+
+ SimpleRole role = getRole(rolename);
+ if (role == null) {
+ role = new SimpleRole(rolename);
+ add(role);
+ }
+
+ Set<Permission> permissions = PermissionUtils.resolveDelimitedPermissions(value, getPermissionResolver());
+ role.setPermissions(permissions);
+ }
+ }
+
+ protected void processUserDefinitions() throws ParseException {
+
+ String userDefinitions = getUserDefinitions();
+ if (userDefinitions == null) {
+ return;
+ }
+
+ Map<String, String> userDefs = toMap(toLines(userDefinitions));
+ if (userDefs == null || userDefs.isEmpty()) {
+ return;
+ }
+
+ for (String username : userDefs.keySet()) {
+
+ String value = userDefs.get(username);
+
+ String[] passwordAndRolesArray = StringUtils.split(value);
+
+ String password = passwordAndRolesArray[0];
+
+ SimpleAccount account = getUser(username);
+ if (account == null) {
+ account = new SimpleAccount(username, password, getName());
+ add(account);
+ }
+ account.setCredentials(password);
+
+ if (passwordAndRolesArray.length > 1) {
+ for (int i = 1; i < passwordAndRolesArray.length; i++) {
+ String rolename = passwordAndRolesArray[i];
+ account.addRole(rolename);
+
+ SimpleRole role = getRole(rolename);
+ if (role != null) {
+ account.addObjectPermissions(role.getPermissions());
+ }
+ }
+ } else {
+ account.setRoles(null);
+ }
+ }
+ }
+
+ protected static Set<String> toLines(String s) {
+ LinkedHashSet<String> set = new LinkedHashSet<String>();
+ Scanner scanner = new Scanner(s);
+ while (scanner.hasNextLine()) {
+ set.add(scanner.nextLine());
+ }
+ return set;
+ }
+
+ protected static Map<String, String> toMap(Collection<String> keyValuePairs) throws ParseException {
+ if (keyValuePairs == null || keyValuePairs.isEmpty()) {
+ return null;
+ }
+
+ Map<String, String> pairs = new HashMap<String, String>();
+ for (String pairString : keyValuePairs) {
+ String[] pair = StringUtils.splitKeyValue(pairString);
+ pairs.put(pair[0].trim(), pair[1].trim());
+ }
+
+ return pairs;
+ }
+
+ public void onLogout(PrincipalCollection accountPrincipal) {
+ //override parent method of removing user from cache
+ //we don't want that to happen on cache-only realm since that would permanently
+ //remove the user from the realm.
+ }
+}
diff --git a/core/src/org/jsecurity/realm/text/default-jsecurity-users.properties b/core/src/org/jsecurity/realm/text/default-jsecurity-users.properties
new file mode 100644
index 0000000..b4379e5
--- /dev/null
+++ b/core/src/org/jsecurity/realm/text/default-jsecurity-users.properties
@@ -0,0 +1,62 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# ============================================================================
+# Failsafe properties-based Realm configuration
+#
+# A Properties-based configuration is static by nature, which means its user,
+# role, and permission definitions contained within do not change during
+# runtime. This means you can't add or remove any of them during runtime
+# which is probably of little value to a 'real' application.
+#
+# This file primarily exists as a failsafe mechanism in case you don't provide
+# any Realms to the JSecurity SecurityManager at startup. It also serves as a
+# simple and fun example. But you will want to provide one or more of your
+# own Realms in a real application.
+#
+# The key/value pairs format is defined in the
+# org.jsecurity.realm.text.PropertiesRealm JavaDoc, but it is probably simple
+# enough that you could figure it out from looking at the definitions below.
+#
+# For those that might not understand the references in this file, the
+# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
+# ============================================================================
+
+# ------------------------------
+# Users and their assigned roles
+# ------------------------------
+# user 'root' with password 'secret' and the 'root' role
+user.root = secret,root
+# user 'guest' with the password 'guest' and the 'guest' role
+user.guest = guest,guest
+# user 'presidentskroob' with password '12345' ("That's the same combination on my luggage!!!" ;)), and role 'president'
+user.presidentskroob = 12345,president
+# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
+user.darkhelmet = ludicrousspeed,darklord,schwartz
+# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
+user.lonestarr = vespa,goodguy,schwartz
+
+# -------------------------------
+# Roles with assigned permissions
+# -------------------------------
+# 'root' role has all permissions, indicated by the wildcard '*'
+role.root = *
+# The 'schwartz' role can do anything (*) with any lightsaber:
+role.schwartz = lightsaber:*
+# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with license plate 'eagle5' (instance specific id)
+role.goodguy = winnebago:drive:eagle5
\ No newline at end of file
diff --git a/core/src/org/jsecurity/session/ExpiredSessionException.java b/core/src/org/jsecurity/session/ExpiredSessionException.java
new file mode 100644
index 0000000..057ff4b
--- /dev/null
+++ b/core/src/org/jsecurity/session/ExpiredSessionException.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.io.Serializable;
+
+/**
+ * A special case of a StoppedSessionException. An expired session is a session that has
+ * stopped explicitly due to inactivity (i.e. time-out), as opposed to stopping due to log-out or
+ * other reason.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class ExpiredSessionException extends StoppedSessionException {
+
+ /**
+ * Creates a new ExpiredSessionException.
+ */
+ public ExpiredSessionException() {
+ super();
+ }
+
+ /**
+ * Constructs a new ExpiredSessionException.
+ *
+ * @param message the reason for the exception
+ */
+ public ExpiredSessionException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new ExpiredSessionException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ExpiredSessionException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new ExpiredSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public ExpiredSessionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new ExpiredSessionException.
+ *
+ * @param sessionId the session id of the session that expired.
+ */
+ public ExpiredSessionException(Serializable sessionId) {
+ this("Session with id [" + sessionId + "] has expired", sessionId);
+ }
+
+ /**
+ * Constructs a new ExpiredSessionException.
+ *
+ * @param message the reason for the exception
+ * @param sessionId the session id of the session that expired.
+ */
+ public ExpiredSessionException(String message, Serializable sessionId) {
+ super(message, sessionId);
+ }
+
+ /**
+ * Constructs a new ExpiredSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ * @param sessionId the session id of the session that expired.
+ */
+ public ExpiredSessionException(String message, Throwable cause, Serializable sessionId) {
+ super(message, cause, sessionId);
+ }
+}
diff --git a/core/src/org/jsecurity/session/InvalidSessionException.java b/core/src/org/jsecurity/session/InvalidSessionException.java
new file mode 100644
index 0000000..53a7ec1
--- /dev/null
+++ b/core/src/org/jsecurity/session/InvalidSessionException.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.io.Serializable;
+
+/**
+ * Exception thrown when attempting to interact with the system under an established session
+ * when that session is considered invalid. The meaning of the term 'invalid' is based on
+ * application behavior. For example, a Session is considered invalid if it has been explicitly
+ * stopped (e.g. when a user logs-out or when explicitly
+ * {@link org.jsecurity.session.Session#stop() stopped} programmatically. A Session can also be
+ * considered invalid if it has expired.
+ *
+ * @author Les Hazlewood
+ * @see StoppedSessionException
+ * @see ExpiredSessionException
+ * @see UnknownSessionException
+ * @since 0.1
+ */
+public class InvalidSessionException extends SessionException {
+
+ /**
+ * Creates a new InvalidSessionException.
+ */
+ public InvalidSessionException() {
+ super();
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param message the reason for the exception
+ */
+ public InvalidSessionException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public InvalidSessionException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public InvalidSessionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param sessionId the session id of the session that has been invalidated.
+ */
+ public InvalidSessionException(Serializable sessionId) {
+ this("Session with id [" + sessionId + "] has been invalidated (stopped)", sessionId);
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param message the reason for the exception
+ * @param sessionId the session id of the session that has been invalidated.
+ */
+ public InvalidSessionException(String message, Serializable sessionId) {
+ super(message, sessionId);
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ * @param sessionId the session id of the session that has been invalidated.
+ */
+ public InvalidSessionException(String message, Throwable cause, Serializable sessionId) {
+ super(message, cause, sessionId);
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/ProxiedSession.java b/core/src/org/jsecurity/session/ProxiedSession.java
new file mode 100644
index 0000000..c3b6b77
--- /dev/null
+++ b/core/src/org/jsecurity/session/ProxiedSession.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * Simple <code>Session</code> implementation that immediately delegates all corresponding calls to an
+ * underlying proxied session instance.
+ * <p/>
+ * This class is mostly useful for framework subclassing to intercept certain <code>Session</code> calls
+ * and perform additional logic.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class ProxiedSession implements Session {
+
+ /**
+ * The proxied instance
+ */
+ protected final Session proxy;
+
+ /**
+ * Constructs an instance that proxies the specified <code>target</code>. Subclasses may access this
+ * target via the <code>protected final 'proxy'</code> attribute, i.e. <code>this.proxy</code>.
+ *
+ * @param target the specified target <code>Session</code> to proxy.
+ */
+ public ProxiedSession(Session target) {
+ if (target == null) {
+ throw new IllegalArgumentException("Target session to proxy cannot be null.");
+ }
+ proxy = target;
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public Serializable getId() {
+ return proxy.getId();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public Date getStartTimestamp() {
+ return proxy.getStartTimestamp();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public Date getLastAccessTime() {
+ return proxy.getLastAccessTime();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public long getTimeout() throws InvalidSessionException {
+ return proxy.getTimeout();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException {
+ proxy.setTimeout(maxIdleTimeInMillis);
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public InetAddress getHostAddress() {
+ return proxy.getHostAddress();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public void touch() throws InvalidSessionException {
+ proxy.touch();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public void stop() throws InvalidSessionException {
+ proxy.stop();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public Collection<Object> getAttributeKeys() throws InvalidSessionException {
+ return proxy.getAttributeKeys();
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public Object getAttribute(Object key) throws InvalidSessionException {
+ return proxy.getAttribute(key);
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public void setAttribute(Object key, Object value) throws InvalidSessionException {
+ proxy.setAttribute(key, value);
+ }
+
+ /**
+ * Immediately delegates to the underlying proxied session.
+ */
+ public Object removeAttribute(Object key) throws InvalidSessionException {
+ return proxy.removeAttribute(key);
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/Session.java b/core/src/org/jsecurity/session/Session.java
new file mode 100644
index 0000000..efde797
--- /dev/null
+++ b/core/src/org/jsecurity/session/Session.java
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * A <tt>Session</tt> is a stateful data context associated with a single Subject (user, 3rd party process,
+ * etc) who interacts with a software system over a period of time.
+ *
+ * <p>A <tt>Session</tt> is intended to be managed by the business tier and accessible via other
+ * tiers without being tied to any given client technology. This is a <em>great</em> benefit to Java
+ * systems, since until now, the only viable session mechanisms were the
+ * {@link javax.servlet.http.HttpSession HttpSession} or Stateful Session EJB's, which many times
+ * unnecessarily coupled applications to web or ejb technologies.
+ *
+ * <p>See the {@link SessionFactory#getSession(java.io.Serializable) SessionFactory.getSession(Serializable)}
+ * JavaDoc for more on the benefits of a POJO-based <tt>Session</tt> framework.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public interface Session {
+
+ /**
+ * Returns the unique identifier assigned by the system upon session creation.
+ *
+ * <p>All return values from this method are expected to have proper <code>toString()</code>,
+ * <code>equals()</code>, and <code>hashCode()</code> implementations. Good candiadates for such
+ * an identifier are {@link java.util.UUID UUID}s, {@link java.lang.Integer Integer}s, and
+ * {@link java.lang.String String}s.
+ *
+ * @return The unique identifier assigned to the session upon creation.
+ */
+ Serializable getId();
+
+ /**
+ * Returns the time the session was started; that is, the time the system created the instance.
+ *
+ * @return The time the system created the session.
+ */
+ Date getStartTimestamp();
+
+ /**
+ * Returns the last time the user associated with the session interacted with the system.
+ *
+ * @return The time the user last interacted with the system.
+ * @see #touch()
+ */
+ Date getLastAccessTime();
+
+ /**
+ * Returns the time in milliseconds that the session session may remain idle before expiring.
+ *
+ * <ul>
+ * <li>A negative return value means the session will never expire.</li>
+ * <li>A non-negative return value (0 or greater) means the session expiration will occur if idle for that
+ * length of time.</li>
+ * </ul>
+ *
+ * @return the time in milliseconds the session may remain idle before expiring.
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if the session has been stopped or expired prior to calling this method.
+ * @since 0.2
+ */
+ long getTimeout() throws InvalidSessionException;
+
+ /**
+ * Sets the time in milliseconds that the session may remain idle before expiring.
+ *
+ * <ul>
+ * <li>A negative return value means the session will never expire.</li>
+ * <li>A non-negative return value (0 or greater) means the session expiration will occur if idle for that
+ * length of time.</li>
+ * </ul>
+ *
+ * @param maxIdleTimeInMillis the time in milliseconds that the session may remain idle before expiring.
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if the session has been stopped or expired prior to calling this method.
+ * @since 0.2
+ */
+ void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException;
+
+
+ /**
+ * Returns the <tt>InetAddress</tt> of the host that originated this session, or <tt>null</tt>
+ * if the host address is unknown.
+ *
+ * @return the <tt>InetAddress</tt> of the host that originated this session, or <tt>null</tt>
+ * if the host address is unknown.
+ * @see SessionFactory#start(java.net.InetAddress)
+ */
+ InetAddress getHostAddress();
+
+ /**
+ * Explicitly updates the {@link #getLastAccessTime() lastAccessTime} of this session. This
+ * method can be used to ensure a session does not time out.
+ *
+ * <p>Most programmers won't use this method explicitly and will instead rely calling the other Session methods
+ * to update the time transparently, or on a framework during a remote procedure call or upon a web request.
+ *
+ * <p>This method is particularly useful however when supporting rich-client applications such as
+ * Java Web Start appp, Java or Flash applets, etc. Although rare, it is possible in a rich-client
+ * environment that a user continuously interacts with the client-side application without a
+ * server-side method call ever being invoked. If this happens over a long enough period of
+ * time, the user's server-side session could time-out. Again, such cases are rare since most
+ * rich-clients frequently require server-side method invocations.
+ *
+ * <p>In this example though, the user's session might still be considered valid because
+ * the user is actively "using" the application, just not communicating with the
+ * server. But because no server-side method calls are invoked, there is no way for the server
+ * to know if the user is sitting idle or not, so it must assume so to maintain session
+ * integrity. The touch method could be invoked by the rich-client application code during those
+ * times to ensure that the next time a server-side method is invoked, the invocation will not
+ * throw an {@link ExpiredSessionException ExpiredSessionException}. In short terms, it could be used periodically
+ * to ensure a session does not time out.
+ *
+ * <p>How often this rich-client "maintenance" might occur is entirely dependent upon
+ * the application and would be based on variables such as session timeout configuration,
+ * usage characteristics of the client application, network utilization and application server
+ * performance.
+ *
+ * @throws InvalidSessionException if this session has stopped or expired prior to calling
+ * this method.
+ */
+ void touch() throws InvalidSessionException;
+
+ /**
+ * Explicitly stops (invalidates) this session and releases all associated resources.
+ *
+ * <p>If this session has already been authenticated (i.e. the <code>Subject</code> that
+ * owns this session has logged-in), calling this method explicitly might have undesired side effects:
+ * <p/>
+ * It is common for a <code>Subject</code> implementation to retain authentication state in the
+ * <code>Session</code>. If the session
+ * is explicitly stopped by application code by calling this method directly, it could clear out any
+ * authentication state that might exist, thereby effectively "unauthenticating" the <code>Subject</code>.
+ * <p/>
+ * As such, you might consider {@link org.jsecurity.subject.Subject#logout logging-out} the 'owning'
+ * <code>Subject</code> instead of manually calling this method, as a log out is expected to stop the
+ * corresponding session automatically, and also allows framework code to execute additional cleanup logic.
+ *
+ * @throws InvalidSessionException if this session has stopped or expired prior to calling this method.
+ */
+ void stop() throws InvalidSessionException;
+
+ /**
+ * Returns the keys of all the attributes stored under this session. If there are no
+ * attributes, this returns an empty collection.
+ *
+ * @return the keys of all attributes stored under this session, or an empty collection if
+ * there are no session attributes.
+ * @throws InvalidSessionException if this session has stopped or expired prior to calling this method.
+ * @since 0.2
+ */
+ Collection<Object> getAttributeKeys() throws InvalidSessionException;
+
+ /**
+ * Returns the object bound to this session identified by the specified key. If there is no
+ * object bound under the key, <tt>null</tt> is returned.
+ *
+ * @param key the unique name of the object bound to this session
+ * @return the object bound under the specified <tt>key</tt> name or <tt>null</tt> if there is
+ * no object bound under that name.
+ * @throws InvalidSessionException if this session has stopped or expired prior to calling
+ * this method.
+ */
+ Object getAttribute(Object key) throws InvalidSessionException;
+
+ /**
+ * Binds the specified <tt>value</tt> to this session, uniquely identified by the specifed
+ * <tt>key</tt> name. If there is already an object bound under the <tt>key</tt> name, that
+ * existing object will be replaced by the new <tt>value</tt>.
+ *
+ * <p>If the <tt>value</tt> parameter is null, it has the same effect as if
+ * <tt>removeAttribute(key)</tt> was called.
+ *
+ * @param key the name under which the <tt>value</tt> object will be bound in this session
+ * @param value the object to bind in this session.
+ * @throws InvalidSessionException if this session has stopped or expired prior to calling
+ * this method.
+ */
+ void setAttribute(Object key, Object value) throws InvalidSessionException;
+
+ /**
+ * Removes (unbinds) the object bound to this session under the specified <tt>key</tt> name.
+ *
+ * @param key the name uniquely identifying the object to remove
+ * @return the object removed or <tt>null</tt> if there was no object bound under the name
+ * <tt>key</tt>.
+ * @throws InvalidSessionException if this session has stopped or expired prior to calling
+ * this method.
+ */
+ Object removeAttribute(Object key) throws InvalidSessionException;
+}
diff --git a/core/src/org/jsecurity/session/SessionException.java b/core/src/org/jsecurity/session/SessionException.java
new file mode 100644
index 0000000..f54fb37
--- /dev/null
+++ b/core/src/org/jsecurity/session/SessionException.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import org.jsecurity.JSecurityException;
+
+import java.io.Serializable;
+
+/**
+ * General security exception attributed to problems during interaction with the system during
+ * a session.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class SessionException extends JSecurityException {
+
+ private Serializable sessionId;
+
+ /**
+ * Creates a new SessionException.
+ */
+ public SessionException() {
+ super();
+ }
+
+ /**
+ * Constructs a new SessionException.
+ *
+ * @param message the reason for the exception
+ */
+ public SessionException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new SessionException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public SessionException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new SessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public SessionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new SessionException.
+ *
+ * @param sessionId the session id of associated {@link Session Session}.
+ */
+ public SessionException(Serializable sessionId) {
+ setSessionId(sessionId);
+ }
+
+ /**
+ * Constructs a new SessionException.
+ *
+ * @param message the reason for the exception
+ * @param sessionId the session id of associated {@link Session Session}.
+ */
+ public SessionException(String message, Serializable sessionId) {
+ this(message);
+ setSessionId(sessionId);
+ }
+
+ /**
+ * Constructs a new InvalidSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ * @param sessionId the session id of associated {@link Session Session}.
+ */
+ public SessionException(String message, Throwable cause, Serializable sessionId) {
+ this(message, cause);
+ setSessionId(sessionId);
+ }
+
+ /**
+ * Returns the session id of the associated <tt>Session</tt>.
+ *
+ * @return the session id of the associated <tt>Session</tt>.
+ */
+ public Serializable getSessionId() {
+ return sessionId;
+ }
+
+ /**
+ * Sets the session id of the <tt>Session</tt> associated with this exception.
+ *
+ * @param sessionId the session id of the <tt>Session</tt> associated with this exception.
+ */
+ public void setSessionId(Serializable sessionId) {
+ this.sessionId = sessionId;
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/SessionFactory.java b/core/src/org/jsecurity/session/SessionFactory.java
new file mode 100644
index 0000000..6d74066
--- /dev/null
+++ b/core/src/org/jsecurity/session/SessionFactory.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.HostUnauthorizedException;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+
+/**
+ * A <tt>SessionFactory</tt> is responsible for starting new {@link Session Session}s and
+ * acquiring existing {@link Session Session}s.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public interface SessionFactory {
+
+ /**
+ * Starts a new session within the system for the host with the specified
+ * originating IP address.
+ *
+ * <p>An implementation of this interface may be configured to allow a <tt>null</tt> argument,
+ * thereby indicating the originating IP is either unknown or has been
+ * explicitly omitted by the caller. However, if the implementation is configured to require
+ * a valid <tt>hostAddress</tt> and the argument is <tt>null</tt>, an
+ * {@link IllegalArgumentException IllegalArgumentException} will be thrown.
+ *
+ * <p>In web-based systems, this InetAddress can be inferred from the
+ * {@link javax.servlet.ServletRequest#getRemoteAddr() javax.servlet.ServletRequest.getRemoteAddr()}
+ * method, or in socket-based systems, it can be obtained via inspecting the socket
+ * initiator's host IP.
+ *
+ * <p>Most secure environments <em>should</em> require that a valid, non-<tt>null</tt>
+ * <tt>hostAddress</tt> be specified, since knowing the <tt>hostAddress</tt> allows for more
+ * flexibility when securing a system: by requiring an InetAddress, access control policies
+ * can also ensure access is restricted to specific client <em>locations</em> in
+ * addition to user principals, if so desired.
+ *
+ * <p><b>Caveat</b> - if clients to your system are on a
+ * public network (as would be the case for a public web site), odds are high the clients can be
+ * behind a NAT (Network Address Translation) router or HTTP proxy server. If so, all clients
+ * accessing your system behind that router or proxy will have the same originating IP address.
+ * If your system is configured to allow only one session per IP, then the next request from a
+ * different NAT or proxy client will fail and access will be deny for that client. Just be
+ * aware that ip-based security policies are best utilized in LAN or private WAN environments
+ * when you can be ensure clients will not share IPs or be behind such NAT routers or
+ * proxy servers.
+ *
+ * @param hostAddress the originating host InetAddress of the external party
+ * (user, 3rd party product, etc) that is attempting to interact with the system.
+ * @return a handle to the newly created session.
+ * @throws HostUnauthorizedException if the system access control policy restricts access based
+ * on client location/IP and the specified hostAddress hasn't been enabled.
+ * @throws IllegalArgumentException if the system is configured to require a valid,
+ * non-<tt>null</tt> argument and the specified <tt>hostAddress</tt> is null.
+ */
+ Session start(InetAddress hostAddress) throws HostUnauthorizedException, IllegalArgumentException;
+
+ /**
+ * Acquires a handle to the session identified by the specified <tt>sessionId</tt>.
+ *
+ * <p><b>Although simple, this method finally enables behavior absent in Java for years:</b>
+ *
+ * <p>the
+ * ability to participate in a server-side session across clients of different mediums,
+ * such as web appliations, Java applets, standalone C# clients over XMLRPC and/or SOAP, and
+ * many others. This is a <em>huge</em> benefit in heterogeneous enterprise applications.
+ *
+ * <p>To maintain session integrity across client mediums, the sessionId must be transmitted
+ * to all client mediums securely (e.g. over SSL) to prevent man-in-the-middle attacks. This
+ * is nothing new - all web applications are susceptible to the same problem when transmitting
+ * {@link javax.servlet.http.Cookie Cookie}s or when using URL rewriting. As long as the
+ * <tt>sessionId</tt> is transmitted securely, session integrity can be maintained.
+ *
+ * @param sessionId the id of the session to acquire.
+ * @return a handle to the session identified by <tt>sessionId</tt>
+ * @throws InvalidSessionException if the session identified by <tt>sessionId</tt> has
+ * been stopped, expired, or doesn't exist.
+ * @throws AuthorizationException if the executor of this method is not allowed to acquire
+ * (i.e. join) the session identified by <tt>sessionId</tt>. The reason for the exception
+ * is implementation specific and could be for any number of reasons. A common reason in many
+ * systems would be if one host tried to acquire/join a session that originated on an entirely
+ * different host (although it is not a JSecurity requirement this scenario is disallowed -
+ * its just an example that <em>may</em> throw an Exception in many systems).
+ * @see HostUnauthorizedException
+ */
+ Session getSession(Serializable sessionId) throws InvalidSessionException, AuthorizationException;
+
+}
diff --git a/core/src/org/jsecurity/session/SessionListener.java b/core/src/org/jsecurity/session/SessionListener.java
new file mode 100644
index 0000000..58821f7
--- /dev/null
+++ b/core/src/org/jsecurity/session/SessionListener.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+/**
+ * Interface to be implemented by components that wish to be notified of events that occur during a
+ * {@link Session Session}'s lifecycle.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface SessionListener {
+
+ /**
+ * Notification callback that occurs when the corresponding Session has started.
+ *
+ * @param session the session that has started.
+ */
+ void onStart(Session session);
+
+ /**
+ * Notification callback that occurs when the corresponding Session has stopped.
+ *
+ * @param session the session that has stopped.
+ */
+ void onStop(Session session);
+
+ /**
+ * Notification callback that occurs when the corresponding Session has expired.
+ *
+ * @param session the session that has expired.
+ */
+ void onExpiration(Session session);
+}
diff --git a/core/src/org/jsecurity/session/SessionListenerRegistrar.java b/core/src/org/jsecurity/session/SessionListenerRegistrar.java
new file mode 100644
index 0000000..265350f
--- /dev/null
+++ b/core/src/org/jsecurity/session/SessionListenerRegistrar.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.util.Collection;
+
+/**
+ * A <code>SessionListenerRegistrar</code> is a component that is capable of registering interested
+ * {@link SessionListener SessionListener}s that wish to be notified during
+ * {@link Session Session} lifecycle events.
+ * <p/>
+ * This interface only guarantees that registered listeners will be notified during a <code>Session</code>'s
+ * lifecycle. How that notification occurs is implementation specific (e.g. iteration over a collection of
+ * listeners, JMS, etc.).
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface SessionListenerRegistrar {
+
+ /**
+ * Sets the <code>SessionListener</code>(s) that wish to be notified during <code>Session</code> lifecycles.
+ *
+ * @param listeners one or more <code>SessionListener</code>s that should be notified during
+ * <code>Session</code> lifecycles.
+ */
+ void setSessionListeners(Collection<SessionListener> listeners);
+
+ /**
+ * Registeres a single <code>listener</code> that wishes to be notified during <code>Session</code> lifecycles.
+ * @param listener the single <code>listener</code> that wishes to be notified during <code>Session</code> lifecycles.
+ */
+ void add(SessionListener listener);
+
+ /**
+ * Removes a single <code>listener</code> that no longer wishes to be notified during <code>Session</code> lifecycles.
+ * @param listener the single <code>listener</code> that no longer wishes to be notified during <code>Session</code> lifecycles.
+ * @return <code>true</code> if the listener was removed (i.e. it was previously registered), or <code>false</code>
+ * if the listener was not removed (i.e. it wasn't registered yet, effectively a no-op).
+ */
+ boolean remove(SessionListener listener);
+}
diff --git a/core/src/org/jsecurity/session/StoppedSessionException.java b/core/src/org/jsecurity/session/StoppedSessionException.java
new file mode 100644
index 0000000..9efc807
--- /dev/null
+++ b/core/src/org/jsecurity/session/StoppedSessionException.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.io.Serializable;
+
+/**
+ * Exception thrown when attempting to interact with the system under a session that has been
+ * stopped. A session may be stopped in any number of ways, most commonly due to explicit
+ * stopping (e.g. from logging out), or due to expiration.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class StoppedSessionException extends InvalidSessionException {
+
+ /**
+ * Creates a new StoppedSessionException.
+ */
+ public StoppedSessionException() {
+ super();
+ }
+
+ /**
+ * Constructs a new StoppedSessionException.
+ *
+ * @param message the reason for the exception
+ */
+ public StoppedSessionException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new StoppedSessionException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public StoppedSessionException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new StoppedSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public StoppedSessionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new StoppedSessionException.
+ *
+ * @param sessionId the session id of the session that has been stopped.
+ */
+ public StoppedSessionException(Serializable sessionId) {
+ super(sessionId);
+ }
+
+ /**
+ * Constructs a new StoppedSessionException.
+ *
+ * @param message the reason for the exception
+ * @param sessionId the session id of the session that has been stopped.
+ */
+ public StoppedSessionException(String message, Serializable sessionId) {
+ super(message, sessionId);
+ }
+
+ /**
+ * Constructs a new StoppedSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ * @param sessionId the session id of the session that has been stopped.
+ */
+ public StoppedSessionException(String message, Throwable cause, Serializable sessionId) {
+ super(message, cause, sessionId);
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/UnknownSessionException.java b/core/src/org/jsecurity/session/UnknownSessionException.java
new file mode 100644
index 0000000..66f944f
--- /dev/null
+++ b/core/src/org/jsecurity/session/UnknownSessionException.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session;
+
+import java.io.Serializable;
+
+/**
+ * Exception thrown when attempting to interact with the system under the pretense of a
+ * particular session (e.g. under a specific session id), and that session does not exist in
+ * the system.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class UnknownSessionException extends InvalidSessionException {
+
+ /**
+ * Creates a new UnknownSessionException.
+ */
+ public UnknownSessionException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnknownSessionException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnknownSessionException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnknownSessionException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownSessionException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnknownSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownSessionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new UnknownSessionException.
+ *
+ * @param sessionId the session id given that is unknown to the system.
+ */
+ public UnknownSessionException(Serializable sessionId) {
+ super(sessionId);
+ }
+
+ /**
+ * Constructs a new UnknownSessionException.
+ *
+ * @param message the reason for the exception
+ * @param sessionId the session id given that is unknown to the system.
+ */
+ public UnknownSessionException(String message, Serializable sessionId) {
+ super(message, sessionId);
+ }
+
+ /**
+ * Constructs a new UnknownSessionException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ * @param sessionId the session id given that is unknown to the system.
+ */
+ public UnknownSessionException(String message, Throwable cause, Serializable sessionId) {
+ super(message, cause, sessionId);
+ }
+}
diff --git a/core/src/org/jsecurity/session/mgt/AbstractSessionManager.java b/core/src/org/jsecurity/session/mgt/AbstractSessionManager.java
new file mode 100644
index 0000000..e58dac8
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/AbstractSessionManager.java
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authz.HostUnauthorizedException;
+import org.jsecurity.session.*;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * TODO - complete JavaDoc
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public abstract class AbstractSessionManager implements SessionManager, SessionListenerRegistrar {
+
+ private static final Log log = LogFactory.getLog(AbstractSessionManager.class);
+
+ protected Collection<SessionListener> listeners = new ArrayList<SessionListener>();
+
+ public AbstractSessionManager() {
+ }
+
+ public void setSessionListeners(Collection<SessionListener> listeners) {
+ if (listeners == null) {
+ this.listeners = new ArrayList<SessionListener>();
+ } else {
+ this.listeners = listeners;
+ }
+ }
+
+ public void add(SessionListener listener) {
+ this.listeners.add(listener);
+ }
+
+ public boolean remove(SessionListener listener) {
+ return this.listeners.remove(listener);
+ }
+
+ public Serializable start(InetAddress originatingHost) throws HostUnauthorizedException, IllegalArgumentException {
+ Session session = createSession(originatingHost);
+ notifyStart(session);
+ return session.getId();
+ }
+
+ /**
+ * Returns the session instance to use to pass to registered <code>SessionListener</code>s for notification
+ * that the session has been invalidated (stopped or expired).
+ * <p/>
+ * The default implementation returns an
+ * {@link org.jsecurity.session.mgt.ImmutableProxiedSession ImmutableProxiedSession} instance to ensure
+ * that the specified <code>session</code> argument is not modified by any listeners.
+ *
+ * @param session the <code>Session</code> object being invalidated.
+ * @return the <code>Session</code> instance to use to pass to registered <code>SessionListener</code>s for
+ * notification.
+ */
+ protected Session beforeInvalidNotification(Session session) {
+ return new ImmutableProxiedSession(session);
+ }
+
+ protected void notifyStart(Session session) {
+ for (SessionListener listener : this.listeners) {
+ listener.onStart(session);
+ }
+ }
+
+ protected void notifyStop(Session session) {
+ Session forNotification = beforeInvalidNotification(session);
+ for (SessionListener listener : this.listeners) {
+ listener.onStop(forNotification);
+ }
+ }
+
+ protected void notifyExpiration(Session session) {
+ Session forNotification = beforeInvalidNotification(session);
+ for (SessionListener listener : this.listeners) {
+ listener.onExpiration(forNotification);
+ }
+ }
+
+ public Date getStartTimestamp(Serializable sessionId) {
+ return getSession(sessionId).getStartTimestamp();
+ }
+
+ public Date getLastAccessTime(Serializable sessionId) {
+ return getSession(sessionId).getStartTimestamp();
+ }
+
+ public long getTimeout(Serializable sessionId) throws InvalidSessionException {
+ return getSession(sessionId).getTimeout();
+ }
+
+ public void setTimeout(Serializable sessionId, long maxIdleTimeInMillis) throws InvalidSessionException {
+ Session s = getSession(sessionId);
+ s.setTimeout(maxIdleTimeInMillis);
+ onChange(s);
+ }
+
+ public void touch(Serializable sessionId) throws InvalidSessionException {
+ Session s = getSession(sessionId);
+ s.touch();
+ onChange(s);
+ }
+
+ public InetAddress getHostAddress(Serializable sessionId) {
+ return getSession(sessionId).getHostAddress();
+ }
+
+ public void stop(Serializable sessionId) throws InvalidSessionException {
+ Session session = getSession(sessionId);
+ stop(session);
+ }
+
+ protected void stop(Session session) {
+ if (log.isDebugEnabled()) {
+ log.debug("Stopping session with id [" + session.getId() + "]");
+ }
+ notifyStop(session);
+ session.stop();
+ onStop(session);
+ }
+
+ protected void onStop(Session session) {
+ onChange(session);
+ }
+
+ protected void onExpiration(Session session) {
+ onChange(session);
+ }
+
+ public Collection<Object> getAttributeKeys(Serializable sessionId) {
+ return getSession(sessionId).getAttributeKeys();
+ }
+
+ public Object getAttribute(Serializable sessionId, Object key) throws InvalidSessionException {
+ return getSession(sessionId).getAttribute(key);
+ }
+
+ public void setAttribute(Serializable sessionId, Object key, Object value) throws InvalidSessionException {
+ if (value == null) {
+ removeAttribute(sessionId, key);
+ } else {
+ Session s = getSession(sessionId);
+ s.setAttribute(key, value);
+ onChange(s);
+ }
+ }
+
+ public Object removeAttribute(Serializable sessionId, Object key) throws InvalidSessionException {
+ Session s = getSession(sessionId);
+ Object removed = s.removeAttribute(key);
+ if (removed != null) {
+ onChange(s);
+ }
+ return removed;
+ }
+
+ protected Session getSession(Serializable sessionId) throws InvalidSessionException {
+ Session session = doGetSession(sessionId);
+ if (session == null) {
+ String msg = "There is no session with id [" + sessionId + "]";
+ throw new UnknownSessionException(msg);
+ }
+ return session;
+ }
+
+ public boolean isValid(Serializable sessionId) {
+ try {
+ getSession(sessionId);
+ } catch (InvalidSessionException e) {
+ return false;
+ }
+ return true;
+ }
+
+ protected void onChange(Session s) {
+ }
+
+ protected abstract Session doGetSession(Serializable sessionId) throws InvalidSessionException;
+
+ protected abstract Session createSession(InetAddress originatingHost) throws HostUnauthorizedException, IllegalArgumentException;
+}
diff --git a/core/src/org/jsecurity/session/mgt/AbstractValidatingSessionManager.java b/core/src/org/jsecurity/session/mgt/AbstractValidatingSessionManager.java
new file mode 100644
index 0000000..18b2176
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/AbstractValidatingSessionManager.java
@@ -0,0 +1,301 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authz.HostUnauthorizedException;
+import org.jsecurity.session.ExpiredSessionException;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.util.Destroyable;
+import org.jsecurity.util.LifecycleUtils;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+
+/**
+ * Default business-tier implementation of the {@link ValidatingSessionManager} interface.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public abstract class AbstractValidatingSessionManager extends AbstractSessionManager
+ implements ValidatingSessionManager, Destroyable {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(AbstractValidatingSessionManager.class);
+
+ protected static final long MILLIS_PER_SECOND = 1000;
+ protected static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
+ protected static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
+
+ /**
+ * Default main session timeout value (30 * 60 * 1000 milliseconds = 30 minutes).
+ */
+ public static final long DEFAULT_GLOBAL_SESSION_TIMEOUT = 30 * MILLIS_PER_MINUTE;
+
+ /**
+ * The default interval at which sessions will be validated (1 hour);
+ * This can be overridden by calling {@link #setSessionValidationInterval(long)}
+ */
+ public static final long DEFAULT_SESSION_VALIDATION_INTERVAL = MILLIS_PER_HOUR;
+
+ protected boolean sessionValidationSchedulerEnabled = true; //default
+ /**
+ * Scheduler used to validate sessions on a regular basis.
+ */
+ protected SessionValidationScheduler sessionValidationScheduler = null;
+
+ protected long sessionValidationInterval = DEFAULT_SESSION_VALIDATION_INTERVAL;
+ protected long globalSessionTimeout = DEFAULT_GLOBAL_SESSION_TIMEOUT;
+
+ public AbstractValidatingSessionManager() {
+ }
+
+ public boolean isSessionValidationSchedulerEnabled() {
+ return sessionValidationSchedulerEnabled;
+ }
+
+ public void setSessionValidationSchedulerEnabled(boolean sessionValidationSchedulerEnabled) {
+ this.sessionValidationSchedulerEnabled = sessionValidationSchedulerEnabled;
+ }
+
+ public void setSessionValidationScheduler(SessionValidationScheduler sessionValidationScheduler) {
+ this.sessionValidationScheduler = sessionValidationScheduler;
+ }
+
+ public SessionValidationScheduler getSessionValidationScheduler() {
+ return sessionValidationScheduler;
+ }
+
+ public void enableSessionValidationIfNecessary() {
+ SessionValidationScheduler scheduler = getSessionValidationScheduler();
+ if (isSessionValidationSchedulerEnabled() && (scheduler == null || !scheduler.isEnabled())) {
+ enableSessionValidation();
+ }
+ }
+
+ /**
+ * Returns the time in milliseconds that any session may remain idle before expiring. This
+ * value is just a main default for all sessions and may be overridden by subclasses on a
+ * <em>per-session</em> basis by overriding the {@link #getTimeout(Session)} method if
+ * so desired.
+ *
+ * <ul>
+ * <li>A negative return value means sessions never expire.</li>
+ * <li>A non-negative return value (0 or greater) means session timeout will occur as expected.</li>
+ * </ul>
+ *
+ * <p>Unless overridden via the {@link #setGlobalSessionTimeout} method, the default value is
+ * {@link #DEFAULT_GLOBAL_SESSION_TIMEOUT}.
+ *
+ * @return the time in milliseconds that any session may remain idle before expiring.
+ */
+ public long getGlobalSessionTimeout() {
+ return globalSessionTimeout;
+ }
+
+ /**
+ * Sets the time in milliseconds that any session may remain idle before expiring. This
+ * value is just a main default for all sessions. Subclasses may override the
+ * {@link #getTimeout} method to determine time-out values on a <em>per-session</em> basis.
+ *
+ * @param globalSessionTimeout the time in milliseconds any session may remain idle before
+ * expiring.
+ */
+ public void setGlobalSessionTimeout(int globalSessionTimeout) {
+ this.globalSessionTimeout = globalSessionTimeout;
+ }
+
+ /**
+ * If using the underlying default <tt>SessionValidationScheduler</tt> (that is, the
+ * {@link #setSessionValidationScheduler(SessionValidationScheduler) setSessionValidationScheduler} method is
+ * never called) , this method allows one to specify how
+ * frequently session should be validated (to check for orphans). The default value is
+ * {@link #DEFAULT_SESSION_VALIDATION_INTERVAL}.
+ *
+ * <p>If you override the default scheduler, it is assumed that overriding instance 'knows' how often to
+ * validate sessions, and this attribute will be ignored.
+ *
+ * <p>Unless this method is called, the default value is {@link #DEFAULT_SESSION_VALIDATION_INTERVAL}.
+ *
+ * @param sessionValidationInterval the time in milliseconds between checking for valid sessions to reap orphans.
+ */
+ public void setSessionValidationInterval(long sessionValidationInterval) {
+ this.sessionValidationInterval = sessionValidationInterval;
+ }
+
+ public long getSessionValidationInterval() {
+ return sessionValidationInterval;
+ }
+
+ protected final Session doGetSession(Serializable sessionId) throws InvalidSessionException {
+ enableSessionValidationIfNecessary();
+ return retrieveSession(sessionId);
+ }
+
+ protected abstract Session retrieveSession(Serializable sessionId) throws InvalidSessionException;
+
+ protected final Session createSession(InetAddress originatingHost) throws HostUnauthorizedException, IllegalArgumentException {
+ enableSessionValidationIfNecessary();
+ return doCreateSession(originatingHost);
+ }
+
+ protected abstract Session doCreateSession(InetAddress originatingHost) throws HostUnauthorizedException, IllegalArgumentException;
+
+ protected void validate(Session session) throws InvalidSessionException {
+ if (session instanceof ValidatingSession) {
+ try {
+ ((ValidatingSession) session).validate();
+ } catch (ExpiredSessionException ese) {
+ notifyExpiration(session);
+ onExpiration(session);
+ //propagate to caller:
+ throw ese;
+ }
+ } else {
+ String msg = "The " + getClass().getName() + " implementation only supports validating " +
+ "Session implementations of the " + ValidatingSession.class.getName() + " interface. " +
+ "Please either implement this interface in your session implementation or override the " +
+ getClass().getName() + ".validate(Session) method to perform validation.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ /**
+ * Subclass template hook in case per-session timeout is not based on
+ * {@link org.jsecurity.session.Session#getTimeout()}.
+ *
+ * <p>This implementation merely returns {@link org.jsecurity.session.Session#getTimeout()}</p>
+ *
+ * @param session the session for which to determine session timeout.
+ * @return the time in milliseconds the specified session may remain idle before expiring.
+ */
+ protected long getTimeout(Session session) {
+ return session.getTimeout();
+ }
+
+ protected SessionValidationScheduler createSessionValidationScheduler() {
+ SessionValidationScheduler scheduler;
+
+ if (log.isDebugEnabled()) {
+ log.debug("No sessionValidationScheduler set. Attempting to create default instance.");
+ }
+ scheduler = new ExecutorServiceSessionValidationScheduler(this);
+ ((ExecutorServiceSessionValidationScheduler) scheduler).setInterval(getSessionValidationInterval());
+ if (log.isTraceEnabled()) {
+ log.trace("Created default SessionValidationScheduler instance of type [" + scheduler.getClass().getName() + "].");
+ }
+ return scheduler;
+ }
+
+ protected void enableSessionValidation() {
+ SessionValidationScheduler scheduler = getSessionValidationScheduler();
+ if (scheduler == null) {
+ scheduler = createSessionValidationScheduler();
+ setSessionValidationScheduler(scheduler);
+ }
+ if (log.isInfoEnabled()) {
+ log.info("Enabling session validation scheduler...");
+ }
+ scheduler.enableSessionValidation();
+ afterSessionValidationEnabled();
+ }
+
+ protected void afterSessionValidationEnabled() {
+ }
+
+ protected void disableSessionValidation() {
+ beforeSessionValidationDisabled();
+ SessionValidationScheduler scheduler = getSessionValidationScheduler();
+ if (scheduler != null) {
+ try {
+ scheduler.disableSessionValidation();
+ if (log.isInfoEnabled()) {
+ log.info("Disabled session validation scheduler.");
+ }
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ String msg = "Unable to disable SessionValidationScheduler. Ignoring (shutting down)...";
+ log.debug(msg, e);
+ }
+ }
+ LifecycleUtils.destroy(scheduler);
+ setSessionValidationScheduler(null);
+ }
+ }
+
+ protected void beforeSessionValidationDisabled() {
+ }
+
+ public void destroy() {
+ disableSessionValidation();
+ }
+
+ /**
+ * @see ValidatingSessionManager#validateSessions()
+ */
+ public void validateSessions() {
+ if (log.isInfoEnabled()) {
+ log.info("Validating all active sessions...");
+ }
+
+ int invalidCount = 0;
+
+ Collection<Session> activeSessions = getActiveSessions();
+
+ if (activeSessions != null && !activeSessions.isEmpty()) {
+ for (Session s : activeSessions) {
+ try {
+ validate(s);
+ } catch (InvalidSessionException e) {
+ if (log.isDebugEnabled()) {
+ boolean expired = (e instanceof ExpiredSessionException);
+ String msg = "Invalidated session with id [" + s.getId() + "]" +
+ (expired ? " (expired)" : " (stopped)");
+ log.debug(msg);
+ }
+ invalidCount++;
+ }
+ }
+ }
+
+ if (log.isInfoEnabled()) {
+ String msg = "Finished session validation.";
+ if (invalidCount > 0) {
+ msg += " [" + invalidCount + "] sessions were stopped.";
+ } else {
+ msg += " No sessions were stopped.";
+ }
+ log.info(msg);
+ }
+ }
+
+ protected abstract Collection<Session> getActiveSessions();
+
+ public void validateSession(Serializable sessionId) {
+ //standard getSession call will validate, so just call the method:
+ getSession(sessionId);
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/mgt/DefaultSessionManager.java b/core/src/org/jsecurity/session/mgt/DefaultSessionManager.java
new file mode 100644
index 0000000..42ac514
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/DefaultSessionManager.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.cache.CacheManager;
+import org.jsecurity.cache.CacheManagerAware;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.mgt.eis.MemorySessionDAO;
+import org.jsecurity.session.mgt.eis.SessionDAO;
+import org.jsecurity.util.CollectionUtils;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * Default business-tier implementation of the {@link ValidatingSessionManager} interface.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class DefaultSessionManager extends AbstractValidatingSessionManager implements CacheManagerAware {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(DefaultSessionManager.class);
+
+ protected SessionDAO sessionDAO = new MemorySessionDAO();
+
+ public DefaultSessionManager() {
+ }
+
+ public void setSessionDAO(SessionDAO sessionDAO) {
+ this.sessionDAO = sessionDAO;
+ }
+
+ public SessionDAO getSessionDAO() {
+ return this.sessionDAO;
+ }
+
+ public void setCacheManager(CacheManager cacheManager) {
+ ((CacheManagerAware) getSessionDAO()).setCacheManager(cacheManager);
+ }
+
+ protected Session doCreateSession(InetAddress originatingHost) {
+ if (log.isTraceEnabled()) {
+ log.trace("Creating session for originating host [" + originatingHost + "]");
+ }
+ Session s = newSessionInstance(originatingHost);
+ create(s);
+ return s;
+ }
+
+ protected Session newSessionInstance(InetAddress inetAddress) {
+ return new SimpleSession(inetAddress);
+ }
+
+ protected void create(Session session) {
+ if (log.isDebugEnabled()) {
+ log.debug("Creating new EIS record for new session instance [" + session + "]");
+ }
+ sessionDAO.create(session);
+ }
+
+ protected void onStop(Session session) {
+ if (session instanceof SimpleSession) {
+ Date stopTs = ((SimpleSession) session).getStopTimestamp();
+ ((SimpleSession) session).setLastAccessTime(stopTs);
+ }
+ super.onStop(session);
+ }
+
+ protected void onExpiration(Session session) {
+ if (session instanceof SimpleSession) {
+ ((SimpleSession) session).setExpired(true);
+ }
+ onChange(session);
+ }
+
+ protected void onChange(Session session) {
+ sessionDAO.update(session);
+ }
+
+ protected Session retrieveSession(Serializable sessionId) throws InvalidSessionException {
+ if (log.isTraceEnabled()) {
+ log.trace("Retrieving session with id [" + sessionId + "]");
+ }
+ Session s = sessionDAO.readSession(sessionId);
+ validate(s);
+ return s;
+ }
+
+ protected Collection<Session> getActiveSessions() {
+ Collection<Session> active = sessionDAO.getActiveSessions();
+ return active != null ? active : CollectionUtils.emptyCollection(Session.class);
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/mgt/DelegatingSession.java b/core/src/org/jsecurity/session/mgt/DelegatingSession.java
new file mode 100644
index 0000000..feb491e
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/DelegatingSession.java
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * A DelegatingSession is a client-tier representation of a server side
+ * {@link org.jsecurity.session.Session Session}.
+ * This implementation is basically a proxy to a server-side {@link SessionManager SessionManager},
+ * which will return the proper results for each method call.
+ *
+ * <p>A <tt>DelegatingSession</tt> will cache data when appropriate to avoid a remote method invocation,
+ * only communicating with the server when necessary.
+ *
+ * <p>Of course, if used in-process with a SessionManager business POJO, as might be the case in a
+ * web-based application where the web classes and server-side business pojos exist in the same
+ * JVM, a remote method call will not be incurred.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public class DelegatingSession implements Session {
+
+ //TODO - complete JavaDoc
+
+ private Serializable id = null;
+
+ //cached fields to avoid a server-side method call if out-of-process:
+ private Date startTimestamp = null;
+ private InetAddress hostAddress = null;
+
+ /**
+ * Handle to a server-side SessionManager. See {@link #setSessionManager} for details.
+ */
+ private SessionManager sessionManager = null;
+
+
+ public DelegatingSession() {
+ }
+
+ public DelegatingSession(SessionManager sessionManager, Serializable id) {
+ this.sessionManager = sessionManager;
+ this.id = id;
+ }
+
+ /**
+ * Returns the {@link SessionManager SessionManager} used by this handle to invoke
+ * all session-related methods.
+ *
+ * @return the {@link SessionManager SessionManager} used by this handle to invoke
+ * all session-related methods.
+ */
+ public SessionManager getSessionManager() {
+ return sessionManager;
+ }
+
+ /**
+ * Sets the {@link SessionManager SessionManager} to which this <tt>DelegatingSession</tt> will
+ * delegate its method calls. In a rich client environment, this <tt>SessionManager</tt> will
+ * probably be a remoting proxy which executes remote method invocations. In a single-process
+ * environment (e.g. a web application deployed in the same JVM of the application server),
+ * the <tt>SessionManager</tt> can be the actual business POJO implementation.
+ *
+ * <p>You'll notice the {@link Session Session} interface and the {@link SessionManager}
+ * interface are nearly identical. This is to ensure the SessionManager can support
+ * most method calls in the Session interface, via this handle/proxy technique. The session
+ * manager is implementated as a stateless business POJO, with the handle passing the
+ * session id as necessary.
+ *
+ * @param sessionManager the <tt>SessionManager</tt> this handle will use when delegating
+ * method calls.
+ */
+ public void setSessionManager(SessionManager sessionManager) {
+ this.sessionManager = sessionManager;
+ }
+
+ /**
+ * Sets the sessionId used by this handle for all future {@link SessionManager SessionManager}
+ * method invocations.
+ *
+ * @param id the <tt>sessionId</tt> to use for all <tt>SessionManager</tt> invocations.
+ * @see #setSessionManager(SessionManager sessionManager)
+ */
+ public void setId(Serializable id) {
+ this.id = id;
+ }
+
+ /**
+ * @see Session#getId()
+ */
+ public Serializable getId() {
+ return id;
+ }
+
+ /**
+ * @see Session#getStartTimestamp()
+ */
+ public Date getStartTimestamp() {
+ if (startTimestamp == null) {
+ startTimestamp = sessionManager.getStartTimestamp(id);
+ }
+ return startTimestamp;
+ }
+
+ /**
+ * @see org.jsecurity.session.Session#getLastAccessTime()
+ */
+ public Date getLastAccessTime() {
+ //can't cache - only business pojo knows the accurate time:
+ return sessionManager.getLastAccessTime(id);
+ }
+
+ public long getTimeout() throws InvalidSessionException {
+ return sessionManager.getTimeout(id);
+ }
+
+ public void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException {
+ sessionManager.setTimeout(id, maxIdleTimeInMillis);
+ }
+
+ /**
+ * @see org.jsecurity.session.Session#getHostAddress()
+ */
+ public InetAddress getHostAddress() {
+ if (hostAddress == null) {
+ hostAddress = sessionManager.getHostAddress(id);
+ }
+ return hostAddress;
+ }
+
+ /**
+ * @see org.jsecurity.session.Session#touch()
+ */
+ public void touch() throws InvalidSessionException {
+ sessionManager.touch(id);
+ }
+
+ /**
+ * @see org.jsecurity.session.Session#stop()
+ */
+ public void stop() throws InvalidSessionException {
+ sessionManager.stop(id);
+ }
+
+ /**
+ * @see org.jsecurity.session.Session#getAttributeKeys
+ */
+ public Collection<Object> getAttributeKeys() throws InvalidSessionException {
+ return sessionManager.getAttributeKeys(id);
+ }
+
+ /**
+ * @see Session#getAttribute(Object key)
+ */
+ public Object getAttribute(Object key) throws InvalidSessionException {
+ return sessionManager.getAttribute(id, key);
+ }
+
+ /**
+ * @see Session#setAttribute(Object key, Object value)
+ */
+ public void setAttribute(Object key, Object value) throws InvalidSessionException {
+ if (value == null) {
+ removeAttribute(key);
+ } else {
+ sessionManager.setAttribute(id, key, value);
+ }
+ }
+
+ /**
+ * @see Session#removeAttribute(Object key)
+ */
+ public Object removeAttribute(Object key) throws InvalidSessionException {
+ return sessionManager.removeAttribute(id, key);
+ }
+}
diff --git a/core/src/org/jsecurity/session/mgt/ExecutorServiceSessionValidationScheduler.java b/core/src/org/jsecurity/session/mgt/ExecutorServiceSessionValidationScheduler.java
new file mode 100644
index 0000000..7b65890
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/ExecutorServiceSessionValidationScheduler.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * SessionValidationScheduler implementation that uses a
+ * {@link ScheduledExecutorService} to call {@link ValidatingSessionManager#validateSessions()} every
+ * <em>{@link #getInterval interval}</em> milliseconds.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class ExecutorServiceSessionValidationScheduler implements SessionValidationScheduler, Runnable {
+
+ //TODO - complete JavaDoc
+
+ /** Private internal log instance. */
+ private static final Log log = LogFactory.getLog(ExecutorServiceSessionValidationScheduler.class);
+
+ ValidatingSessionManager sessionManager;
+ private ScheduledExecutorService service;
+ private long interval = DefaultSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
+ private boolean enabled = false;
+
+ public ExecutorServiceSessionValidationScheduler() {
+ super();
+ }
+
+ public ExecutorServiceSessionValidationScheduler(ValidatingSessionManager sessionManager) {
+ this.sessionManager = sessionManager;
+ }
+
+ public ValidatingSessionManager getSessionManager() {
+ return sessionManager;
+ }
+
+ public void setSessionManager(ValidatingSessionManager sessionManager) {
+ this.sessionManager = sessionManager;
+ }
+
+ public long getInterval() {
+ return interval;
+ }
+
+ public void setInterval(long interval) {
+ this.interval = interval;
+ }
+
+ public boolean isEnabled() {
+ return this.enabled;
+ }
+
+ public void enableSessionValidation() {
+ if (this.interval > 0l) {
+ this.service = Executors.newSingleThreadScheduledExecutor();
+ this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
+ this.enabled = true;
+ }
+ }
+
+ public void run() {
+ if (log.isDebugEnabled()) {
+ log.debug("Executing session validation...");
+ }
+ long startTime = System.currentTimeMillis();
+ this.sessionManager.validateSessions();
+ long stopTime = System.currentTimeMillis();
+ if (log.isDebugEnabled()) {
+ log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
+ }
+ }
+
+ public void disableSessionValidation() {
+ this.service.shutdownNow();
+ this.enabled = false;
+ }
+}
diff --git a/core/src/org/jsecurity/session/mgt/ImmutableProxiedSession.java b/core/src/org/jsecurity/session/mgt/ImmutableProxiedSession.java
new file mode 100644
index 0000000..7133e5e
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/ImmutableProxiedSession.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.ProxiedSession;
+import org.jsecurity.session.Session;
+
+/**
+ * Implementation of the {@link Session Session} interface that proxies another <code>Session</code>, but does not
+ * allow any 'write' operations to the underlying session. It allows 'read' operations only.
+ * <p/>
+ * The <code>Session</code> write operations are defined as follows. A call to any of these methods on this
+ * proxy will immediately result in an {@link InvalidSessionException} being thrown:
+ *
+ * <ul>
+ * <li>{@link Session#setTimeout(long) Session.setTimeout(long)}</li>
+ * <li>{@link Session#touch() Session.touch()}</li>
+ * <li>{@link Session#stop() Session.stop()}</li>
+ * <li>{@link Session#setAttribute(Object, Object) Session.setAttribute(key,value)}</li>
+ * <li>{@link Session#removeAttribute(Object) Session.removeAttribute(key)}</li>
+ * </ul>
+ *
+ * <p/>
+ * Any other method invocation not listed above will result in a corresponding call to the underlying <code>Session</code>.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class ImmutableProxiedSession extends ProxiedSession {
+
+ /**
+ * Constructs a new instance of this class proxying the specified <code>Session</code>.
+ *
+ * @param target the target <code>Session</code> to proxy.
+ */
+ public ImmutableProxiedSession(Session target) {
+ super(target);
+ }
+
+ /**
+ * Simply throws an <code>InvalidSessionException</code> indicating that this proxy is immutable. Used
+ * only in the Session's 'write' methods documented in the top class-level JavaDoc.
+ *
+ * @throws InvalidSessionException in all cases - used by the Session 'write' method implementations.
+ */
+ protected void throwImmutableException() throws InvalidSessionException {
+ String msg = "This session is immutable and read-only - it cannot be altered. This is usually because " +
+ "the session has been stopped or expired already.";
+ throw new InvalidSessionException(msg);
+ }
+
+ /**
+ * Immediately {@link #throwImmutableException() throws} an <code>InvalidSessionException</code> in all
+ * cases because this proxy is immutable.
+ */
+ public void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException {
+ throwImmutableException();
+ }
+
+ /**
+ * Immediately {@link #throwImmutableException() throws} an <code>InvalidSessionException</code> in all
+ * cases because this proxy is immutable.
+ */
+ public void touch() throws InvalidSessionException {
+ throwImmutableException();
+ }
+
+ /**
+ * Immediately {@link #throwImmutableException() throws} an <code>InvalidSessionException</code> in all
+ * cases because this proxy is immutable.
+ */
+ public void stop() throws InvalidSessionException {
+ throwImmutableException();
+ }
+
+ /**
+ * Immediately {@link #throwImmutableException() throws} an <code>InvalidSessionException</code> in all
+ * cases because this proxy is immutable.
+ */
+ public void setAttribute(Object key, Object value) throws InvalidSessionException {
+ throwImmutableException();
+ }
+
+ /**
+ * Immediately {@link #throwImmutableException() throws} an <code>InvalidSessionException</code> in all
+ * cases because this proxy is immutable.
+ */
+ public Object removeAttribute(Object key) throws InvalidSessionException {
+ throwImmutableException();
+ //we should never ever reach this point due to the exception being thrown.
+ throw new InternalError("This code should never execute - please report this as a bug!");
+ }
+}
diff --git a/core/src/org/jsecurity/session/mgt/SessionManager.java b/core/src/org/jsecurity/session/mgt/SessionManager.java
new file mode 100644
index 0000000..ab833d1
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/SessionManager.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.jsecurity.authz.HostUnauthorizedException;
+import org.jsecurity.session.InvalidSessionException;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * A SessionManager manages the creation, maintenance, and clean-up of all application
+ * {@link org.jsecurity.session.Session Session}s.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public interface SessionManager {
+
+ /**
+ * Starts a new session within the system for the host with the specified originating IP
+ * address.
+ *
+ * <p><b>Note</b>: see the
+ * {@link org.jsecurity.session.SessionFactory#start(java.net.InetAddress) SessionFactory.init(InetAddress)} method
+ * about the implications of using <tt>InetAddress</tt>es in access control policies.
+ *
+ * @param originatingHost the originating host InetAddress of the external party
+ * (user, 3rd party product, etc) that is attempting to interact with the system.
+ * @return the system identifier of the newly created session.
+ * @throws IllegalArgumentException if the host specified is not valid.
+ * @throws org.jsecurity.authz.HostUnauthorizedException
+ * if the host specified is not allowed to start sessions.
+ * @see org.jsecurity.session.SessionFactory#start(InetAddress)
+ */
+ Serializable start(InetAddress originatingHost)
+ throws HostUnauthorizedException, IllegalArgumentException;
+
+ /**
+ * Returns the time the Session identified by the specified <tt>sessionId</tt> was started
+ * in the system.
+ *
+ * @param sessionId the system identifier for the session of interest.
+ * @return the system time the specified session was started (i.e. created).
+ * @see org.jsecurity.session.Session#getStartTimestamp()
+ */
+ Date getStartTimestamp(Serializable sessionId);
+
+ /**
+ * Returns the time the <tt>Session</tt> identified by the specified <tt>sessionId</tt> last
+ * interacted with the system.
+ *
+ * @param sessionId the system identifier for the session of interest
+ * @return tye time the session last accessed the system
+ * @see org.jsecurity.session.Session#getLastAccessTime()
+ * @see org.jsecurity.session.Session#touch()
+ */
+ Date getLastAccessTime(Serializable sessionId);
+
+
+ /**
+ * Returns <tt>true</tt> if the session is valid (it exists and is not stopped nor expired), <tt>false</tt> otherwise.
+ *
+ * @param sessionId the id of the session to check
+ * @return <tt>true</tt> if the session is valid (exists and is not stopped or expired), <tt>false</tt> otherwise.
+ */
+ boolean isValid(Serializable sessionId);
+
+ /**
+ * Returns the time in milliseconds that the specified session may remain idle before expiring.
+ *
+ * <ul>
+ * <li>A negative return value means the session will never expire.</li>
+ * <li>A non-negative return value (0 or greater) means the session expiration will occur if idle for that
+ * length of time.</li>
+ * </ul>
+ *
+ * @param sessionId the system identifier of the session of interest.
+ * @return the time in milliseconds that the specified session may remain idle before expiring.
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if the session has been stopped or expired prior to calling this method.
+ * @since 0.2
+ */
+ long getTimeout(Serializable sessionId) throws InvalidSessionException;
+
+ /**
+ * Sets the time in milliseconds that the specified session may remain idle before expiring.
+ *
+ * <ul>
+ * <li>A negative return value means the session will never expire.</li>
+ * <li>A non-negative return value (0 or greater) means the session expiration will occur if idle for that
+ * length of time.</li>
+ * </ul>
+ *
+ * @param sessionId the system identifier of the session of interest.
+ * @param maxIdleTimeInMillis the time in milliseconds that the specified session may remain idle before expiring.
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if the session has been stopped or expired prior to calling this method.
+ * @since 0.2
+ */
+ void setTimeout(Serializable sessionId, long maxIdleTimeInMillis) throws InvalidSessionException;
+
+ /**
+ * Updates the last accessed time of the session identified by <code>sessionId</code>. This
+ * can be used to explicitly ensure that a session does not time out.
+ *
+ * @param sessionId the id of the session to update.
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if the session has been stopped or expired prior to calling this method.
+ * @see org.jsecurity.session.Session#touch
+ */
+ void touch(Serializable sessionId) throws InvalidSessionException;
+
+
+ /**
+ * Returns the IP address of the host where the session was started, if known. If
+ * no IP was specified when starting the session, this method returns <code>null</code>
+ *
+ * @param sessionId the id of the session to query.
+ * @return the ip address of the host where the session originated, if known. If unknown,
+ * this method returns <code>null</code>.
+ * @see #start(InetAddress originatingHost) init( InetAddress originatingHost )
+ */
+ InetAddress getHostAddress(Serializable sessionId);
+
+ /**
+ * Explicitly stops the session identified by <tt>sessionId</tt>, thereby releasing all
+ * associated resources.
+ *
+ * @param sessionId the system identfier of the system to destroy.
+ * @throws InvalidSessionException if the session has stopped or expired prior to calling
+ * this method.
+ * @see org.jsecurity.session.Session#stop
+ */
+ void stop(Serializable sessionId) throws InvalidSessionException;
+
+ /**
+ * Returns the keys of all the attributes stored under the session identified by <tt>sessionId</tt>.
+ * If there are no attributes, this returns an empty collection.
+ *
+ * @param sessionId the system identifier of the system to access.
+ * @return the keys of all attributes stored under the specified session, or an empty collection if
+ * there are no session attributes.
+ * @throws InvalidSessionException if the specified session has stopped or expired prior to calling this method.
+ * @see org.jsecurity.session.Session#getAttributeKeys()
+ * @since 0.2
+ */
+ Collection<Object> getAttributeKeys(Serializable sessionId);
+
+ /**
+ * Returns the object bound to the specified session identified by the specified key. If there
+ * is noobject bound under the key for the given session, <tt>null</tt> is returned.
+ *
+ * @param sessionId the system identifier of the session of interest
+ * @param key the unique name of the object bound to the specified session
+ * @return the object bound under the specified <tt>key</tt> name or <tt>null</tt> if there is
+ * no object bound under that name.
+ * @throws InvalidSessionException if the specified session has stopped or expired prior to calling this method.
+ * @see org.jsecurity.session.Session#getAttribute(Object key)
+ */
+ Object getAttribute(Serializable sessionId, Object key) throws InvalidSessionException;
+
+ /**
+ * Binds the specified <tt>value</tt> to the specified session uniquely identified by the
+ * specifed <tt>key</tt> name. If there is already an object bound under the <tt>key</tt>
+ * name, that existing object will be replaced by the new <tt>value</tt>.
+ *
+ * <p>If the <tt>value</tt> parameter is null, it has the same effect as if the
+ * {@link #removeAttribute(Serializable sessionId, Object key)} method was called.
+ *
+ * @param sessionId the system identifier of the session of interest
+ * @param key the name under which the <tt>value</tt> object will be bound in this session
+ * @param value the object to bind in this session.
+ * @throws InvalidSessionException if the specified session has stopped or expired prior to calling this method.
+ * @see org.jsecurity.session.Session#setAttribute(Object key, Object value)
+ */
+ void setAttribute(Serializable sessionId, Object key, Object value) throws InvalidSessionException;
+
+ /**
+ * Removes (unbinds) the object bound to this session under the specified <tt>key</tt> name.
+ *
+ * @param sessionId the system identifier of the session of interest
+ * @param key the name uniquely identifying the object to remove
+ * @return the object removed or <tt>null</tt> if there was no object bound under the specified
+ * <tt>key</tt> name.
+ * @throws InvalidSessionException if the specified session has stopped or expired prior to calling this method.
+ * @see org.jsecurity.session.Session#removeAttribute(Object key)
+ */
+ Object removeAttribute(Serializable sessionId, Object key) throws InvalidSessionException;
+}
diff --git a/core/src/org/jsecurity/session/mgt/SessionValidationScheduler.java b/core/src/org/jsecurity/session/mgt/SessionValidationScheduler.java
new file mode 100644
index 0000000..80976f5
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/SessionValidationScheduler.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+/**
+ * Interface that should be implemented by classes that can control validating sessions on a regular
+ * basis. This interface is used as a delegate for session validation by the {@link DefaultSessionManager}
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @see DefaultSessionManager#setSessionValidationScheduler(SessionValidationScheduler)
+ * @since 0.1
+ */
+public interface SessionValidationScheduler {
+
+ /**
+ * Returns <code>true</code> if this Scheduler is enabled and ready to begin validation at the appropriate time,
+ * <code>false</code> otherwise.
+ * <p/>
+ * It does <em>not</em> indicate if the validation is actually executing at that instant - only that it is prepared
+ * to do so at the appropriate time.
+ *
+ * @return <code>true</code> if this Scheduler is enabled and ready to begin validation at the appropriate time,
+ * <code>false</code> otherwise.
+ */
+ boolean isEnabled();
+
+ /**
+ * Enables the session validation job.
+ */
+ void enableSessionValidation();
+
+ /**
+ * Disables the session validation job.
+ */
+ void disableSessionValidation();
+
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/session/mgt/SimpleSession.java b/core/src/org/jsecurity/session/mgt/SimpleSession.java
new file mode 100644
index 0000000..f981182
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/SimpleSession.java
@@ -0,0 +1,316 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.session.ExpiredSessionException;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.StoppedSessionException;
+
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.text.DateFormat;
+import java.util.*;
+
+/**
+ * Simple {@link org.jsecurity.session.Session} POJO implementation, intended to be used on the business/server tier.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class SimpleSession implements ValidatingSession, Serializable {
+
+ //TODO - complete JavaDoc
+
+ protected static final long MILLIS_PER_SECOND = 1000;
+ protected static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
+ protected static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
+
+ private transient static final Log log = LogFactory.getLog(SimpleSession.class);
+
+
+ private Serializable id = null;
+ private Date startTimestamp = null;
+ private Date stopTimestamp = null;
+ private Date lastAccessTime = null;
+ private long timeout = DefaultSessionManager.DEFAULT_GLOBAL_SESSION_TIMEOUT;
+ private boolean expired = false;
+ private InetAddress hostAddress = null;
+
+ private Map<Object, Object> attributes = null;
+
+ public SimpleSession() {
+ this(getLocalHost());
+ }
+
+ public SimpleSession(InetAddress hostAddress) {
+ this.startTimestamp = new Date();
+ this.lastAccessTime = startTimestamp;
+ this.hostAddress = hostAddress;
+ }
+
+ private static InetAddress getLocalHost() {
+ try {
+ return InetAddress.getLocalHost();
+ } catch (UnknownHostException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public Serializable getId() {
+ return this.id;
+ }
+
+ public void setId(Serializable id) {
+ this.id = id;
+ }
+
+ public Date getStartTimestamp() {
+ return startTimestamp;
+ }
+
+ public void setStartTimestamp(Date startTimestamp) {
+ this.startTimestamp = startTimestamp;
+ }
+
+ /**
+ * Returns the time the session was stopped, or <tt>null</tt> if the session is still active.
+ *
+ * <p>A session may become stopped under a number of conditions:
+ * <ul>
+ * <li>If the user logs out of the system, their current session is terminated (released).</li>
+ * <li>If the session expires</li>
+ * <li>The application explicitly calls {@link #stop() destroy()}</li>
+ * <li>If there is an internal system error and the session state can no longer accurately
+ * reflect the user's behavior, such in the case of a system crash</li>
+ * </ul>
+ * </p>
+ *
+ * <p>Once stopped, a session may no longer be used. It is locked from all further activity.
+ *
+ * @return The time the session was stopped, or <tt>null</tt> if the session is still
+ * active.
+ */
+ public Date getStopTimestamp() {
+ return stopTimestamp;
+ }
+
+ public void setStopTimestamp(Date stopTimestamp) {
+ this.stopTimestamp = stopTimestamp;
+ }
+
+ public Date getLastAccessTime() {
+ return lastAccessTime;
+ }
+
+ public void setLastAccessTime(Date lastAccessTime) {
+ this.lastAccessTime = lastAccessTime;
+ }
+
+ /**
+ * Returns true if this session has expired, false otherwise. If the session has
+ * expired, no further user interaction with the system may be done under this session.
+ *
+ * @return true if this session has expired, false otherwise.
+ */
+ public boolean isExpired() {
+ return expired;
+ }
+
+ public void setExpired(boolean expired) {
+ this.expired = expired;
+ }
+
+ public long getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout) {
+ this.timeout = timeout;
+ }
+
+ public InetAddress getHostAddress() {
+ return hostAddress;
+ }
+
+ public void setHostAddress(InetAddress hostAddress) {
+ this.hostAddress = hostAddress;
+ }
+
+ public Map<Object, Object> getAttributes() {
+ touch();
+ return attributes;
+ }
+
+ public void setAttributes(Map<Object, Object> attributes) {
+ touch();
+ this.attributes = attributes;
+ }
+
+ public void touch() {
+ this.lastAccessTime = new Date();
+ }
+
+ public void stop() {
+ if (this.stopTimestamp == null) {
+ this.stopTimestamp = new Date();
+ }
+ }
+
+ protected boolean isStopped() {
+ return getStopTimestamp() != null;
+ }
+
+ protected void expire() {
+ stop();
+ if ( !this.expired ) {
+ this.expired = true;
+ }
+ }
+
+ /**
+ * @since 0.9
+ */
+ public boolean isValid() {
+ return !isStopped() && !isExpired();
+ }
+
+ /**
+ * Determines if this session is expired.
+ *
+ * @return true if the specified session has expired, false otherwise.
+ */
+ protected boolean isTimedOut() {
+
+ if (isExpired()) {
+ return true;
+ }
+
+ long timeout = getTimeout();
+
+ if (timeout >= 0l) {
+
+ Date lastAccessTime = getLastAccessTime();
+
+ if (lastAccessTime == null) {
+ String msg = "session.lastAccessTime for session with id [" +
+ getId() + "] is null. This value must be set at " +
+ "least once, preferably at least upon instantiation. Please check the " +
+ getClass().getName() + " implementation and ensure " +
+ "this value will be set (perhaps in the constructor?)";
+ throw new IllegalStateException(msg);
+ }
+
+ // Calculate at what time a session would have been last accessed
+ // for it to be expired at this point. In other words, subtract
+ // from the current time the amount of time that a session can
+ // be inactive before expiring. If the session was last accessed
+ // before this time, it is expired.
+ long expireTimeMillis = System.currentTimeMillis() - timeout;
+ Date expireTime = new Date(expireTimeMillis);
+ return lastAccessTime.before(expireTime);
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("No timeout for session with id [" + getId() +
+ "]. Session is not considered expired.");
+ }
+ }
+
+ return false;
+ }
+
+ public void validate() throws InvalidSessionException {
+ //check for stopped:
+ if (isStopped()) {
+ //timestamp is set, so the session is considered stopped:
+ String msg = "Session with id [" + getId() + "] has been " +
+ "explicitly stopped. No further interaction under this session is " +
+ "allowed.";
+ throw new StoppedSessionException(msg, getId());
+ }
+
+ //check for expiration
+ if (isTimedOut()) {
+ expire();
+
+ //throw an exception explaining details of why it expired:
+ Date lastAccessTime = getLastAccessTime();
+ long timeout = getTimeout();
+
+ Serializable sessionId = getId();
+
+ DateFormat df = DateFormat.getInstance();
+ String msg = "Session with id [" + sessionId + "] has expired. " +
+ "Last access time: " + df.format(lastAccessTime) +
+ ". Current time: " + df.format(new Date()) +
+ ". Session timeout is set to " + timeout / MILLIS_PER_SECOND + " seconds (" +
+ timeout / MILLIS_PER_MINUTE + " minutes)";
+ if (log.isTraceEnabled()) {
+ log.trace(msg);
+ }
+ throw new ExpiredSessionException(msg, sessionId);
+ }
+ }
+
+ private Map<Object, Object> getAttributesLazy() {
+ Map<Object, Object> attributes = getAttributes();
+ if (attributes == null) {
+ attributes = new HashMap<Object, Object>();
+ setAttributes(attributes);
+ }
+ return attributes;
+ }
+
+ public Collection<Object> getAttributeKeys() throws InvalidSessionException {
+ Map<Object, Object> attributes = getAttributes();
+ if (attributes == null) {
+ //noinspection unchecked
+ return Collections.EMPTY_SET;
+ }
+ return attributes.keySet();
+ }
+
+ public Object getAttribute(Object key) {
+ Map<Object, Object> attributes = getAttributes();
+ if (attributes == null) {
+ return null;
+ }
+ return attributes.get(key);
+ }
+
+ public void setAttribute(Object key, Object value) {
+ if (value == null) {
+ removeAttribute(key);
+ } else {
+ getAttributesLazy().put(key, value);
+ }
+ }
+
+ public Object removeAttribute(Object key) {
+ Map<Object, Object> attributes = getAttributes();
+ if (attributes == null) {
+ return null;
+ } else {
+ return attributes.remove(key);
+ }
+ }
+
+}
diff --git a/core/src/org/jsecurity/session/mgt/ValidatingSession.java b/core/src/org/jsecurity/session/mgt/ValidatingSession.java
new file mode 100644
index 0000000..bd17246
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/ValidatingSession.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+
+/**
+ * A <code>ValidatingSession</code> is a <code>Session</code> that is capable of determining it is valid or not and
+ * is able to validate itself if necessary.
+ * <p/>
+ * Validation is usually an exercise of determining when the session was last accessed or modified and determining if
+ * that time is longer than a specified allowed duration.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface ValidatingSession extends Session {
+
+ boolean isValid();
+
+ void validate() throws InvalidSessionException;
+}
diff --git a/core/src/org/jsecurity/session/mgt/ValidatingSessionManager.java b/core/src/org/jsecurity/session/mgt/ValidatingSessionManager.java
new file mode 100644
index 0000000..76bce33
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/ValidatingSessionManager.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt;
+
+import org.jsecurity.session.InvalidSessionException;
+
+import java.io.Serializable;
+
+/**
+ * A ValidatingSessionManager is a SessionManager that can proactively validate any or all sessions
+ * that may be expired.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public interface ValidatingSessionManager extends SessionManager {
+
+ /**
+ * Performs session validation for all open/active sessions in the system (those that
+ * have not been stopped or expired), and validates each one. If a session is
+ * found to be invalid (e.g. it has expired), it is updated and saved to the EIS.
+ *
+ * <p>This method is necessary in order to handle orphaned sessions and is expected to be run at
+ * a regular interval, such as once an hour, once a day or once a week, etc.
+ * The "best" frequency to run this method is entirely dependent upon the application
+ * and would be based on factors such as performance, average number of active users, hours of
+ * least activity, and other things.
+ *
+ * <p>Most enterprise applications use a request/response programming model.
+ * This is obvious in the case of web applications due to the HTTP protocol, but it is
+ * equally true of remote client applications making remote method invocations. The server
+ * essentially sits idle and only "works" when responding to client requests and/or
+ * method invocations. This type of model is particularly efficent since it means the
+ * security system only has to validate a session during those cases. Such
+ * "lazy" behavior enables the system to lie stateless and/or idle and only incur
+ * overhead for session validation when necessary.
+ *
+ * <p>However, if a client forgets to log-out, or in the event of a server failure, it is
+ * possible for sessions to be orphaned since no further requests would utilize that session.
+ * Because of these lower-probability cases, it is required to regularly clean-up the sessions
+ * maintained by the system.
+ *
+ * <p>Even in applications that aren't primarily based on a request/response model,
+ * such as those that use enterprise asynchronous messaging (where data is pushed to
+ * a client without first receiving a client request), it is almost always acceptable to
+ * utilize this lazy approach and run this method at defined interval.
+ *
+ * <p>Systems that want to proactively validate individual sessions may call the
+ * {@link #validateSession(Serializable) validateSession} method. Note that even in such
+ * proactive systems, this {@link #validateSessions()} method should be invoked regularaly
+ * anyway to <em>guarantee</em> no orphans exist.
+ *
+ * <p><b>Note:</b> JSecurity supports automatic execution of this method at a regular interval
+ * by using {@link SessionValidationScheduler}s. The JSecurity default SecurityManager implementations
+ * needing session validation will create and use one by default if one is not provided by the
+ * application configuration.
+ */
+ void validateSessions();
+
+ /**
+ * Proactively validates a single session.
+ *
+ * @param sessionId the id of the session to validate
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if, upon validation, the session was stopped or expired.
+ */
+ void validateSession(Serializable sessionId) throws InvalidSessionException;
+}
diff --git a/core/src/org/jsecurity/session/mgt/eis/CachingSessionDAO.java b/core/src/org/jsecurity/session/mgt/eis/CachingSessionDAO.java
new file mode 100644
index 0000000..002cc99
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/eis/CachingSessionDAO.java
@@ -0,0 +1,396 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt.eis;
+
+import org.jsecurity.cache.Cache;
+import org.jsecurity.cache.CacheManager;
+import org.jsecurity.cache.CacheManagerAware;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.UnknownSessionException;
+import org.jsecurity.session.mgt.ValidatingSession;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+
+/**
+ * An CachingSessionDAO is a SessionDAO that provides a transparent caching layer between the components that
+ * use it and the underlying EIS (Enterprise Information System) for enhanced performance.
+ *
+ * <p>This implementation caches all active sessions in a cache created by a
+ * {@link org.jsecurity.cache.CacheManager}. All <tt>SessionDAO</tt> methods are implemented by this class to employ
+ * caching behavior and delegates the actual EIS operations to respective do* methods to be implemented by
+ * subclasses (doCreate, doRead, etc).
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public abstract class CachingSessionDAO implements SessionDAO, CacheManagerAware {
+
+ /**
+ * The default active sessions cache name, equal to <code>jsecurity-activeSessionCache</code>.
+ */
+ public static final String ACTIVE_SESSION_CACHE_NAME = "jsecurity-activeSessionCache";
+
+ /**
+ * The CacheManager to use to acquire the Session cache.
+ */
+ private CacheManager cacheManager;
+
+ /**
+ * The Cache instance responsible for caching Sessions.
+ */
+ private Cache activeSessions;
+
+ /**
+ * The name of the session cache, defaults to {@link #ACTIVE_SESSION_CACHE_NAME}.
+ */
+ private String activeSessionsCacheName = ACTIVE_SESSION_CACHE_NAME;
+
+ /**
+ * Default no-arg constructor.
+ */
+ public CachingSessionDAO() {
+ }
+
+ /**
+ * Sets the cacheManager to use for constructing the session cache.
+ *
+ * @param cacheManager the manager to use for constructing the session cache.
+ */
+ public void setCacheManager(CacheManager cacheManager) {
+ this.cacheManager = cacheManager;
+ //force cache reload:
+ this.activeSessions = null;
+ }
+
+ /**
+ * Returns the CacheManager used by the implementation that creates the activeSessions Cache.
+ *
+ * @return the CacheManager used by the implementation that creates the activeSessions Cache.
+ */
+ public CacheManager getCacheManager() {
+ return cacheManager;
+ }
+
+ /**
+ * Returns the name of the actives sessions cache to be returned by the <code>CacheManager</code>. Unless
+ * overridden by {@link #setActiveSessionsCacheName(String)}, defaults to {@link #ACTIVE_SESSION_CACHE_NAME}.
+ * @return the name of the active sessions cache.
+ */
+ public String getActiveSessionsCacheName() {
+ return activeSessionsCacheName;
+ }
+
+ /**
+ * Sets the name of the active sessions cache to be returned by the <code>CacheManager</code>. Defaults to
+ * {@link #ACTIVE_SESSION_CACHE_NAME}.
+ * @param activeSessionsCacheName the name of the active sessions cache to be returned by the <code>CacheManager</code>.
+ */
+ public void setActiveSessionsCacheName(String activeSessionsCacheName) {
+ this.activeSessionsCacheName = activeSessionsCacheName;
+ }
+
+ /**
+ * Returns the cache instance to use for storing active sessions.
+ * @return the cache instance to use for storing active sessions.
+ */
+ public Cache getActiveSessionsCache() {
+ return this.activeSessions;
+ }
+
+ /**
+ * Returns the active sessions cache, but if that cache instance is null, first lazily creates the cache instance
+ * via the {@link #createActiveSessionsCache()} method and then returns the instance.
+ * <p/>
+ * Note that this method will only return a non-null value code if the <code>CacheManager</code> has been set. If
+ * not set, there will be no cache.
+ *
+ * @return the active sessions cache instance.
+ */
+ protected Cache getActiveSessionsCacheLazy() {
+ if (this.activeSessions == null) {
+ this.activeSessions = createActiveSessionsCache();
+ }
+ return this.activeSessions;
+ }
+
+ /**
+ * Sets the cache instance to use for storing active sessions.
+ * @param cache the cache instance to use for storing active sessions.
+ */
+ public void setActiveSessionsCache(Cache cache) {
+ this.activeSessions = cache;
+ }
+
+ /**
+ * Creates a cache instance used to store active sessions. Creation is done by first
+ * {@link #getCacheManager() acquiring} the <code>CacheManager</code>. If the cache manager is not null, the
+ * cache returned is that resulting from the following call:
+ * <pre> String name = {@link #getActiveSessionsCacheName() getActiveSessionsCacheName()};
+ * cacheManager.getCache(name);</pre>
+ * @return a cache instance used to store active sessions, or <em>null</code> if the <code>CacheManager</code> has
+ * not been set.
+ */
+ protected Cache createActiveSessionsCache() {
+ Cache cache = null;
+ CacheManager mgr = getCacheManager();
+ if (mgr != null) {
+ String name = getActiveSessionsCacheName();
+ cache = mgr.getCache(name);
+ }
+ return cache;
+ }
+
+ /**
+ * Creates the session by delegating EIS creation to subclasses via the {@link #doCreate} method, and then
+ * caches the session.
+ *
+ * @param session Session object to create in the EIS and then cache.
+ */
+ public Serializable create(Session session) {
+ Serializable sessionId = doCreate(session);
+ verifySessionId(sessionId);
+ cacheValidSession(session, sessionId);
+ return sessionId;
+ }
+
+ /**
+ * Returns the cached session with the corresponding <code>sessionId</code> or <code>null</code> if there is
+ * no session cached under that id (or if there is no Cache).
+ *
+ * @param sessionId the id of the cached session to acquire.
+ * @return the cached session with the corresponding <code>sessionId</code>, or <code>null</code> if the session
+ * does not exist or is not cached.
+ */
+ protected Session getCachedSession(Serializable sessionId) {
+ Session cached = null;
+ if (sessionId != null) {
+ Cache cache = getActiveSessionsCacheLazy();
+ if (cache != null) {
+ cached = getCachedSession(sessionId, cache);
+ }
+ }
+ return cached;
+ }
+
+ /**
+ * Returns the Session with the specified id from the specified cache. This method simply calls
+ * <code>cache.get(sessionId)</code> and can be overridden by subclasses for custom acquisition behavior.
+ * @param sessionId the id of the session to acquire.
+ * @param cache the cache to acquire the session from
+ * @return the cached session, or <code>null</code> if the session wasn't in the cache.
+ */
+ protected Session getCachedSession(Serializable sessionId, Cache cache) {
+ return (Session) cache.get(sessionId);
+ }
+
+ /**
+ * Caches the specified session under the key <code>sessionId</code>. If the Session is an instance of
+ * {@link org.jsecurity.session.mgt.ValidatingSession ValidatingSession}, it will only be cached if the
+ * session is {@link org.jsecurity.session.mgt.ValidatingSession#isValid() valid}.
+ *
+ * @param session the session to cache
+ * @param sessionId the id of the session, to be used as the cache key.
+ */
+ protected void cacheValidSession(Session session, Serializable sessionId) {
+ if (session == null || sessionId == null) {
+ return;
+ }
+
+ Cache cache = getActiveSessionsCacheLazy();
+ if (cache == null) {
+ return;
+ }
+
+ if (session instanceof ValidatingSession && !((ValidatingSession) session).isValid()) {
+ uncache(session);
+ } else {
+ cache(session, sessionId, cache);
+ }
+ }
+
+ /**
+ * Caches the specified session in the given cache under the key of <code>sessionId</code>. This implementation
+ * simply calls <code>cache.put(sessionId, session)</code> and can be overridden for custom behavior.
+ *
+ * @param session the session to cache
+ * @param sessionId the id of the session, expected to be the cache key.
+ * @param cache the cache to store the session
+ */
+ protected void cache(Session session, Serializable sessionId, Cache cache) {
+ cache.put(sessionId, session);
+ }
+
+ /**
+ * Ensures the sessionId returned from the subclass implementation of {@link #doCreate} is not null and not
+ * already in use.
+ *
+ * @param sessionId session id returned from the subclass implementation of {@link #doCreate}
+ */
+ protected void verifySessionId(Serializable sessionId) {
+ if (sessionId == null) {
+ String msg = "sessionId returned from doCreate implementation is null. Please verify the implementation.";
+ throw new IllegalStateException(msg);
+ }
+ ensureUncached(sessionId);
+ }
+
+ /**
+ * Ensures that there is no cache entry already in place for a session with id of <tt>sessionId</tt>. Used by
+ * the {@link #verifySessionId} implementation.
+ *
+ * @param sessionId the session id to check for non-existence in the cache.
+ */
+ protected void ensureUncached(Serializable sessionId) {
+ Cache cache = getActiveSessionsCacheLazy();
+ if (cache != null && cache.get(sessionId) != null) {
+ String msg = "There is an existing session already created with session id [" +
+ sessionId + "]. Session ID's must be unique.";
+ throw new IllegalArgumentException(msg);
+ }
+ }
+
+ /**
+ * Subclass hook to actually persist the given <tt>Session</tt> instance to the underlying EIS.
+ *
+ * @param session the Session instance to persist to the EIS.
+ * @return the id of the session created in the EIS (i.e. this is almost always a primary key and should be the
+ * value returned from {@link org.jsecurity.session.Session#getId() Session.getId()}.
+ */
+ protected abstract Serializable doCreate(Session session);
+
+ /**
+ * Retrieves the Session object from the underlying EIS identified by <tt>sessionId</tt>.
+ *
+ * <p>Upon receiving the Session object from the subclass's {@link #doReadSession} implementation, it will be
+ * cached first and then returned to the caller.
+ *
+ * @param sessionId the id of the session to retrieve from the EIS.
+ * @return the session identified by <tt>sessionId</tt> in the EIS.
+ * @throws UnknownSessionException if the id specified does not correspond to any session in the cache or EIS.
+ */
+ public Session readSession(Serializable sessionId) throws UnknownSessionException {
+
+ Session s = getCachedSession(sessionId);
+
+ if (s == null) {
+ s = doReadSession(sessionId);
+ if (s != null) {
+ cacheValidSession(s, sessionId);
+ }
+ }
+
+ if (s == null) {
+ throw new UnknownSessionException("There is no session with id [" + sessionId + "]");
+ }
+ return s;
+ }
+
+ /**
+ * Subclass implmentation hook to actually retrieve the Session object from the underlying EIS.
+ *
+ * @param sessionId the id of the <tt>Session</tt> to retrieve.
+ * @return the Session in the EIS identified by <tt>sessionId</tt>
+ */
+ protected abstract Session doReadSession(Serializable sessionId);
+
+ /**
+ * Updates the state of the given session to the EIS.
+ *
+ * <p>If the specified session was previously cached, and the session is now invalid,
+ * it will be removed from the cache.
+ *
+ * <p>If the specified session is not stopped or expired, and was not yet in the cache, it will be added to the
+ * cache.
+ *
+ * <p>Finally, this method calls {@link #doUpdate} for the subclass to actually push the object state to the EIS.
+ *
+ * @param session the session object to update in the EIS.
+ * @throws UnknownSessionException if no existing EIS session record exists with the
+ * identifier of {@link Session#getId() session.getId()}
+ */
+ public void update(Session session) throws UnknownSessionException {
+ doUpdate(session);
+ cacheValidSession(session, session.getId());
+ }
+
+ /**
+ * Subclass implementation hook to actually persist the <tt>Session</tt>'s state to the underlying EIS.
+ *
+ * @param session the session object whose state will be propagated to the EIS.
+ */
+ protected abstract void doUpdate(Session session);
+
+ /**
+ * Removes the specified session from any cache and then permanently deletes the session from the EIS by
+ * delegating to {@link #doDelete}.
+ *
+ * @param session the session to remove from caches and permanently delete from the EIS.
+ */
+ public void delete(Session session) {
+ doDelete(session);
+ uncache(session);
+ }
+
+ /**
+ * Subclass implementation hook to permanently delete the given Session from the underlying EIS.
+ *
+ * @param session the session instance to permanently delete from the EIS.
+ */
+ protected abstract void doDelete(Session session);
+
+ /**
+ * Removes the specified Session from the cache.
+ *
+ * @param session the session to remove from the cache.
+ */
+ protected void uncache(Session session) {
+ if (session == null) {
+ return;
+ }
+ Serializable id = session.getId();
+ if (id == null) {
+ return;
+ }
+ Cache cache = getActiveSessionsCacheLazy();
+ if (cache != null) {
+ cache.remove(id);
+ }
+ }
+
+ /**
+ * Returns all active sessions in the system.
+ *
+ * <p>This implementation merely returns the sessions found in the activeSessions cache. Subclass implementations
+ * may wish to override this method to retrieve them in a different way, perhaps by an RDBMS query or by other
+ * means.
+ *
+ * @return the sessions found in the activeSessions cache.
+ */
+ @SuppressWarnings({"unchecked"})
+ public Collection<Session> getActiveSessions() {
+ Cache cache = getActiveSessionsCacheLazy();
+ if (cache != null) {
+ return cache.values();
+ } else {
+ return Collections.EMPTY_LIST;
+ }
+ }
+}
diff --git a/core/src/org/jsecurity/session/mgt/eis/MemorySessionDAO.java b/core/src/org/jsecurity/session/mgt/eis/MemorySessionDAO.java
new file mode 100644
index 0000000..4867fba
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/eis/MemorySessionDAO.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt.eis;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.cache.HashtableCacheManager;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.mgt.SimpleSession;
+import org.jsecurity.util.JavaEnvironment;
+
+import java.io.Serializable;
+import java.util.Random;
+
+/**
+ * Simple memory-based implementation of the SessionDAO that relies on its configured
+ * {@link #setCacheManager CacheManager} for Session caching and in-memory persistence.
+ *
+ * <p><b>PLEASE NOTE</b> the default CacheManager internal to this implementation is a
+ * {@link org.jsecurity.cache.HashtableCacheManager HashtableCacheManager}, which IS NOT RECOMMENDED for production environments.
+ *
+ * <p>If you
+ * want to use the MemorySessionDAO in production environments, such as those that require session data to be
+ * recoverable in case of a server restart, you should do one of two things (or both):
+ *
+ * <ul>
+ * <li>Configure it with a production-quality CacheManager. The
+ * {@link org.jsecurity.cache.ehcache.EhCacheManager EhCacheManager} is one such implementation. It is not used by default
+ * to prevent a forced runtime dependency on ehcache.jar that may not be required in many environments)</li><br/>
+ * <li>If you need session information beyond their transient start/stop lifetimes, you should subclass this one and
+ * override the <tt>do*</tt> methods to perform CRUD operations using an EIS-tier API (e.g. Hibernate/JPA/JCR/etc).
+ * This class implementation does not retain sessions after they have been stopped or expired, so you would need to
+ * override these methods to ensure Sessions can be accessed beyond JSecurity's needs.</li>
+ * </ul>
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class MemorySessionDAO extends CachingSessionDAO {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(MemorySessionDAO.class);
+
+ private static final String RANDOM_NUM_GENERATOR_ALGORITHM_NAME = "SHA1PRNG";
+ private Random randomNumberGenerator = null;
+
+ public MemorySessionDAO() {
+ setCacheManager(new HashtableCacheManager());
+ }
+
+ private Random getRandomNumberGenerator() {
+ if (randomNumberGenerator == null) {
+ if (log.isInfoEnabled()) {
+ String msg = "On Java 1.4 platforms and below, there is no built-in UUID class (Java 1.5 and above " +
+ "only) to use for Session ID generation - reverting to SecureRandom number generator. " +
+ "Although this is probably sufficient for all but high user volume applications, if you " +
+ "see ID collision, you will want to upgrade to JDK 1.5 or better as soon as possible, or " +
+ "subclass the " + getClass().getName() + " class and override the #generateNewSessionId() " +
+ "method to use a better algorithm.";
+ log.info(msg);
+ }
+
+ try {
+ randomNumberGenerator = java.security.SecureRandom.getInstance(RANDOM_NUM_GENERATOR_ALGORITHM_NAME);
+ } catch (java.security.NoSuchAlgorithmException e) {
+ randomNumberGenerator = new java.security.SecureRandom();
+ }
+ }
+ return randomNumberGenerator;
+ }
+
+ protected Serializable generateNewSessionId() {
+ if (JavaEnvironment.isAtLeastVersion15()) {
+ return java.util.UUID.randomUUID().toString();
+ } else {
+ return Long.toString(getRandomNumberGenerator().nextLong());
+ }
+ }
+
+ protected Serializable doCreate(Session session) {
+ Serializable sessionId = generateNewSessionId();
+ assignSessionId(session, sessionId);
+ return sessionId;
+ }
+
+ protected void assignSessionId(Session session, Serializable sessionId) {
+ ((SimpleSession) session).setId(sessionId);
+ }
+
+ protected Session doReadSession(Serializable sessionId) {
+ return null; //should never execute because this implementation relies on parent class to access cache, which
+ //is where all sessions reside - it is the cache implementation that determines if the
+ //cache is memory only or disk-persistent, etc.
+ }
+
+ protected void doUpdate(Session session) {
+ //does nothing - parent class persists to cache.
+ }
+
+ protected void doDelete(Session session) {
+ //does nothing - parent class removes from cache.
+ }
+}
diff --git a/core/src/org/jsecurity/session/mgt/eis/SessionDAO.java b/core/src/org/jsecurity/session/mgt/eis/SessionDAO.java
new file mode 100644
index 0000000..f92346b
--- /dev/null
+++ b/core/src/org/jsecurity/session/mgt/eis/SessionDAO.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.session.mgt.eis;
+
+import org.jsecurity.session.Session;
+import org.jsecurity.session.UnknownSessionException;
+
+import java.io.Serializable;
+import java.util.Collection;
+
+/**
+ * Data Access Object design pattern specification to enable {@link Session} access to an
+ * EIS (Enterprise Information System).
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public interface SessionDAO {
+
+ /**
+ * Inserts a new Session record into the underling EIS (e.g. Relational database, file system, mainframe,
+ * etc, depending on the DAO implementation).
+ * <p/>
+ * After this method is invoked, the {@link org.jsecurity.session.Session#getId()}
+ * method executed on the argument must return a valid session identifier. That is, the following should
+ * always be true:
+ * <p/>
+ * <code>Serializable id = create( session );<br/>
+ * id.equals( session.getId() ) == true</code>
+ *
+ * <p>Implementations are free to throw any exceptions that might occur due to
+ * integrity violation constraints or other EIS related errors.
+ *
+ * @param session the {@link Session} object to create in the EIS.
+ * @return the EIS id (e.g. primary key) of the created <tt>Session</tt> object.
+ */
+ Serializable create(Session session);
+
+ /**
+ * Retrieves the session from the EIS uniquely identified by the specified
+ * <tt>sessionId</tt>.
+ *
+ * @param sessionId the system-wide unique identifier of the Session object to retrieve from
+ * the EIS.
+ * @return the persisted session in the EIS identified by <tt>sessionId</tt>.
+ * @throws UnknownSessionException if there is no EIS record for any session with the
+ * specified <tt>sessionId</tt>
+ */
+ Session readSession(Serializable sessionId) throws UnknownSessionException;
+
+ /**
+ * Updates (persists) data from a previously created Session instance in the EIS identified by
+ * <tt>{@link Session#getId() session.getId()}</tt>. This effectively propagates
+ * the data in the argument to the EIS record previously saved.
+ *
+ * <p>Aside from the UnknownSessionException, implementations are free to throw any other
+ * exceptions that might occur due to integrity violation constraints or other EIS related
+ * errors.
+ *
+ * @param session the Session to update
+ * @throws UnknownSessionException if no existing EIS session record exists with the
+ * identifier of {@link Session#getId() session.getSessionId()}
+ */
+ void update(Session session) throws UnknownSessionException;
+
+ /**
+ * Deletes the associated EIS record of the specified <tt>session</tt>. If there never
+ * existed a session EIS record with the identifier of
+ * {@link Session#getId() session.getId()}, then this method does nothing.
+ *
+ * @param session the session to delete.
+ */
+ void delete(Session session);
+
+ /**
+ * Returns all sessions in the EIS that are considered active, meaning all sessions that
+ * haven't been stopped/expired. This is primarily used to validate potential orphans.
+ *
+ * If there are no active sessions in the EIS, this method may return an empty collection
+ * or <tt>null</tt>.
+ *
+ * @return a Collection of <tt>Session</tt>s that are considered active, or an
+ * empty collection or <tt>null</tt> if there are no active sessions.
+ */
+ Collection<Session> getActiveSessions();
+}
diff --git a/core/src/org/jsecurity/subject/AbstractRememberMeManager.java b/core/src/org/jsecurity/subject/AbstractRememberMeManager.java
new file mode 100644
index 0000000..d417266
--- /dev/null
+++ b/core/src/org/jsecurity/subject/AbstractRememberMeManager.java
@@ -0,0 +1,276 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.RememberMeAuthenticationToken;
+import org.jsecurity.codec.Base64;
+import org.jsecurity.codec.Hex;
+import org.jsecurity.crypto.BlowfishCipher;
+import org.jsecurity.crypto.Cipher;
+import org.jsecurity.io.DefaultSerializer;
+import org.jsecurity.io.SerializationException;
+import org.jsecurity.io.Serializer;
+
+/**
+ * Abstract implementation of the <code>RememberMeManager</code> interface that handles
+ * {@link #setSerializer(org.jsecurity.io.Serializer) serialization} and
+ * {@link #setCipher(org.jsecurity.crypto.Cipher) encryption} of the remembered user identity.
+ * <p/>
+ * The remembered identity storage location is implementation-specific.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public abstract class AbstractRememberMeManager implements RememberMeManager {
+
+ //TODO - complete JavaDoc
+
+ /** private inner log instance. */
+ private static final Log log = LogFactory.getLog(AbstractRememberMeManager.class);
+
+ private Serializer serializer = new DefaultSerializer();
+ private Cipher cipher = new BlowfishCipher();
+ private byte[] encryptionCipherKey = null;
+ private byte[] decryptionCipherKey = null;
+
+ public AbstractRememberMeManager() {
+ }
+
+ public Serializer getSerializer() {
+ return serializer;
+ }
+
+ public void setSerializer(Serializer serializer) {
+ this.serializer = serializer;
+ }
+
+ public Cipher getCipher() {
+ return cipher;
+ }
+
+ public void setCipher(Cipher cipher) {
+ this.cipher = cipher;
+ }
+
+ public byte[] getEncryptionCipherKey() {
+ return encryptionCipherKey;
+ }
+
+ public void setEncryptionCipherKey(byte[] encryptionCipherKey) {
+ this.encryptionCipherKey = encryptionCipherKey;
+ }
+
+ public void setEncryptionCipherKeyHex(String hex) {
+ setEncryptionCipherKey(Hex.decode(hex));
+ }
+
+ public void setEncryptionCipherKeyBase64(String base64) {
+ setEncryptionCipherKey(Base64.decode(base64));
+ }
+
+ public byte[] getDecryptionCipherKey() {
+ return decryptionCipherKey;
+ }
+
+ public void setDecryptionCipherKey(byte[] decryptionCipherKey) {
+ this.decryptionCipherKey = decryptionCipherKey;
+ }
+
+ public void setDecryptionCipherKeyHex(String hex) {
+ setDecryptionCipherKey(Hex.decode(hex));
+ }
+
+ public void setDecryptionCipherKeyBase64(String base64) {
+ setDecryptionCipherKey(Base64.decode(base64));
+ }
+
+ public byte[] getCipherKey() {
+ //Since this method should only be used with symmetric ciphers
+ //(where the enc and dec keys are the same), either is fine, just return one of them:
+ return getEncryptionCipherKey();
+ }
+
+ public void setCipherKey(byte[] cipherKey) {
+ //Since this method should only be used in symmetric ciphers
+ //(where the enc and dec keys are the same), set it on both:
+ setEncryptionCipherKey(cipherKey);
+ setDecryptionCipherKey(cipherKey);
+ }
+
+ public void setCipherKeyHex(String hex) {
+ setCipherKey(Hex.decode(hex));
+ }
+
+ public void setCipherKeyBase64(String base64) {
+ setCipherKey(Base64.decode(base64));
+ }
+
+ // Abstract methods to be implemented by subclasses
+ protected abstract void rememberSerializedIdentity(byte[] serialized);
+
+ protected abstract byte[] getSerializedRememberedIdentity();
+
+ protected abstract void forgetIdentity();
+
+
+ protected boolean isRememberMe(AuthenticationToken token) {
+ return token != null && (token instanceof RememberMeAuthenticationToken) &&
+ ((RememberMeAuthenticationToken) token).isRememberMe();
+ }
+
+ public void onSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info) {
+ //always clear any previous identity:
+ forgetIdentity(token);
+
+ //reset it if necessary:
+ if (isRememberMe(token)) {
+ rememberIdentity(token, info);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("AuthenticationToken did not indicate RememberMe is requested. " +
+ "RememberMe functionality will not be executed for corresponding account.");
+ }
+ }
+ }
+
+ public void rememberIdentity(AuthenticationToken submittedToken, AuthenticationInfo successfullyAuthenticated) {
+ rememberIdentity(successfullyAuthenticated);
+ }
+
+ public void rememberIdentity(AuthenticationInfo successfullyAuthenticated) {
+ PrincipalCollection principals = getIdentityToRemember(successfullyAuthenticated);
+ rememberIdentity(principals);
+ }
+
+ protected PrincipalCollection getIdentityToRemember(AuthenticationInfo info) {
+ return info.getPrincipals();
+ }
+
+ protected void rememberIdentity(PrincipalCollection accountPrincipals) {
+ try {
+ byte[] bytes = serialize(accountPrincipals);
+ if (getCipher() != null) {
+ bytes = encrypt(bytes);
+ }
+ rememberSerializedIdentity(bytes);
+ } catch (SerializationException se) {
+ if (log.isWarnEnabled()) {
+ log.warn("Unable to serialize account principals [" + accountPrincipals + "]. Identity " +
+ "cannot be remembered! This is a non fatal exception as RememberMe identity services " +
+ "are not considered critical and execution can continue as normal. But please " +
+ "investigate and resolve to prevent seeing this message again.", se);
+ }
+ }
+ }
+
+ public PrincipalCollection getRememberedPrincipals() {
+ try {
+
+ PrincipalCollection principals = null;
+ byte[] bytes = getSerializedRememberedIdentity();
+ if (bytes != null) {
+ if (getCipher() != null) {
+ bytes = decrypt(bytes);
+ }
+ try {
+ principals = deserialize(bytes);
+ } catch (SerializationException e) {
+ if (log.isWarnEnabled()) {
+ log.warn("Unable to deserialize stored identity byte array. Remembered identity " +
+ "cannot be reconstituted! This is a non fatal exception as RememberMe identity services " +
+ "are not considered critical and execution can continue as normal, but please " +
+ "investigate and resolve to prevent seeing this message again.", e);
+ }
+ }
+ }
+ return principals;
+
+ } catch( Exception e ) {
+ return onRememberedPrincipalFailure( e );
+ }
+ }
+
+ /**
+ * Called when an exception is thrown while trying to retrieve principals. The default implementation logs a
+ * warning and forgets the problem identity. This most commonly would occur when an encryption key is
+ * updated and old principals are retrieved that have been encrypted with the previous key.
+ * @param e the exception that was thrown.
+ * @return the principal collection to be returned.
+ */
+ protected PrincipalCollection onRememberedPrincipalFailure(Exception e) {
+ if(log.isWarnEnabled() ) {
+ log.warn("There was a failure while trying to retrieve remembered principals. This could be due to a " +
+ "configuration problem or corrupted principals. This could also be due to a recently " +
+ "changed encryption key. The remembered identity will be forgotten and not used for this " +
+ "request.", e);
+ }
+ forgetIdentity();
+ return null;
+ }
+
+ protected byte[] encrypt(byte[] serialized) {
+ byte[] value = serialized;
+ Cipher cipher = getCipher();
+ if (cipher != null) {
+ value = cipher.encrypt(serialized, getEncryptionCipherKey());
+ }
+ return value;
+ }
+
+ protected byte[] decrypt(byte[] encrypted) {
+ byte[] serialized = encrypted;
+ Cipher cipher = getCipher();
+ if (cipher != null) {
+ serialized = cipher.decrypt(encrypted, getDecryptionCipherKey());
+ }
+ return serialized;
+ }
+
+
+ protected byte[] serialize(PrincipalCollection principals) {
+ return getSerializer().serialize(principals);
+ }
+
+ protected PrincipalCollection deserialize(byte[] serializedIdentity) {
+ return (PrincipalCollection) getSerializer().deserialize(serializedIdentity);
+ }
+
+ public void onFailedLogin(AuthenticationToken token, AuthenticationException ae) {
+ forgetIdentity(token, ae);
+ }
+
+ public void onLogout(PrincipalCollection subjectPrincipals) {
+ forgetIdentity();
+ }
+
+ protected void forgetIdentity(AuthenticationToken token, AuthenticationException ae) {
+ forgetIdentity(token);
+ }
+
+ protected void forgetIdentity(AuthenticationToken token) {
+ forgetIdentity();
+ }
+
+}
diff --git a/core/src/org/jsecurity/subject/DelegatingSubject.java b/core/src/org/jsecurity/subject/DelegatingSubject.java
new file mode 100644
index 0000000..3288c0c
--- /dev/null
+++ b/core/src/org/jsecurity/subject/DelegatingSubject.java
@@ -0,0 +1,323 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.InetAuthenticationToken;
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.Permission;
+import org.jsecurity.authz.UnauthenticatedException;
+import org.jsecurity.mgt.SecurityManager;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.ProxiedSession;
+import org.jsecurity.session.Session;
+import org.jsecurity.util.ThreadContext;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Implementation of the <tt>Subject</tt> interface that delegates
+ * method calls to an underlying {@link org.jsecurity.mgt.SecurityManager SecurityManager} instance for security checks.
+ * It is essentially a <tt>SecurityManager</tt> proxy.
+ * <p/>
+ * This implementation does not maintain state such as roles and permissions (only <code>Subject</code>
+ * {@link #getPrincipals() principals}, such as usernames or user primary keys) for better performance in a stateless
+ * architecture. It instead asks the underlying <tt>SecurityManager</tt> every time to perform
+ * the authorization check.
+ * <p/>
+ * A common misconception in using this implementation is that an EIS resource (RDBMS, etc) would
+ * be "hit" every time a method is called. This is not necessarily the case and is
+ * up to the implementation of the underlying <tt>SecurityManager</tt> instance. If caching of authorization
+ * data is desired (to eliminate EIS round trips and therefore improve database performance), it is considered
+ * much more elegant to let the underlying <tt>SecurityManager</tt> implementation or its delegate components
+ * manage caching, not this class. A <tt>SecurityManager</tt> is considered a business-tier component,
+ * where caching strategies are better suited.
+ * <p/>
+ * Applications from large and clustered to simple and vm local all benefit from
+ * stateless architectures. This implementation plays a part in the stateless programming
+ * paradigm and should be used whenever possible.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public class DelegatingSubject implements Subject {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(DelegatingSubject.class);
+
+ protected PrincipalCollection principals = new SimplePrincipalCollection();
+ protected boolean authenticated = false;
+ protected InetAddress inetAddress = null;
+ protected Session session = null;
+
+ protected SecurityManager securityManager;
+
+ protected static InetAddress getLocalHost() {
+ try {
+ return InetAddress.getLocalHost();
+ } catch (UnknownHostException e) {
+ return null;
+ }
+ }
+
+ public DelegatingSubject(SecurityManager securityManager) {
+ this(null, false, getLocalHost(), null, securityManager);
+ }
+
+ public DelegatingSubject(PrincipalCollection principals, boolean authenticated, InetAddress inetAddress,
+ Session session, SecurityManager securityManager) {
+ if (securityManager == null) {
+ throw new IllegalArgumentException("SecurityManager argument cannot be null.");
+ }
+ this.securityManager = securityManager;
+ this.principals = principals;
+
+ this.authenticated = authenticated;
+
+ if (inetAddress != null) {
+ this.inetAddress = inetAddress;
+ } else {
+ this.inetAddress = getLocalHost();
+ }
+ if (session != null) {
+ this.session = new StoppingAwareProxiedSession(session, this);
+ }
+ }
+
+ public org.jsecurity.mgt.SecurityManager getSecurityManager() {
+ return securityManager;
+ }
+
+ protected boolean hasPrincipals() {
+ PrincipalCollection pc = getPrincipals();
+ return pc != null && !pc.isEmpty();
+ }
+
+ /**
+ * Returns the InetAddress associated with the client who created/is interacting with this Subject.
+ *
+ * @return the InetAddress associated with the client who created/is interacting with this Subject.
+ */
+ public InetAddress getInetAddress() {
+ return this.inetAddress;
+ }
+
+ /**
+ * @see Subject#getPrincipal()
+ */
+ public Object getPrincipal() {
+ PrincipalCollection principals = getPrincipals();
+ if (principals == null || principals.isEmpty()) {
+ return null;
+ }
+ return principals.asSet().iterator().next();
+ }
+
+ public PrincipalCollection getPrincipals() {
+ return this.principals;
+ }
+
+ public boolean isPermitted(String permission) {
+ return hasPrincipals() && securityManager.isPermitted(getPrincipals(), permission);
+ }
+
+ public boolean isPermitted(Permission permission) {
+ return hasPrincipals() && securityManager.isPermitted(getPrincipals(), permission);
+ }
+
+ public boolean[] isPermitted(String... permissions) {
+ if (hasPrincipals()) {
+ return securityManager.isPermitted(getPrincipals(), permissions);
+ } else {
+ return new boolean[permissions.length];
+ }
+ }
+
+ public boolean[] isPermitted(List<Permission> permissions) {
+ if (hasPrincipals()) {
+ return securityManager.isPermitted(getPrincipals(), permissions);
+ } else {
+ return new boolean[permissions.size()];
+ }
+ }
+
+ public boolean isPermittedAll(String... permissions) {
+ return hasPrincipals() && securityManager.isPermittedAll(getPrincipals(), permissions);
+ }
+
+ public boolean isPermittedAll(Collection<Permission> permissions) {
+ return hasPrincipals() && securityManager.isPermittedAll(getPrincipals(), permissions);
+ }
+
+ protected void assertAuthzCheckPossible() throws AuthorizationException {
+ if (!hasPrincipals()) {
+ String msg = "Identity principals are not associated with this Subject instance - " +
+ "authorization operations require an identity to check against. A Subject instance will " +
+ "acquire these identifying principals automatically after a successful login is performed " +
+ "be executing " + Subject.class.getName() + ".login(AuthenticationToken) or when 'Remember Me' " +
+ "functionality is enabled. This exception can also occur when the current Subject has logged out, " +
+ "which relinquishes its identity and essentially makes it anonymous again. " +
+ "Because an identity is currently not known due to any of these conditions, " +
+ "authorization is denied.";
+ throw new UnauthenticatedException(msg);
+ }
+ }
+
+ public void checkPermission(String permission) throws AuthorizationException {
+ assertAuthzCheckPossible();
+ securityManager.checkPermission(getPrincipals(), permission);
+ }
+
+ public void checkPermission(Permission permission) throws AuthorizationException {
+ assertAuthzCheckPossible();
+ securityManager.checkPermission(getPrincipals(), permission);
+ }
+
+ public void checkPermissions(String... permissions)
+ throws AuthorizationException {
+ assertAuthzCheckPossible();
+ securityManager.checkPermissions(getPrincipals(), permissions);
+ }
+
+ public void checkPermissions(Collection<Permission> permissions)
+ throws AuthorizationException {
+ assertAuthzCheckPossible();
+ securityManager.checkPermissions(getPrincipals(), permissions);
+ }
+
+ public boolean hasRole(String roleIdentifier) {
+ return hasPrincipals() && securityManager.hasRole(getPrincipals(), roleIdentifier);
+ }
+
+ public boolean[] hasRoles(List<String> roleIdentifiers) {
+ if (hasPrincipals()) {
+ return securityManager.hasRoles(getPrincipals(), roleIdentifiers);
+ } else {
+ return new boolean[roleIdentifiers.size()];
+ }
+ }
+
+ public boolean hasAllRoles(Collection<String> roleIdentifiers) {
+ return hasPrincipals() && securityManager.hasAllRoles(getPrincipals(), roleIdentifiers);
+ }
+
+ public void checkRole(String role) throws AuthorizationException {
+ assertAuthzCheckPossible();
+ securityManager.checkRole(getPrincipals(), role);
+ }
+
+ public void checkRoles(Collection<String> roles) throws AuthorizationException {
+ assertAuthzCheckPossible();
+ securityManager.checkRoles(getPrincipals(), roles);
+ }
+
+ public void login(AuthenticationToken token) throws AuthenticationException {
+ Subject authcSecCtx = securityManager.login(token);
+ PrincipalCollection principals = authcSecCtx.getPrincipals();
+ if (principals == null || principals.isEmpty()) {
+ String msg = "Principals returned from securityManager.login( token ) returned a null or " +
+ "empty value. This value must be non null and populated with one or more elements. " +
+ "Please check the SecurityManager implementation to ensure this happens after a " +
+ "successful login attempt.";
+ throw new IllegalStateException(msg);
+ }
+ this.principals = principals;
+ Session session = authcSecCtx.getSession(false);
+ if (session != null) {
+ if (session instanceof StoppingAwareProxiedSession) {
+ this.session = session;
+ } else {
+ this.session = new StoppingAwareProxiedSession(session, this);
+ }
+ } else {
+ this.session = null;
+ }
+ this.authenticated = true;
+ if (token instanceof InetAuthenticationToken) {
+ InetAddress addy = ((InetAuthenticationToken) token).getInetAddress();
+ if (addy != null) {
+ this.inetAddress = addy;
+ }
+ }
+ ThreadContext.bind(this);
+ }
+
+ public boolean isAuthenticated() {
+ return authenticated;
+ }
+
+ public Session getSession() {
+ return getSession(true);
+ }
+
+ public Session getSession(boolean create) {
+ if (log.isTraceEnabled()) {
+ log.trace("attempting to get session; create = " + create + "; session is null = " + (this.session == null) + "; session has id = " + (this.session != null && session.getId() != null));
+ }
+
+ if (this.session == null && create) {
+ if (log.isTraceEnabled()) {
+ log.trace("starting session for address [" + getInetAddress() + "]");
+ }
+ Session target = securityManager.start(getInetAddress());
+ this.session = new StoppingAwareProxiedSession(target, this);
+ }
+ return this.session;
+ }
+
+ public void logout() {
+ try {
+ this.securityManager.logout(getPrincipals());
+ } finally {
+ this.session = null;
+ this.principals = null;
+ this.authenticated = false;
+ this.inetAddress = null;
+ this.securityManager = null;
+ }
+ }
+
+ private void sessionStopped() {
+ this.session = null;
+ }
+
+ private class StoppingAwareProxiedSession extends ProxiedSession {
+
+ private final DelegatingSubject owner;
+
+ private StoppingAwareProxiedSession(Session target, DelegatingSubject owningSubject) {
+ super(target);
+ owner = owningSubject;
+ }
+
+ public void stop() throws InvalidSessionException {
+ super.stop();
+ owner.sessionStopped();
+ }
+ }
+
+}
diff --git a/core/src/org/jsecurity/subject/InvalidSubjectException.java b/core/src/org/jsecurity/subject/InvalidSubjectException.java
new file mode 100644
index 0000000..d2ea9b6
--- /dev/null
+++ b/core/src/org/jsecurity/subject/InvalidSubjectException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+/**
+ * Exception thrown when a <tt>Subject</tt> is accessed that has been invalidated. Usually this occurs
+ * when accessing a <tt>Subject</tt> whose {@link Subject#logout()} method
+ * has been called.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class InvalidSubjectException extends SubjectException {
+
+ /**
+ * Creates a new InvalidSubjectException.
+ */
+ public InvalidSubjectException() {
+ super();
+ }
+
+ /**
+ * Constructs a new InvalidSubjectException.
+ *
+ * @param message the reason for the exception
+ */
+ public InvalidSubjectException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new InvalidSubjectException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public InvalidSubjectException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new InvalidSubjectException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public InvalidSubjectException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/subject/MutablePrincipalCollection.java b/core/src/org/jsecurity/subject/MutablePrincipalCollection.java
new file mode 100644
index 0000000..363a010
--- /dev/null
+++ b/core/src/org/jsecurity/subject/MutablePrincipalCollection.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import java.util.Collection;
+
+/**
+ * A {@link PrincipalCollection} that allows modification.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface MutablePrincipalCollection extends PrincipalCollection {
+
+ /**
+ * Adds the given principal to this collection.
+ *
+ * @param principal the principal to be added.
+ * @param realmName the realm this principal came from.
+ */
+ void add(Object principal, String realmName);
+
+ /**
+ * Adds all of the principals in the given collection to this collection.
+ *
+ * @param principals the principals to be added.
+ * @param realmName the realm these principals came from.
+ */
+ void addAll(Collection principals, String realmName);
+
+ /**
+ * Adds all of the principals from the given principal collection to this collection.
+ *
+ * @param principals the principals to add.
+ */
+ void addAll(PrincipalCollection principals);
+
+ /**
+ * Removes all Principals in this collection.
+ */
+ void clear();
+}
diff --git a/core/src/org/jsecurity/subject/PrincipalCollection.java b/core/src/org/jsecurity/subject/PrincipalCollection.java
new file mode 100644
index 0000000..e5d5d16
--- /dev/null
+++ b/core/src/org/jsecurity/subject/PrincipalCollection.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A collection of all principals associated with a corresponding {@link Subject Subject}.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface PrincipalCollection extends Iterable, Serializable {
+
+ /**
+ * Returns a single principal assignable from the specified type, or <tt>null</tt> if there are none of the
+ * specified type.
+ *
+ * <p>Note that this would return <code>null</code> List always if the corresponding subject has not logged in.</p>
+ *
+ * @param type the type of the principal that should be returned.
+ * @return a principal of the specified type or <tt>null</tt> if there isn't one of the specified type.
+ */
+ <T> T oneByType(Class<T> type);
+
+ /**
+ * Returns all principals assignable from the specified type, or an empty Collection if no principals of that
+ * type are contained.
+ *
+ * <p>Note that this would return an empty Collection always if the corresponding subject has not logged in.</p>
+ *
+ * @param type the type of the principals that should be returned.
+ * @return a Collection of principals that are assignable from the specified type, or
+ * an empty Collection if no principals of this type are associated.
+ */
+ <T> Collection<T> byType(Class<T> type);
+
+ /**
+ * Returns a single Subject's principals retrieved from all configured Realms as a List, or an empty List if
+ * there are not any principals.
+ *
+ * <p>Note that this would return an empty List always if the corresponding subject has not logged in.</p>
+ *
+ * @return a single Subject's principals retrieved from all configured Realms as a List.
+ */
+ List asList();
+
+ /**
+ * Returns a single Subject's principals retrieved from all configured Realms as a Set, or an empty Set if there
+ * are not any principals.
+ *
+ * <p>Note that this would return an empty Set always if the corresponding subject has not logged in.</p>
+ *
+ * @return a single Subject's principals retrieved from all configured Realms as a Set.
+ */
+ Set asSet();
+
+ /**
+ * Returns a single Subject's principals retrieved from the specified Realm <em>only</em> as a Collection, or an empty
+ * Collection if there are not any principals from that realm.
+ *
+ * <p>Note that this would return an empty Collection always if the corresponding subject has not logged in.</p>
+ *
+ * @param realmName the name of the Realm from which the principals were retrieved.
+ * @return the Subject's principals from the specified Realm only as a Collection or an empty Collection if there
+ * are not any principals from that realm.
+ */
+ Collection fromRealm(String realmName);
+
+ /**
+ * Returns the realm names that this collection has principals for.
+ *
+ * @return the names of realms that this collection has one or more principals for.
+ */
+ Set<String> getRealmNames();
+
+ /**
+ * Returns <code>true</code> if this collection is empty, <code>false</code> otherwise.
+ *
+ * @return <code>true</code> if this collection is empty, <code>false</code> otherwise.
+ */
+ boolean isEmpty();
+}
diff --git a/core/src/org/jsecurity/subject/RememberMeManager.java b/core/src/org/jsecurity/subject/RememberMeManager.java
new file mode 100644
index 0000000..eebba0b
--- /dev/null
+++ b/core/src/org/jsecurity/subject/RememberMeManager.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationInfo;
+import org.jsecurity.authc.AuthenticationToken;
+
+/**
+ * A RememberMeManager is responsible for remembering a Subject's identity across that Subject's sessions with
+ * the application.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface RememberMeManager {
+
+ //TODO - complete JavaDoc
+
+ PrincipalCollection getRememberedPrincipals();
+
+ void onSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info);
+
+ void onFailedLogin(AuthenticationToken token, AuthenticationException ae);
+
+ void onLogout(PrincipalCollection subjectPrincipals);
+}
diff --git a/core/src/org/jsecurity/subject/SimplePrincipalCollection.java b/core/src/org/jsecurity/subject/SimplePrincipalCollection.java
new file mode 100644
index 0000000..47dada4
--- /dev/null
+++ b/core/src/org/jsecurity/subject/SimplePrincipalCollection.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import java.util.*;
+
+/**
+ * A simple implementation of the {@link MutablePrincipalCollection} interface that tracks principals internally
+ * by storing them in a {@link LinkedHashMap}.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+@SuppressWarnings({"unchecked"})
+public class SimplePrincipalCollection implements MutablePrincipalCollection {
+
+ //TODO - complete JavaDoc
+
+ private Map<String, Set> realmPrincipals;
+
+ public SimplePrincipalCollection() {
+ }
+
+ public SimplePrincipalCollection(Object principal, String realmName) {
+ if (principal instanceof Collection) {
+ addAll((Collection) principal, realmName);
+ } else {
+ add(principal, realmName);
+ }
+ }
+
+ public SimplePrincipalCollection(Collection principals, String realmName) {
+ addAll(principals, realmName);
+ }
+
+ public SimplePrincipalCollection(PrincipalCollection principals) {
+ addAll(principals);
+ }
+
+ protected Collection getPrincipalsLazy(String realmName) {
+ if (realmPrincipals == null) {
+ realmPrincipals = new LinkedHashMap<String, Set>();
+ }
+ Set principals = realmPrincipals.get(realmName);
+ if (principals == null) {
+ principals = new LinkedHashSet();
+ realmPrincipals.put(realmName, principals);
+ }
+ return principals;
+ }
+
+ public void add(Object principal, String realmName) {
+ if (realmName == null) {
+ throw new IllegalArgumentException("realmName argument cannot be null.");
+ }
+ if (principal == null) {
+ throw new IllegalArgumentException("principal argument cannot be null.");
+ }
+ getPrincipalsLazy(realmName).add(principal);
+ }
+
+ public void addAll(Collection principals, String realmName) {
+ if (realmName == null) {
+ throw new IllegalArgumentException("realmName argument cannot be null.");
+ }
+ if (principals == null) {
+ throw new IllegalArgumentException("principals argument cannot be null.");
+ }
+ if (principals.isEmpty()) {
+ throw new IllegalArgumentException("principals argument cannot be an empty collection.");
+ }
+ getPrincipalsLazy(realmName).addAll(principals);
+ }
+
+ public void addAll(PrincipalCollection principals) {
+ if (principals.getRealmNames() != null) {
+ for (String realmName : principals.getRealmNames()) {
+ for (Object principal : principals.fromRealm(realmName)) {
+ add(principal, realmName);
+ }
+ }
+ }
+ }
+
+ public <T> T oneByType(Class<T> type) {
+ if (realmPrincipals == null || realmPrincipals.isEmpty()) {
+ return null;
+ }
+ Collection<Set> values = realmPrincipals.values();
+ for (Set set : values) {
+ for (Object o : set) {
+ if (type.isAssignableFrom(o.getClass())) {
+ return (T) o;
+ }
+ }
+ }
+ return null;
+ }
+
+ public <T> Collection<T> byType(Class<T> type) {
+ if (realmPrincipals == null || realmPrincipals.isEmpty()) {
+ return Collections.EMPTY_SET;
+ }
+ Set<T> typed = new LinkedHashSet<T>();
+ Collection<Set> values = realmPrincipals.values();
+ for (Set set : values) {
+ for (Object o : set) {
+ if (type.isAssignableFrom(o.getClass())) {
+ typed.add((T) o);
+ }
+ }
+ }
+ if (typed.isEmpty()) {
+ return Collections.EMPTY_SET;
+ }
+ return Collections.unmodifiableSet(typed);
+ }
+
+ public List asList() {
+ Set all = asSet();
+ if (all.isEmpty()) {
+ return Collections.EMPTY_LIST;
+ }
+ return Collections.unmodifiableList(new ArrayList(all));
+ }
+
+ public Set asSet() {
+ if (realmPrincipals == null || realmPrincipals.isEmpty()) {
+ return Collections.EMPTY_SET;
+ }
+ Set aggregated = new LinkedHashSet();
+ Collection<Set> values = realmPrincipals.values();
+ for (Set set : values) {
+ aggregated.addAll(set);
+ }
+ if (aggregated.isEmpty()) {
+ return Collections.EMPTY_SET;
+ }
+ return Collections.unmodifiableSet(aggregated);
+ }
+
+ public Collection fromRealm(String realmName) {
+ if (realmPrincipals == null || realmPrincipals.isEmpty()) {
+ return Collections.EMPTY_SET;
+ }
+ Set principals = realmPrincipals.get(realmName);
+ if (principals == null || principals.isEmpty()) {
+ principals = Collections.EMPTY_SET;
+ }
+ return Collections.unmodifiableSet(principals);
+ }
+
+ public Set<String> getRealmNames() {
+ if (realmPrincipals == null) {
+ return null;
+ } else {
+ return realmPrincipals.keySet();
+ }
+ }
+
+ public boolean isEmpty() {
+ return realmPrincipals == null || realmPrincipals.isEmpty();
+ }
+
+ public void clear() {
+ if (realmPrincipals != null) {
+ realmPrincipals.clear();
+ realmPrincipals = null;
+ }
+ }
+
+ public Iterator iterator() {
+ return asSet().iterator();
+ }
+
+ public boolean equals(Object o) {
+ if (o == this) {
+ return true;
+ }
+ if (o instanceof SimplePrincipalCollection) {
+ SimplePrincipalCollection other = (SimplePrincipalCollection) o;
+ return this.realmPrincipals != null ? this.realmPrincipals.equals(other.realmPrincipals) : other.realmPrincipals == null;
+ }
+ return false;
+ }
+
+ public int hashCode() {
+ if (this.realmPrincipals != null && !realmPrincipals.isEmpty()) {
+ return realmPrincipals.hashCode();
+ }
+ return super.hashCode();
+ }
+}
diff --git a/core/src/org/jsecurity/subject/Subject.java b/core/src/org/jsecurity/subject/Subject.java
new file mode 100644
index 0000000..834a804
--- /dev/null
+++ b/core/src/org/jsecurity/subject/Subject.java
@@ -0,0 +1,364 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.Permission;
+import org.jsecurity.session.Session;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * A <tt>Subject</tt> represents state and security operations for a <em>single</em> application user.
+ * These operations include authentication (login/logout), authorization (access control), and
+ * session access. It is JSecurity's primary mechanism for single-user security functionality.
+ *
+ * <p>Note that there are many *Permission methods in this interface overloaded to accept String arguments instead of
+ * {@link Permission Permission} instances. They are a convenience allowing the caller to use a String representation of
+ * a {@link Permission Permission} if desired. The underlying Authorization subsystem implementations will usually
+ * simply convert these String values to {@link Permission Permission} instances and then just call the corresponding
+ * type-safe method. (JSecurity's default implementations do String-to-Permission conversion for these methods using
+ * {@link org.jsecurity.authz.permission.PermissionResolver PermissionResolver}s.)
+ *
+ * <p>These overloaded *Permission methods <em>do</em> forego type-saftey for the benefit of convenience and simplicity,
+ * so you should choose which ones to use based on your preferences and needs.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public interface Subject {
+
+ /**
+ * Returns this Subject's uniquely-identifying principal, or <tt>null</tt> if this
+ * Subject doesn't yet have account data associated with it (for example, if they haven't logged in).
+ *
+ * <p>The term <em>principal</em> is just a fancy security term for any identifying attribute(s) of an application
+ * user, such as a username, or user id, or public key, or anything else you might use in your application to
+ * identify a user. And although given names and family names (first/last) are technically principals as well,
+ * JSecurity expects the object(s) returned from this method to be uniquely identifying attibute(s) for
+ * your application. This implies that things like given names and family names are usually poor candidates as
+ * return values since they are rarely guaranteed to be unique.</p>
+ *
+ * <p>Most single-Realm applications would return from this method a single unique principal as noted above
+ * (for example a String username or Long user id, etc, etc). Single-realm applications represent the large
+ * majority of JSecurity applications.</p>
+ *
+ * <p>However, in <em>multi</em>-Realm configurations, which are fully supported by JSecurity as well, it is
+ * possible that the return value encapsulates more than one principal. Typically multi-realm applications need to
+ * retain the unique principals for <em>each</em> Realm so subsequent security checks against these Realms can
+ * utilize these multiple principals. In these cases, the object returned could be a Collection or any
+ * application-specific instance that encapsulates the principals.</p>
+ *
+ * @return this Subject's application-specific identity.
+ */
+ Object getPrincipal();
+
+
+ /**
+ * Returns all of this Subject's principals (identifying attributes) in the form of a <code>PrincipalCollection</code>.
+ * <p/>
+ * The word "principals" is nothing more than a fancy security term for identifying attributes associated
+ * with a Subject, aka, application user. For example, user id, a surname (family/last name), given (first) name,
+ * social security number, nickname, username, etc, are all examples of a principal.
+ * <p/>
+ * This method returns all of the principals associated with the Subject, and it is expected that at least one of
+ * the principals contained within this collection represent an absolute unique identifier for the application.
+ * User IDs, such a <code>Long</code> database primary key or UUID, or maybe a globally unique username or email
+ * address are all good candidates for such a unique identifier. Non-unique things, such as surnames and
+ * given names, are often poor candidates.
+ * <p/>
+ * For convenience's sake, it is convention that the first principal in this collection be the application's
+ * "primary" principal. That is, <code>getPrincipals().iterator().next();</code> would return this
+ * primary uniquely-identifying principal.
+ * In fact, this logic is often the implementation of the {@link #getPrincipal() getPrincipal()} method.
+ *
+ * @return all of this Subject's principals (identifying attributes).
+ * @see #getPrincipal()
+ */
+ PrincipalCollection getPrincipals();
+
+
+ /**
+ * Returns <tt>true</tt> if this Subject is permitted to perform an action or access a resource summarized by the
+ * specified permission string.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param permission the String representation of a Permission that is being checked.
+ * @return true if this Subject is permitted, false otherwise.
+ * @see #isPermitted(Permission permission)
+ * @since 0.9
+ */
+ boolean isPermitted(String permission);
+
+ /**
+ * Returns <tt>true</tt> if this Subject is permitted to perform an action or access a resource summarized by the
+ * specified permission.
+ *
+ * <p>More specifically, this method determines if any <tt>Permission</tt>s associated
+ * with the subject {@link Permission#implies(Permission) imply} the specified permission.
+ *
+ * @param permission the permission that is being checked.
+ * @return true if this Subject is permitted, false otherwise.
+ */
+ boolean isPermitted(Permission permission);
+
+ /**
+ * Checks if this Subject implies the given permission strings and returns a boolean array indicating which
+ * permissions are implied.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param permissions the String representations of the Permissions that are being checked.
+ * @return an array of booleans whose indices correspond to the index of the
+ * permissions in the given list. A true value at an index indicates this Subject is permitted for
+ * for the associated <tt>Permission</tt> string in the list. A false value at an index
+ * indicates otherwise.
+ * @since 0.9
+ */
+ boolean[] isPermitted(String... permissions);
+
+ /**
+ * Checks if this Subject implies the given Permissions and returns a boolean array indicating which permissions
+ * are implied.
+ *
+ * <p>More specifically, this method should determine if each <tt>Permission</tt> in
+ * the array is {@link Permission#implies(Permission) implied} by permissions
+ * already associated with the subject.
+ *
+ * <p>This is primarily a performance-enhancing method to help reduce the number of
+ * {@link #isPermitted} invocations over the wire in client/server systems.
+ *
+ * @param permissions the permissions that are being checked.
+ * @return an array of booleans whose indices correspond to the index of the
+ * permissions in the given list. A true value at an index indicates this Subject is permitted for
+ * for the associated <tt>Permission</tt> object in the list. A false value at an index
+ * indicates otherwise.
+ */
+ boolean[] isPermitted(List<Permission> permissions);
+
+ /**
+ * Returns <tt>true</tt> if this Subject implies all of the specified permission strings, <tt>false</tt> otherwise.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param permissions the String representations of the Permissions that are being checked.
+ * @return true if this Subject has all of the specified permissions, false otherwise.
+ * @see #isPermittedAll(Collection)
+ * @since 0.9
+ */
+ boolean isPermittedAll(String... permissions);
+
+ /**
+ * Returns <tt>true</tt> if this Subject implies all of the specified permissions, <tt>false</tt> otherwise.
+ *
+ * <p>More specifically, this method determines if all of the given <tt>Permission</tt>s are
+ * {@link Permission#implies(Permission) implied by} permissions already associated with this Subject.
+ *
+ * @param permissions the permissions to check.
+ * @return true if this Subject has all of the specified permissions, false otherwise.
+ */
+ boolean isPermittedAll(Collection<Permission> permissions);
+
+ /**
+ * Ensures this Subject implies the specified permission String.
+ *
+ * <p>If this subject's existing associated permissions do not {@link Permission#implies(Permission)} imply}
+ * the given permission, an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param permission the String representation of the Permission to check.
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the user does not have the permission.
+ * @since 0.9
+ */
+ void checkPermission(String permission) throws AuthorizationException;
+
+ /**
+ * Ensures this Subject {@link Permission#implies(Permission) implies} the specified <tt>Permission</tt>.
+ *
+ * <p>If this subject's exisiting associated permissions do not {@link Permission#implies(Permission) imply}
+ * the given permission, an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * @param permission the Permission to check.
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if this Subject does not have the permission.
+ */
+ void checkPermission(Permission permission) throws AuthorizationException;
+
+ /**
+ * Ensures this Subject
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) implies} all of the
+ * specified permission strings.
+ *
+ * If this subject's exisiting associated permissions do not
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) imply} all of the given permissions,
+ * an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * <p>This is an overloaded method for the corresponding type-safe {@link Permission Permission} variant.
+ * Please see the class-level JavaDoc for more information on these String-based permission methods.
+ *
+ * @param permissions the string representations of Permissions to check.
+ * @throws AuthorizationException if this Subject does not have all of the given permissions.
+ * @since 0.9
+ */
+ void checkPermissions(String... permissions) throws AuthorizationException;
+
+ /**
+ * Ensures this Subject
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) implies} all of the
+ * specified permission strings.
+ *
+ * If this subject's exisiting associated permissions do not
+ * {@link org.jsecurity.authz.Permission#implies(org.jsecurity.authz.Permission) imply} all of the given permissions,
+ * an {@link org.jsecurity.authz.AuthorizationException} will be thrown.
+ *
+ * @param permissions the Permissions to check.
+ * @throws AuthorizationException if this Subject does not have all of the given permissions.
+ */
+ void checkPermissions(Collection<Permission> permissions) throws AuthorizationException;
+
+ /**
+ * Returns <tt>true</tt> if this Subject has the specified role, <tt>false</tt> otherwise.
+ *
+ * @param roleIdentifier the application-specific role identifier (usually a role id or role name).
+ * @return <tt>true</tt> if this Subject has the specified role, <tt>false</tt> otherwise.
+ */
+ boolean hasRole(String roleIdentifier);
+
+ /**
+ * Checks if this Subject has the specified roles, returning a boolean array indicating
+ * which roles are associated.
+ *
+ * <p>This is primarily a performance-enhancing method to help reduce the number of
+ * {@link #hasRole} invocations over the wire in client/server systems.
+ *
+ * @param roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
+ * @return an array of booleans whose indices correspond to the index of the
+ * roles in the given identifiers. A true value indicates this Subject has the
+ * role at that index. False indicates this Subject does not have the role at that index.
+ */
+ boolean[] hasRoles(List<String> roleIdentifiers);
+
+ /**
+ * Returns <tt>true</tt> if this Subject has all of the specified roles, <tt>false</tt> otherwise.
+ *
+ * @param roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
+ * @return true if this Subject has all the roles, false otherwise.
+ */
+ boolean hasAllRoles(Collection<String> roleIdentifiers);
+
+ /**
+ * Asserts this Subject has the specified role by returning quietly if they do or throwing an
+ * {@link org.jsecurity.authz.AuthorizationException} if they do not.
+ *
+ * @param roleIdentifier the application-specific role identifier (usually a role id or role name ).
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if this Subject does not have the role.
+ */
+ void checkRole(String roleIdentifier) throws AuthorizationException;
+
+ /**
+ * Asserts this Subject has all of the specified roles by returning quietly if they do or throwing an
+ * {@link org.jsecurity.authz.AuthorizationException} if they do not.
+ *
+ * @param roleIdentifiers the application-specific role identifiers to check (usually role ids or role names).
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if this Subject does not have all of the specified roles.
+ */
+ void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException;
+
+ /**
+ * Performs a login attempt for this Subject/user. If unsuccessful,
+ * an {@link AuthenticationException} is thrown, the subclass of which identifies why the attempt failed.
+ * If successful, the account data associated with the submitted principals/credentials will be
+ * associated with this <tt>Subject</tt> and the method will return quietly.
+ *
+ * <p>Upon returninq quietly, this <tt>Subject</tt> instance can be considered
+ * authenticated and {@link #getPrincipal() getPrincipal()} will be non-null and
+ * {@link #isAuthenticated() isAuthenticated()} will be <tt>true</tt>.
+ *
+ * @param token the token encapsulating the subject's principals and credentials to be passed to the
+ * Authentication subsystem for verification.
+ * @throws AuthenticationException if the authentication attempt fails.
+ * @since 0.9
+ */
+ void login(AuthenticationToken token) throws AuthenticationException;
+
+ /**
+ * Returns <tt>true</tt> if this Subject/user has proven their identity <em>during their current session</em>
+ * by providing valid credentials matching those known to the system, <tt>false</tt> otherwise.
+ *
+ * <p>Note that even if this Subject's identity has been remembered via 'remember me' services, this method will
+ * still return <tt>false</tt> unless the user has actually logged in with proper credentials <em>during their
+ * current session</em>. See the
+ * {@link org.jsecurity.authc.RememberMeAuthenticationToken RememberMeAuthenticationToken} class JavaDoc for why
+ * this would occur.</p>
+ *
+ * @return <tt>true</tt> if this Subject has proven their identity during their current session
+ * by providing valid credentials matching those known to the system, <tt>false</tt> otherwise.
+ * @since 0.9
+ */
+ boolean isAuthenticated();
+
+ /**
+ * Returns the application <tt>Session</tt> associated with this Subject. If no session exists when this
+ * method is called, a new session will be created, associated with this Subject, and then returned.
+ *
+ * @return the application <tt>Session</tt> associated with this Subject.
+ * @see #getSession(boolean)
+ * @since 0.2
+ */
+ Session getSession();
+
+ /**
+ * Returns the application <tt>Session</tt> associated with this Subject. Based on the boolean argument,
+ * this method functions as follows:
+ *
+ * <ul>
+ * <li>If there is already an existing session associated with this <tt>Subject</tt>, it is returned and
+ * the <tt>create</tt> argument is ignored.</li>
+ * <li>If no session exists and <tt>create</tt> is <tt>true</tt>, a new session will be created, associated with
+ * this <tt>Subject</tt> and then returned.</li>
+ * <li>If no session exists and <tt>create</tt> is <tt>false</tt>, <tt>null</tt> is returned.</li>
+ * </ul>
+ *
+ * @param create boolean argument determining if a new session should be created or not if there is no existing session.
+ * @return the application <tt>Session</tt> associated with this <tt>Subject</tt> or <tt>null</tt> based
+ * on the above described logic.
+ * @since 0.2
+ */
+ Session getSession(boolean create);
+
+ /**
+ * Logs out this Subject and invalidates and/or removes any associated entities
+ * (such as a {@link Session Session} and authorization data.
+ */
+ void logout();
+
+}
diff --git a/core/src/org/jsecurity/subject/SubjectException.java b/core/src/org/jsecurity/subject/SubjectException.java
new file mode 100644
index 0000000..8ab36cc
--- /dev/null
+++ b/core/src/org/jsecurity/subject/SubjectException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * Throws when there is an error accessing or interacting with a {@link Subject}.
+ *
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public class SubjectException extends JSecurityException {
+
+ /**
+ * Creates a new SubjectException.
+ */
+ public SubjectException() {
+ super();
+ }
+
+ /**
+ * Constructs a new SubjectException.
+ *
+ * @param message the reason for the exception
+ */
+ public SubjectException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new SubjectException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public SubjectException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new SubjectException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public SubjectException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
\ No newline at end of file
diff --git a/core/src/org/jsecurity/util/AntPathMatcher.java b/core/src/org/jsecurity/util/AntPathMatcher.java
new file mode 100644
index 0000000..b928b98
--- /dev/null
+++ b/core/src/org/jsecurity/util/AntPathMatcher.java
@@ -0,0 +1,428 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+/**
+ * <p>PathMatcher implementation for Ant-style path patterns.
+ * Examples are provided below.</p>
+ *
+ * <p>Part of this mapping code has been kindly borrowed from
+ * <a href="http://ant.apache.org">Apache Ant</a>.
+ *
+ * <p>The mapping matches URLs using the following rules:<br>
+ * <ul>
+ * <li>? matches one character</li>
+ * <li>* matches zero or more characters</li>
+ * <li>** matches zero or more 'directories' in a path</li>
+ * </ul>
+ *
+ * <p>Some examples:<br>
+ * <ul>
+ * <li><code>com/t?st.jsp</code> - matches <code>com/test.jsp</code> but also
+ * <code>com/tast.jsp</code> or <code>com/txst.jsp</code></li>
+ * <li><code>com/*.jsp</code> - matches all <code>.jsp</code> files in the
+ * <code>com</code> directory</li>
+ * <li><code>com/**/test.jsp</code> - matches all <code>test.jsp</code>
+ * files underneath the <code>com</code> path</li>
+ * <li><code>org/jsecurity/**/*.jsp</code> - matches all <code>.jsp</code>
+ * files underneath the <code>org/jsecurity</code> path</li>
+ * <li><code>org/**/servlet/bla.jsp</code> - matches
+ * <code>org/jsecurity/servlet/bla.jsp</code> but also
+ * <code>org/jsecurity/testing/servlet/bla.jsp</code> and
+ * <code>org/servlet/bla.jsp</code></li>
+ * </ul>
+ *
+ * <p><b>N.B.</b>: This class was borrowed (with much appreciation) from the
+ * <a href="http://www.springframework.org">Spring Framework</a> with modifications. We didn't want to reinvent the
+ * wheel of great work they've done, but also didn't want to force every JSecurity user to depend on Spring</p>
+ *
+ * <p>As per the Apache 2.0 license, the original copyright notice and all author and copyright information have
+ * remained in tact.</p>
+ *
+ * @author Alef Arendsen
+ * @author Juergen Hoeller
+ * @author Rob Harrop
+ * @since 16.07.2003
+ */
+public class AntPathMatcher implements PatternMatcher {
+
+ //TODO - complete JavaDoc
+
+ /**
+ * Default path separator: "/"
+ */
+ public static final String DEFAULT_PATH_SEPARATOR = "/";
+
+ private String pathSeparator = DEFAULT_PATH_SEPARATOR;
+
+
+ /**
+ * Set the path separator to use for pattern parsing.
+ * Default is "/", as in Ant.
+ */
+ public void setPathSeparator(String pathSeparator) {
+ this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR);
+ }
+
+
+ public boolean isPattern(String path) {
+ return (path.indexOf('*') != -1 || path.indexOf('?') != -1);
+ }
+
+ public boolean matches(String pattern, String source) {
+ return match(pattern, source);
+ }
+
+ public boolean match(String pattern, String path) {
+ return doMatch(pattern, path, true);
+ }
+
+ public boolean matchStart(String pattern, String path) {
+ return doMatch(pattern, path, false);
+ }
+
+
+ /**
+ * Actually match the given <code>path</code> against the given <code>pattern</code>.
+ *
+ * @param pattern the pattern to match against
+ * @param path the path String to test
+ * @param fullMatch whether a full pattern match is required
+ * (else a pattern match as far as the given base path goes is sufficient)
+ * @return <code>true</code> if the supplied <code>path</code> matched,
+ * <code>false</code> if it didn't
+ */
+ protected boolean doMatch(String pattern, String path, boolean fullMatch) {
+ if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) {
+ return false;
+ }
+
+ String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
+ String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator);
+
+ int pattIdxStart = 0;
+ int pattIdxEnd = pattDirs.length - 1;
+ int pathIdxStart = 0;
+ int pathIdxEnd = pathDirs.length - 1;
+
+ // Match all elements up to the first **
+ while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
+ String patDir = pattDirs[pattIdxStart];
+ if ("**".equals(patDir)) {
+ break;
+ }
+ if (!matchStrings(patDir, pathDirs[pathIdxStart])) {
+ return false;
+ }
+ pattIdxStart++;
+ pathIdxStart++;
+ }
+
+ if (pathIdxStart > pathIdxEnd) {
+ // Path is exhausted, only match if rest of pattern is * or **'s
+ if (pattIdxStart > pattIdxEnd) {
+ return (pattern.endsWith(this.pathSeparator) ?
+ path.endsWith(this.pathSeparator) : !path.endsWith(this.pathSeparator));
+ }
+ if (!fullMatch) {
+ return true;
+ }
+ if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") &&
+ path.endsWith(this.pathSeparator)) {
+ return true;
+ }
+ for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
+ if (!pattDirs[i].equals("**")) {
+ return false;
+ }
+ }
+ return true;
+ } else if (pattIdxStart > pattIdxEnd) {
+ // String not exhausted, but pattern is. Failure.
+ return false;
+ } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
+ // Path start definitely matches due to "**" part in pattern.
+ return true;
+ }
+
+ // up to last '**'
+ while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
+ String patDir = pattDirs[pattIdxEnd];
+ if (patDir.equals("**")) {
+ break;
+ }
+ if (!matchStrings(patDir, pathDirs[pathIdxEnd])) {
+ return false;
+ }
+ pattIdxEnd--;
+ pathIdxEnd--;
+ }
+ if (pathIdxStart > pathIdxEnd) {
+ // String is exhausted
+ for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
+ if (!pattDirs[i].equals("**")) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
+ int patIdxTmp = -1;
+ for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
+ if (pattDirs[i].equals("**")) {
+ patIdxTmp = i;
+ break;
+ }
+ }
+ if (patIdxTmp == pattIdxStart + 1) {
+ // '**/**' situation, so skip one
+ pattIdxStart++;
+ continue;
+ }
+ // Find the pattern between padIdxStart & padIdxTmp in str between
+ // strIdxStart & strIdxEnd
+ int patLength = (patIdxTmp - pattIdxStart - 1);
+ int strLength = (pathIdxEnd - pathIdxStart + 1);
+ int foundIdx = -1;
+
+ strLoop:
+ for (int i = 0; i <= strLength - patLength; i++) {
+ for (int j = 0; j < patLength; j++) {
+ String subPat = (String) pattDirs[pattIdxStart + j + 1];
+ String subStr = (String) pathDirs[pathIdxStart + i + j];
+ if (!matchStrings(subPat, subStr)) {
+ continue strLoop;
+ }
+ }
+ foundIdx = pathIdxStart + i;
+ break;
+ }
+
+ if (foundIdx == -1) {
+ return false;
+ }
+
+ pattIdxStart = patIdxTmp;
+ pathIdxStart = foundIdx + patLength;
+ }
+
+ for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
+ if (!pattDirs[i].equals("**")) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Tests whether or not a string matches against a pattern.
+ * The pattern may contain two special characters:<br>
+ * '*' means zero or more characters<br>
+ * '?' means one and only one character
+ *
+ * @param pattern pattern to match against.
+ * Must not be <code>null</code>.
+ * @param str string which must be matched against the pattern.
+ * Must not be <code>null</code>.
+ * @return <code>true</code> if the string matches against the
+ * pattern, or <code>false</code> otherwise.
+ */
+ private boolean matchStrings(String pattern, String str) {
+ char[] patArr = pattern.toCharArray();
+ char[] strArr = str.toCharArray();
+ int patIdxStart = 0;
+ int patIdxEnd = patArr.length - 1;
+ int strIdxStart = 0;
+ int strIdxEnd = strArr.length - 1;
+ char ch;
+
+ boolean containsStar = false;
+ for (char aPatArr : patArr) {
+ if (aPatArr == '*') {
+ containsStar = true;
+ break;
+ }
+ }
+
+ if (!containsStar) {
+ // No '*'s, so we make a shortcut
+ if (patIdxEnd != strIdxEnd) {
+ return false; // Pattern and string do not have the same size
+ }
+ for (int i = 0; i <= patIdxEnd; i++) {
+ ch = patArr[i];
+ if (ch != '?') {
+ if (ch != strArr[i]) {
+ return false;// Character mismatch
+ }
+ }
+ }
+ return true; // String matches against pattern
+ }
+
+
+ if (patIdxEnd == 0) {
+ return true; // Pattern contains only '*', which matches anything
+ }
+
+ // Process characters before first star
+ while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {
+ if (ch != '?') {
+ if (ch != strArr[strIdxStart]) {
+ return false;// Character mismatch
+ }
+ }
+ patIdxStart++;
+ strIdxStart++;
+ }
+ if (strIdxStart > strIdxEnd) {
+ // All characters in the string are used. Check if only '*'s are
+ // left in the pattern. If so, we succeeded. Otherwise failure.
+ for (int i = patIdxStart; i <= patIdxEnd; i++) {
+ if (patArr[i] != '*') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ // Process characters after last star
+ while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {
+ if (ch != '?') {
+ if (ch != strArr[strIdxEnd]) {
+ return false;// Character mismatch
+ }
+ }
+ patIdxEnd--;
+ strIdxEnd--;
+ }
+ if (strIdxStart > strIdxEnd) {
+ // All characters in the string are used. Check if only '*'s are
+ // left in the pattern. If so, we succeeded. Otherwise failure.
+ for (int i = patIdxStart; i <= patIdxEnd; i++) {
+ if (patArr[i] != '*') {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ // process pattern between stars. padIdxStart and patIdxEnd point
+ // always to a '*'.
+ while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
+ int patIdxTmp = -1;
+ for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
+ if (patArr[i] == '*') {
+ patIdxTmp = i;
+ break;
+ }
+ }
+ if (patIdxTmp == patIdxStart + 1) {
+ // Two stars next to each other, skip the first one.
+ patIdxStart++;
+ continue;
+ }
+ // Find the pattern between padIdxStart & padIdxTmp in str between
+ // strIdxStart & strIdxEnd
+ int patLength = (patIdxTmp - patIdxStart - 1);
+ int strLength = (strIdxEnd - strIdxStart + 1);
+ int foundIdx = -1;
+ strLoop:
+ for (int i = 0; i <= strLength - patLength; i++) {
+ for (int j = 0; j < patLength; j++) {
+ ch = patArr[patIdxStart + j + 1];
+ if (ch != '?') {
+ if (ch != strArr[strIdxStart + i + j]) {
+ continue strLoop;
+ }
+ }
+ }
+
+ foundIdx = strIdxStart + i;
+ break;
+ }
+
+ if (foundIdx == -1) {
+ return false;
+ }
+
+ patIdxStart = patIdxTmp;
+ strIdxStart = foundIdx + patLength;
+ }
+
+ // All characters in the string are used. Check if only '*'s are left
+ // in the pattern. If so, we succeeded. Otherwise failure.
+ for (int i = patIdxStart; i <= patIdxEnd; i++) {
+ if (patArr[i] != '*') {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Given a pattern and a full path, determine the pattern-mapped part.
+ * <p>For example:
+ * <ul>
+ * <li>'<code>/docs/cvs/commit.html</code>' and '<code>/docs/cvs/commit.html</code> -> ''</li>
+ * <li>'<code>/docs/*</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>
+ * <li>'<code>/docs/cvs/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>commit.html</code>'</li>
+ * <li>'<code>/docs/**</code>' and '<code>/docs/cvs/commit</code> -> '<code>cvs/commit</code>'</li>
+ * <li>'<code>/docs/**\/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>cvs/commit.html</code>'</li>
+ * <li>'<code>/*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>docs/cvs/commit.html</code>'</li>
+ * <li>'<code>*.html</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>
+ * <li>'<code>*</code>' and '<code>/docs/cvs/commit.html</code> -> '<code>/docs/cvs/commit.html</code>'</li>
+ * </ul>
+ * <p>Assumes that {@link #match} returns <code>true</code> for '<code>pattern</code>'
+ * and '<code>path</code>', but does <strong>not</strong> enforce this.
+ */
+ public String extractPathWithinPattern(String pattern, String path) {
+ String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
+ String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator);
+
+ StringBuffer buffer = new StringBuffer();
+
+ // Add any path parts that have a wildcarded pattern part.
+ int puts = 0;
+ for (int i = 0; i < patternParts.length; i++) {
+ String patternPart = patternParts[i];
+ if ((patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) && pathParts.length >= i + 1) {
+ if (puts > 0 || (i == 0 && !pattern.startsWith(this.pathSeparator))) {
+ buffer.append(this.pathSeparator);
+ }
+ buffer.append(pathParts[i]);
+ puts++;
+ }
+ }
+
+ // Append any trailing path parts.
+ for (int i = patternParts.length; i < pathParts.length; i++) {
+ if (puts > 0 || i > 0) {
+ buffer.append(this.pathSeparator);
+ }
+ buffer.append(pathParts[i]);
+ }
+
+ return buffer.toString();
+ }
+
+}
diff --git a/core/src/org/jsecurity/util/ClassUtils.java b/core/src/org/jsecurity/util/ClassUtils.java
new file mode 100644
index 0000000..b3be021
--- /dev/null
+++ b/core/src/org/jsecurity/util/ClassUtils.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.InputStream;
+import java.lang.reflect.Constructor;
+
+/**
+ * Utility method library used to conveniently interact with <code>Class</code>es, such as acquiring them from the
+ * application <code>ClassLoader</code>s and instantiating Objects from them.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class ClassUtils {
+
+ //TODO - complete JavaDoc
+
+ /** Private internal log instance. */
+ private static final Log log = LogFactory.getLog(ClassUtils.class);
+
+ /**
+ * Returns the specified resource by checking the current thread's
+ * {@link Thread#getContextClassLoader() context class loader}, then the
+ * current ClassLoader (<code>ClassUtils.class.getClassLoader()</code>), then the system/application
+ * ClassLoader (<code>ClassLoader.getSystemClassLoader()</code>, in that order, using
+ * {@link ClassLoader#getResourceAsStream(String) getResourceAsStream(name)}.
+ *
+ * @param name the name of the resource to acquire from the classloader(s).
+ * @return the InputStream of the resource found, or <code>null</code> if the resource cannot be found from any
+ * of the three mentioned ClassLoaders.
+ * @since 0.9
+ */
+ public static InputStream getResourceAsStream(String name) {
+ InputStream is = null;
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if (cl != null) {
+ is = cl.getResourceAsStream(name);
+ }
+
+ if (is == null) {
+ if (log.isTraceEnabled()) {
+ log.trace("Resource [" + name + "] was not found via the thread context ClassLoader. Trying the " +
+ "current ClassLoader...");
+ }
+ cl = ClassUtils.class.getClassLoader();
+ is = cl.getResourceAsStream(name);
+ if (is == null) {
+ if (log.isTraceEnabled()) {
+ log.trace("Resource [" + name + "] was not found via the current class loader. Trying the " +
+ "system/application ClassLoader...");
+ }
+ cl = ClassLoader.getSystemClassLoader();
+ is = cl.getResourceAsStream(name);
+ if (is == null && log.isTraceEnabled()) {
+ log.trace("Resource [" + name + "] was not found via the thread context, current, or " +
+ "system/application ClassLoaders. All heuristics have been exhausted. Returning null.");
+ }
+ }
+ }
+ return is;
+ }
+
+ /**
+ * Attempts to load the specified class name from the current thread's
+ * {@link Thread#getContextClassLoader() context class loader}, then the
+ * current ClassLoader (<code>ClassUtils.class.getClassLoader()</code>), then the system/application
+ * ClassLoader (<code>ClassLoader.getSystemClassLoader()</code>, in that order. If any of them cannot locate
+ * the specified class, an <code>UnknownClassException</code> is thrown (our RuntimeException equivalent of
+ * the JRE's <code>ClassNotFoundException</code>.
+ *
+ * @param fqcn the fully qualified class name to load
+ * @return the located class
+ * @throws UnknownClassException if the class cannot be found.
+ */
+ public static Class forName(String fqcn) throws UnknownClassException {
+ Class clazz = null;
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if (cl != null) {
+ try {
+ clazz = cl.loadClass(fqcn);
+ } catch (ClassNotFoundException e) {
+ if (log.isTraceEnabled()) {
+ log.trace("Unable to load class named [" + fqcn +
+ "] from the thread context ClassLoader. Trying the current ClassLoader...");
+ }
+ }
+ }
+ if (clazz == null) {
+ cl = ClassUtils.class.getClassLoader();
+ try {
+ clazz = cl.loadClass(fqcn);
+ } catch (ClassNotFoundException e1) {
+ if (log.isTraceEnabled()) {
+ log.trace("Unable to load class named [" + fqcn + "] from the current ClassLoader. " +
+ "Trying the system/application ClassLoader...");
+ }
+ cl = ClassLoader.getSystemClassLoader();
+ try {
+ clazz = cl.loadClass(fqcn);
+ } catch (ClassNotFoundException ignored) {
+ if (log.isTraceEnabled()) {
+ log.trace("Unable to load class named [" + fqcn + "] from the " +
+ "system/application ClassLoader.");
+ }
+ }
+ }
+ }
+
+ if (clazz == null) {
+ String msg = "Unable to load class named [" + fqcn + "] from the thread context, current, or " +
+ "system/application ClassLoaders. All heuristics have been exausted. Class could not be found.";
+ throw new UnknownClassException(msg);
+ }
+ return clazz;
+ }
+
+ public static boolean isAvailable(String fullyQualifiedClassName) {
+ try {
+ forName(fullyQualifiedClassName);
+ return true;
+ } catch (UnknownClassException e) {
+ return false;
+ }
+ }
+
+ public static Object newInstance(String fqcn) {
+ return newInstance(forName(fqcn));
+ }
+
+ public static Object newInstance(String fqcn, Object... args) {
+ return newInstance(forName(fqcn), args);
+ }
+
+ public static Object newInstance(Class clazz) {
+ if (clazz == null) {
+ String msg = "Class method parameter cannot be null.";
+ throw new IllegalArgumentException(msg);
+ }
+ try {
+ return clazz.newInstance();
+ } catch (Exception e) {
+ throw new org.jsecurity.util.InstantiationException("Unable to instantiate class [" + clazz.getName() + "]", e);
+ }
+ }
+
+ public static Object newInstance(Class clazz, Object... args) {
+ Class[] argTypes = new Class[args.length];
+ for (int i = 0; i < args.length; i++) {
+ argTypes[i] = args[i].getClass();
+ }
+ Constructor ctor = getConstructor(clazz, argTypes);
+ return instantiate(ctor, args);
+ }
+
+ public static Constructor getConstructor(Class clazz, Class... argTypes) {
+ try {
+ return clazz.getConstructor(argTypes);
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException(e);
+ }
+
+ }
+
+ public static Object instantiate(Constructor ctor, Object... args) {
+ try {
+ return ctor.newInstance(args);
+ } catch (Exception e) {
+ String msg = "Unable to instantiate Permission instance with constructor [" + ctor + "]";
+ throw new org.jsecurity.util.InstantiationException(msg, e);
+ }
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/util/CollectionUtils.java b/core/src/org/jsecurity/util/CollectionUtils.java
new file mode 100644
index 0000000..939a1b8
--- /dev/null
+++ b/core/src/org/jsecurity/util/CollectionUtils.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import java.util.*;
+
+/**
+ * Static helper class for use dealing with Arrays.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class CollectionUtils {
+
+ //TODO - complete JavaDoc
+
+ /**
+ * Simple method that just returns <code>Collections.EMPTY_SET</code>.
+ * This exists to enable type-safe empty collections so other locations in JSecurity code
+ * do not need to worry about suppressing warnings.
+ *
+ * @param clazz the class of the collection type to return
+ * @return an empty collection
+ */
+ @SuppressWarnings({"unchecked"})
+ public static <E> Collection<E> emptyCollection(Class<E> clazz) {
+ return Collections.EMPTY_SET;
+ }
+
+ @SuppressWarnings({"unchecked"})
+ public static <E> Set<E> asSet(E... elements) {
+ if (elements == null || elements.length == 0) {
+ return Collections.EMPTY_SET;
+ }
+ LinkedHashSet<E> set = new LinkedHashSet<E>(elements.length * 4 / 3 + 1);
+ Collections.addAll(set, elements);
+ return set;
+ }
+
+ @SuppressWarnings({"unchecked"})
+ public static <E> List<E> asList(E... elements) {
+ if (elements == null || elements.length == 0) {
+ return Collections.EMPTY_LIST;
+ }
+ // Avoid integer overflow when a large array is passed in
+ int capacity = computeListCapacity(elements.length);
+ ArrayList<E> list = new ArrayList<E>(capacity);
+ Collections.addAll(list, elements);
+ return list;
+ }
+
+ static int computeListCapacity(int arraySize) {
+ return (int) Math.min(5L + arraySize + (arraySize / 10), Integer.MAX_VALUE);
+ }
+}
diff --git a/core/src/org/jsecurity/util/Destroyable.java b/core/src/org/jsecurity/util/Destroyable.java
new file mode 100644
index 0000000..6547b12
--- /dev/null
+++ b/core/src/org/jsecurity/util/Destroyable.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+/**
+ * JSecurity container-agnostic interface that indicates that this object requires a callback during destruction.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @see org.jsecurity.spring.LifecycleBeanPostProcessor
+ * @since 0.2
+ */
+public interface Destroyable {
+
+ /**
+ * Called when this object is being destroyed, allowing any necessary cleanup of internal resources.
+ *
+ * @throws Exception if an exception occurs during object destruction.
+ */
+ void destroy() throws Exception;
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/src/org/jsecurity/util/Initializable.java
similarity index 61%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/src/org/jsecurity/util/Initializable.java
index 8e597f2..4d30d8f 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/src/org/jsecurity/util/Initializable.java
@@ -16,8 +16,25 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.util;
+
+import org.jsecurity.JSecurityException;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * JSecurity container-agnostic interface that indicates that this object requires initialization.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @see org.jsecurity.spring.LifecycleBeanPostProcessor
+ * @since 0.2
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public interface Initializable {
+
+ /**
+ * Initializes this object.
+ *
+ * @throws JSecurityException if an exception occurs during initialization.
+ */
+ void init() throws JSecurityException;
+
+}
diff --git a/core/src/org/jsecurity/util/InstantiationException.java b/core/src/org/jsecurity/util/InstantiationException.java
new file mode 100644
index 0000000..a25226f
--- /dev/null
+++ b/core/src/org/jsecurity/util/InstantiationException.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * Runtime exception thrown by the framework when unable to instantiate a Class via reflection.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class InstantiationException extends JSecurityException {
+
+ /**
+ * Creates a new InstantiationException.
+ */
+ public InstantiationException() {
+ super();
+ }
+
+ /**
+ * Constructs a new InstantiationException.
+ *
+ * @param message the reason for the exception
+ */
+ public InstantiationException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new InstantiationException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public InstantiationException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new InstantiationException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public InstantiationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/util/JavaEnvironment.java b/core/src/org/jsecurity/util/JavaEnvironment.java
new file mode 100644
index 0000000..c3eb5a3
--- /dev/null
+++ b/core/src/org/jsecurity/util/JavaEnvironment.java
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+/**
+ * Internal helper class used to find the Java/JDK version
+ * that JSecurity is operating within, to allow for automatically
+ * adapting to the present platform's capabilities.
+ *
+ * <p>Note that JSecurity does not support 1.2 or earlier JVMs - only 1.3 and later.
+ *
+ * <p><em>This class was borrowed and heavily based upon a nearly identical version found in
+ * the <a href="http://www.springframework.org/">Spring Framework</a>, with minor modifications.
+ * The original author names and copyright (Apache 2.0) has been left in place. A special
+ * thanks to Rod Johnson, Juergen Hoeller, and Rick Evans for making this available.</em>
+ *
+ * @author Rod Johnson
+ * @author Juergen Hoeller
+ * @author Rick Evans
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public abstract class JavaEnvironment {
+
+ /**
+ * Constant identifying the 1.3.x JVM (JDK 1.3).
+ */
+ public static final int JAVA_13 = 0;
+
+ /**
+ * Constant identifying the 1.4.x JVM (J2SE 1.4).
+ */
+ public static final int JAVA_14 = 1;
+
+ /**
+ * Constant identifying the 1.5 JVM (Java 5).
+ */
+ public static final int JAVA_15 = 2;
+
+ /**
+ * Constant identifying the 1.6 JVM (Java 6).
+ */
+ public static final int JAVA_16 = 3;
+
+ /**
+ * Constant identifying the 1.7 JVM.
+ */
+ public static final int JAVA_17 = 4;
+
+ /** The virtual machine version, i.e. <code>System.getProperty("java.version");</code>. */
+ private static final String version;
+
+ /**
+ * The virtual machine <em>major</em> version. For example, with a <code>version</code> of
+ * <code>1.5.6_10</code>, this would be <code>1.5</code>
+ */
+ private static final int majorVersion;
+
+ /**
+ * Static code initialization block that sets the
+ * <code>version</code> and <code>majorVersion</code> Class constants
+ * upon initialization.
+ */
+ static {
+ version = System.getProperty("java.version");
+ // version String should look like "1.4.2_10"
+ if (version.indexOf("1.7.") != -1) {
+ majorVersion = JAVA_17;
+ } else if (version.indexOf("1.6.") != -1) {
+ majorVersion = JAVA_16;
+ } else if (version.indexOf("1.5.") != -1) {
+ majorVersion = JAVA_15;
+ } else if (version.indexOf("1.4.") != -1) {
+ majorVersion = JAVA_14;
+ } else {
+ // else leave 1.3 as default (it's either 1.3 or unknown)
+ majorVersion = JAVA_13;
+ }
+ }
+
+
+ /**
+ * Return the full Java version string, as returned by
+ * <code>System.getProperty("java.version")</code>.
+ *
+ * @return the full Java version string
+ * @see System#getProperty(String)
+ */
+ public static String getVersion() {
+ return version;
+ }
+
+ /**
+ * Get the major version code. This means we can do things like
+ * <code>if (getMajorVersion() < JAVA_14)</code>.
+ *
+ * @return a code comparable to the JAVA_XX codes in this class
+ * @see #JAVA_13
+ * @see #JAVA_14
+ * @see #JAVA_15
+ * @see #JAVA_16
+ * @see #JAVA_17
+ */
+ public static int getMajorVersion() {
+ return majorVersion;
+ }
+
+ /**
+ * Convenience method to determine if the current JVM is at least Java 1.4.
+ *
+ * @return <code>true</code> if the current JVM is at least Java 1.4
+ * @see #getMajorVersion()
+ * @see #JAVA_14
+ * @see #JAVA_15
+ * @see #JAVA_16
+ * @see #JAVA_17
+ */
+ public static boolean isAtLeastVersion14() {
+ return getMajorVersion() >= JAVA_14;
+ }
+
+ /**
+ * Convenience method to determine if the current JVM is at least
+ * Java 1.5 (Java 5).
+ *
+ * @return <code>true</code> if the current JVM is at least Java 1.5
+ * @see #getMajorVersion()
+ * @see #JAVA_15
+ * @see #JAVA_16
+ * @see #JAVA_17
+ */
+ public static boolean isAtLeastVersion15() {
+ return getMajorVersion() >= JAVA_15;
+ }
+}
diff --git a/core/src/org/jsecurity/util/JdbcUtils.java b/core/src/org/jsecurity/util/JdbcUtils.java
new file mode 100644
index 0000000..0f34a23
--- /dev/null
+++ b/core/src/org/jsecurity/util/JdbcUtils.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+/**
+ * A set of static helper methods for managing JDBC API objects.
+ * <p/>
+ * <em>Note:</em> Some parts of this class were copied from the Spring Framework and then modified.
+ * They were copied here to prevent Spring dependencies in the JSecurity core API. The original license conditions
+ * (Apache 2.0) have been maintained.
+ *
+ * @author Jeremy Haile
+ * @since 0.2
+ */
+public class JdbcUtils {
+
+ /** Private internal log instance. */
+ private static final Log log = LogFactory.getLog(JdbcUtils.class);
+
+ /**
+ * Private constructor to prevent instantiation.
+ */
+ private JdbcUtils() {
+ }
+
+ /**
+ * Close the given JDBC Connection and ignore any thrown exception.
+ * This is useful for typical finally blocks in manual JDBC code.
+ *
+ * @param connection the JDBC Connection to close (may be <tt>null</tt>)
+ */
+ public static void closeConnection(Connection connection) {
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (SQLException ex) {
+ if (log.isDebugEnabled()) {
+ log.debug("Could not close JDBC Connection", ex);
+ }
+ } catch (Throwable ex) {
+ if (log.isDebugEnabled()) {
+ log.debug("Unexpected exception on closing JDBC Connection", ex);
+ }
+ }
+ }
+ }
+
+ /**
+ * Close the given JDBC Statement and ignore any thrown exception.
+ * This is useful for typical finally blocks in manual JDBC code.
+ *
+ * @param statement the JDBC Statement to close (may be <tt>null</tt>)
+ */
+ public static void closeStatement(Statement statement) {
+ if (statement != null) {
+ try {
+ statement.close();
+ } catch (SQLException ex) {
+ if (log.isDebugEnabled()) {
+ log.debug("Could not close JDBC Statement", ex);
+ }
+ } catch (Throwable ex) {
+ if (log.isDebugEnabled()) {
+ log.debug("Unexpected exception on closing JDBC Statement", ex);
+ }
+ }
+ }
+ }
+
+ /**
+ * Close the given JDBC ResultSet and ignore any thrown exception.
+ * This is useful for typical finally blocks in manual JDBC code.
+ *
+ * @param rs the JDBC ResultSet to close (may be <tt>null</tt>)
+ */
+ public static void closeResultSet(ResultSet rs) {
+ if (rs != null) {
+ try {
+ rs.close();
+ } catch (SQLException ex) {
+ if (log.isDebugEnabled()) {
+ log.debug("Could not close JDBC ResultSet", ex);
+ }
+ } catch (Throwable ex) {
+ if (log.isDebugEnabled()) {
+ log.debug("Unexpected exception on closing JDBC ResultSet", ex);
+ }
+ }
+ }
+ }
+
+}
diff --git a/core/src/org/jsecurity/util/LifecycleUtils.java b/core/src/org/jsecurity/util/LifecycleUtils.java
new file mode 100644
index 0000000..8a2fbe5
--- /dev/null
+++ b/core/src/org/jsecurity/util/LifecycleUtils.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.JSecurityException;
+
+import java.util.Collection;
+
+/**
+ * TODO - complete JavaDoc
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public abstract class LifecycleUtils {
+
+ private static final Log log = LogFactory.getLog(LifecycleUtils.class);
+
+ public static void init(Object o) throws JSecurityException {
+ if (o instanceof Initializable) {
+ init((Initializable) o);
+ }
+ }
+
+ public static void init(Initializable initializable) throws JSecurityException {
+ initializable.init();
+ }
+
+ /**
+ * @param c
+ * @throws JSecurityException
+ * @since 0.9
+ */
+ public static void init(Collection c) throws JSecurityException {
+ if (c == null || c.isEmpty()) {
+ return;
+ }
+ for (Object o : c) {
+ init(o);
+ }
+ }
+
+ public static void destroy(Object o) {
+ if (o instanceof Destroyable) {
+ destroy((Destroyable) o);
+ }
+ }
+
+ public static void destroy(Destroyable d) {
+ if (d != null) {
+ try {
+ d.destroy();
+ } catch (Throwable t) {
+ if (log.isDebugEnabled()) {
+ String msg = "Unable to cleanly destroy instance [" + d + "] of type [" + d.getClass().getName() + "].";
+ log.debug(msg, t);
+ }
+ }
+ }
+ }
+
+ /**
+ * Calls {@link #destroy(Object) destroy} for each object in the collection. If the collection is <code>null</code> or
+ * empty, this method returns quietly.
+ *
+ * @param c the collection of objects to destroy.
+ * @since 0.9
+ */
+ public static void destroy(Collection c) {
+ if (c == null || c.isEmpty()) {
+ return;
+ }
+
+ for (Object o : c) {
+ destroy(o);
+ }
+ }
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/src/org/jsecurity/util/Nameable.java
similarity index 64%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/src/org/jsecurity/util/Nameable.java
index 8e597f2..0cd324e 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/src/org/jsecurity/util/Nameable.java
@@ -16,8 +16,20 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.util;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * Interface implemented by components that can be named, such as via configuration, and wish to have that name
+ * set once it has been configured.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public interface Nameable {
+
+ /**
+ * Sets the (preferably application unique) name for this component.
+ * @param name the preferably application unique name for this component.
+ */
+ void setName(String name);
+}
diff --git a/core/src/org/jsecurity/util/PatternMatcher.java b/core/src/org/jsecurity/util/PatternMatcher.java
new file mode 100644
index 0000000..e2bddab
--- /dev/null
+++ b/core/src/org/jsecurity/util/PatternMatcher.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+/**
+ * Interface for components that can match source strings against a specified pattern string.
+ * <p/>
+ * Different implementations can support different pattern types, for example, Ant style path expressions, or
+ * regular expressions, or other types of text based patterns.
+ *
+ * @author Les Hazlewood
+ * @see org.jsecurity.util.AntPathMatcher AntPathMatcher
+ * @since 0.9 RC2
+ */
+public interface PatternMatcher {
+
+ /**
+ * Returns <code>true</code> if the given <code>source</code> matches the specified <code>pattern</code>,
+ * <code>false</code> otherwise.
+ *
+ * @param pattern the pattern to match against
+ * @param source the source to match
+ * @return <code>true</code> if the given <code>source</code> matches the specified <code>pattern</code>,
+ * <code>false</code> otherwise.
+ */
+ boolean matches(String pattern, String source);
+}
diff --git a/core/src/org/jsecurity/util/PermissionUtils.java b/core/src/org/jsecurity/util/PermissionUtils.java
new file mode 100644
index 0000000..340b70b
--- /dev/null
+++ b/core/src/org/jsecurity/util/PermissionUtils.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.jsecurity.authz.Permission;
+import org.jsecurity.authz.permission.PermissionResolver;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+/**
+ * TODO - comlete JavaDoc
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public class PermissionUtils {
+
+ public static Set<Permission> resolveDelimitedPermissions(String s, PermissionResolver permissionResolver) {
+ Set<String> permStrings = toPermissionStrings(s);
+ return resolvePermissions(permStrings, permissionResolver);
+ }
+
+ public static Set<String> toPermissionStrings(String permissionsString) {
+ String[] tokens = StringUtils.split(permissionsString);
+ if (tokens != null && tokens.length > 0) {
+ return new LinkedHashSet<String>(Arrays.asList(tokens));
+ }
+ return null;
+ }
+
+ public static Set<Permission> resolvePermissions(Collection<String> permissionStrings, PermissionResolver permissionResolver) {
+ Set<Permission> permissions = new LinkedHashSet<Permission>(permissionStrings.size());
+ for (String permissionString : permissionStrings) {
+ permissions.add(permissionResolver.resolvePermission(permissionString));
+ }
+ return permissions;
+ }
+}
diff --git a/core/src/org/jsecurity/util/SoftHashMap.java b/core/src/org/jsecurity/util/SoftHashMap.java
new file mode 100644
index 0000000..0b67f2f
--- /dev/null
+++ b/core/src/org/jsecurity/util/SoftHashMap.java
@@ -0,0 +1,175 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.util.*;
+
+/**
+ * A <code><em>Soft</em>HashMap</code> is a memory-constrained map that stores its <em>values</em> in
+ * {@link SoftReference SoftReference}s. (Contrast this with the JDK's
+ * {@link WeakHashMap WeakHashMap}, which uses weak references for its <em>keys</em>, which is of little value if you
+ * want the cache to auto-resize itself based on memory constraints).
+ * <p/>
+ * Having the values wrapped by soft references allows the cache to automatically reduce its size based on memory
+ * limitations and garbage collection. This ensures that the cache will not cause memory leaks by holding hard
+ * references to all of its values.
+ * <p/>
+ * This class is a generics-enabled Map based on initial ideas from Hienz Kabutz's and Sydney Redelinghuys's
+ * <a href="http://www.javaspecialists.eu/archive/Issue015.html">publicly posted version</a>, with continued
+ * modifications.
+ *
+ * @author Les Hazlewood
+ * @since 1.0
+ */
+public class SoftHashMap<K, V> extends AbstractMap<K, V> {
+
+ /**
+ * The default value of the HARD_SIZE attribute, equal to 100.
+ */
+ private static final int DEFAULT_HARD_SIZE = 100;
+
+ /**
+ * The internal HashMap that will hold the SoftReference.
+ */
+ private final Map<K, SoftValue<V, K>> map = new HashMap<K, SoftValue<V, K>>();
+
+ /**
+ * The number of "hard" references to hold internally, that is, the number of instances to prevent
+ * from being garbage collected automatically (unlike other soft references).
+ */
+ private final int HARD_SIZE;
+
+ /**
+ * The FIFO list of hard references (not to be garbage collected), order of last access.
+ */
+ private final LinkedList<V> hardCache = new LinkedList<V>();
+
+ /**
+ * Reference queue for cleared SoftReference objects.
+ */
+ private final ReferenceQueue<? super V> queue = new ReferenceQueue<V>();
+
+ public SoftHashMap() {
+ this(DEFAULT_HARD_SIZE);
+ }
+
+ public SoftHashMap(int hardSize) {
+ HARD_SIZE = hardSize;
+ }
+
+ public V get(Object key) {
+
+ V result = null;
+
+ SoftValue<V, K> value = map.get(key);
+
+ if (value != null) {
+ //unwrap the 'real' value from the SoftReference
+ result = value.get();
+ if (result == null) {
+ //The wrapped value was garbage collected, so remove this entry from the backing map:
+ map.remove(key);
+ } else {
+ //Add this value to the beginning of the 'hard' reference queue (FIFO).
+ hardCache.addFirst(result);
+
+ //trim the hard ref queue if necessary:
+ if (hardCache.size() > HARD_SIZE) {
+ hardCache.removeLast();
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * We define our own subclass of SoftReference which contains
+ * not only the value but also the key to make it easier to find
+ * the entry in the HashMap after it's been garbage collected.
+ */
+ private static class SoftValue<V, K> extends SoftReference<V> {
+
+ private final K key;
+
+ /**
+ * Constructs a new instance, wrapping the value, key, and queue, as
+ * required by the superclass.
+ *
+ * @param value the map value
+ * @param key the map key
+ * @param queue the soft reference queue to poll to determine if the entry had been reaped by the GC.
+ */
+ private SoftValue(V value, K key, ReferenceQueue<? super V> queue) {
+ super(value, queue);
+ this.key = key;
+ }
+ }
+
+ /**
+ * Traverses the ReferenceQueue and removes garbage-collected SoftValue objects from the backing map
+ * by looking them up using the SoftValue.key data member.
+ */
+ private void processQueue() {
+ SoftValue sv;
+ while ((sv = (SoftValue) queue.poll()) != null) {
+ map.remove(sv.key); // we can access private data!
+ }
+ }
+
+ /**
+ * Creates a new entry, but wraps the value in a SoftValue instance to enable auto garbage collection.
+ */
+ public V put(K key, V value) {
+ processQueue(); // throw out garbage collected values first
+ SoftValue<V, K> sv = new SoftValue<V, K>(value, key, queue);
+ return map.put(key, sv).get();
+ }
+
+ public V remove(Object key) {
+ processQueue(); // throw out garbage collected values first
+ SoftValue<V, K> raw = map.remove(key);
+ V removed = null;
+ if (raw != null) {
+ removed = raw.get();
+ }
+ return removed;
+ }
+
+ public void clear() {
+ hardCache.clear();
+ processQueue(); // throw out garbage collected values
+ map.clear();
+ }
+
+ public int size() {
+ processQueue(); // throw out garbage collected values first
+ return map.size();
+ }
+
+ @SuppressWarnings({"unchecked"})
+ public Set<Map.Entry<K, V>> entrySet() {
+ processQueue(); // throw out garbage collected values first
+ Set set = map.entrySet();
+ return Collections.unmodifiableSet(set);
+ }
+
+
+}
diff --git a/core/src/org/jsecurity/util/StringUtils.java b/core/src/org/jsecurity/util/StringUtils.java
new file mode 100644
index 0000000..59abc1b
--- /dev/null
+++ b/core/src/org/jsecurity/util/StringUtils.java
@@ -0,0 +1,367 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.StringTokenizer;
+
+/**
+ * <p>Simple utility class for String operations useful across the framework.
+ *
+ * <p>Some methods in this class were copied from the Spring Framework so we didn't have to re-invent the wheel,
+ * and in these cases, we have retained all license, copyright and author information.
+ *
+ * @author Les Hazlewood
+ * @author Rod Johnson
+ * @author Juergen Hoeller
+ * @author Keith Donald
+ * @author Rob Harrop
+ * @since 0.9
+ */
+public class StringUtils {
+
+ //TODO - complete JavaDoc
+
+ /** Constant representing the empty string, equal to "" */
+ public static final String EMPTY_STRING = "";
+
+ /** Constant representing the default delimiter character (comma), equal to <code>','</code> */
+ public static final char DEFAULT_DELIMITER_CHAR = ',';
+
+ /** Constant representing the default quote character (double quote), equal to '"'</code> */
+ public static final char DEFAULT_QUOTE_CHAR = '"';
+
+ /**
+ * Check whether the given String has actual text.
+ * More specifically, returns <code>true</code> if the string not <code>null</code>,
+ * its length is greater than 0, and it contains at least one non-whitespace character.
+ * <p/>
+ * <code>StringUtils.hasText(null) == false<br/>
+ * StringUtils.hasText("") == false<br/>
+ * StringUtils.hasText(" ") == false<br/>
+ * StringUtils.hasText("12345") == true<br/>
+ * StringUtils.hasText(" 12345 ") == true</code>
+ *
+ * <p>Copied from the Spring Framework while retaining all license, copyright and author information.
+ *
+ * @param str the String to check (may be <code>null</code>)
+ * @return <code>true</code> if the String is not <code>null</code>, its length is
+ * greater than 0, and it does not contain whitespace only
+ * @see java.lang.Character#isWhitespace
+ */
+ public static boolean hasText(String str) {
+ if (!hasLength(str)) {
+ return false;
+ }
+ int strLen = str.length();
+ for (int i = 0; i < strLen; i++) {
+ if (!Character.isWhitespace(str.charAt(i))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check that the given String is neither <code>null</code> nor of length 0.
+ * Note: Will return <code>true</code> for a String that purely consists of whitespace.
+ * <p/>
+ * <code>StringUtils.hasLength(null) == false<br/>
+ * StringUtils.hasLength("") == false<br/>
+ * StringUtils.hasLength(" ") == true<br/>
+ * StringUtils.hasLength("Hello") == true</code>
+ * <p/>
+ * Copied from the Spring Framework while retaining all license, copyright and author information.
+ *
+ * @param str the String to check (may be <code>null</code>)
+ * @return <code>true</code> if the String is not null and has length
+ * @see #hasText(String)
+ */
+ public static boolean hasLength(String str) {
+ return (str != null && str.length() > 0);
+ }
+
+
+ /**
+ * Test if the given String starts with the specified prefix,
+ * ignoring upper/lower case.
+ *
+ * <p>Copied from the Spring Framework while retaining all license, copyright and author information.
+ *
+ * @param str the String to check
+ * @param prefix the prefix to look for
+ * @return <code>true</code> starts with the specified prefix (ignoring case), <code>false</code> if it does not.
+ * @see java.lang.String#startsWith
+ */
+ public static boolean startsWithIgnoreCase(String str, String prefix) {
+ if (str == null || prefix == null) {
+ return false;
+ }
+ if (str.startsWith(prefix)) {
+ return true;
+ }
+ if (str.length() < prefix.length()) {
+ return false;
+ }
+ String lcStr = str.substring(0, prefix.length()).toLowerCase();
+ String lcPrefix = prefix.toLowerCase();
+ return lcStr.equals(lcPrefix);
+ }
+
+ /**
+ * Returns a 'cleaned' representation of the specified argument. 'Cleaned' is defined as the following:
+ *
+ * <ol>
+ * <li>If the specified <code>String</code> is <code>null</code>, return <code>null</code></li>
+ * <li>If not <code>null</code>, {@link String#trim() trim()} it.</li>
+ * <li>If the trimmed string is equal to the empty String (i.e. ""), return <code>null</code></li>
+ * <li>If the trimmed string is not the empty string, return the trimmed version</li>.
+ * </ol>
+ *
+ * Therefore this method always ensures that any given string has trimmed text, and if it doesn't, <code>null</code>
+ * is returned.
+ *
+ * @param in the input String to clean.
+ * @return a populated-but-trimmed String or <code>null</code> otherwise
+ */
+ public static String clean(String in) {
+ String out = in;
+
+ if (in != null) {
+ out = in.trim();
+ if (out.equals(EMPTY_STRING)) {
+ out = null;
+ }
+ }
+
+ return out;
+ }
+
+ /**
+ * Tokenize the given String into a String array via a StringTokenizer.
+ * Trims tokens and omits empty tokens.
+ * <p>The given delimiters string is supposed to consist of any number of
+ * delimiter characters. Each of those characters can be used to separate
+ * tokens. A delimiter is always a single character; for multi-character
+ * delimiters, consider using <code>delimitedListToStringArray</code>
+ *
+ * <p>Copied from the Spring Framework while retaining all license, copyright and author information.
+ *
+ * @param str the String to tokenize
+ * @param delimiters the delimiter characters, assembled as String
+ * (each of those characters is individually considered as delimiter).
+ * @return an array of the tokens
+ * @see java.util.StringTokenizer
+ * @see java.lang.String#trim()
+ */
+ public static String[] tokenizeToStringArray(String str, String delimiters) {
+ return tokenizeToStringArray(str, delimiters, true, true);
+ }
+
+ /**
+ * Tokenize the given String into a String array via a StringTokenizer.
+ * <p>The given delimiters string is supposed to consist of any number of
+ * delimiter characters. Each of those characters can be used to separate
+ * tokens. A delimiter is always a single character; for multi-character
+ * delimiters, consider using <code>delimitedListToStringArray</code>
+ *
+ * <p>Copied from the Spring Framework while retaining all license, copyright and author information.
+ *
+ * @param str the String to tokenize
+ * @param delimiters the delimiter characters, assembled as String
+ * (each of those characters is individually considered as delimiter)
+ * @param trimTokens trim the tokens via String's <code>trim</code>
+ * @param ignoreEmptyTokens omit empty tokens from the result array
+ * (only applies to tokens that are empty after trimming; StringTokenizer
+ * will not consider subsequent delimiters as token in the first place).
+ * @return an array of the tokens (<code>null</code> if the input String
+ * was <code>null</code>)
+ * @see java.util.StringTokenizer
+ * @see java.lang.String#trim()
+ */
+ @SuppressWarnings({"unchecked"})
+ public static String[] tokenizeToStringArray(
+ String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {
+
+ if (str == null) {
+ return null;
+ }
+ StringTokenizer st = new StringTokenizer(str, delimiters);
+ List tokens = new ArrayList();
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken();
+ if (trimTokens) {
+ token = token.trim();
+ }
+ if (!ignoreEmptyTokens || token.length() > 0) {
+ tokens.add(token);
+ }
+ }
+ return toStringArray(tokens);
+ }
+
+ /**
+ * Copy the given Collection into a String array.
+ * The Collection must contain String elements only.
+ *
+ * <p>Copied from the Spring Framework while retaining all license, copyright and author information.
+ *
+ * @param collection the Collection to copy
+ * @return the String array (<code>null</code> if the passed-in
+ * Collection was <code>null</code>)
+ */
+ @SuppressWarnings({"unchecked"})
+ public static String[] toStringArray(Collection collection) {
+ if (collection == null) {
+ return null;
+ }
+ return (String[]) collection.toArray(new String[collection.size()]);
+ }
+
+ public static String[] splitKeyValue(String aLine) throws ParseException {
+ String line = clean(aLine);
+ if (line == null) {
+ return null;
+ }
+ String[] split = line.split(" ", 2);
+ if (split.length != 2) {
+ //fallback to checking for an equals sign
+ split = line.split("=", 2);
+ if (split.length != 2) {
+ String msg = "Unable to determine Key/Value pair from line [" + line + "]. There is no space from " +
+ "which the split location could be determined.";
+ throw new ParseException(msg, 0);
+ }
+
+ }
+
+ split[0] = clean(split[0]);
+ split[1] = clean(split[1]);
+ if (split[1].startsWith("=")) {
+ //they used spaces followed by an equals followed by zero or more spaces to split the key/value pair, so
+ //remove the equals sign to result in only the key and values in the
+ split[1] = clean(split[1].substring(1));
+ }
+
+ if (split[0] == null) {
+ String msg = "No valid key could be found in line [" + line + "] to form a key/value pair.";
+ throw new ParseException(msg, 0);
+ }
+ if (split[1] == null) {
+ String msg = "No corresponding value could be found in line [" + line + "] for key [" + split[0] + "]";
+ throw new ParseException(msg, 0);
+ }
+
+ return split;
+ }
+
+ public static String[] split(String line) {
+ return split(line, DEFAULT_DELIMITER_CHAR);
+ }
+
+ public static String[] split(String line, char delimiter) {
+ return split(line, delimiter, DEFAULT_QUOTE_CHAR);
+ }
+
+ public static String[] split(String line, char delimiter, char quoteChar) {
+ return split(line, delimiter, quoteChar, quoteChar);
+ }
+
+ public static String[] split(String line, char delimiter, char beginQuoteChar, char endQuoteChar) {
+ return split(line, delimiter, beginQuoteChar, endQuoteChar, false, true);
+ }
+
+ /**
+ * Splits the specified delimited String into tokens, supporting quoted tokens so that quoted strings themselves
+ * won't be tokenized.
+ *
+ * <p>This method's implementation is very loosely based (with significant modifications) on
+ * <a href="http://blogs.bytecode.com.au/glen">Glen Smith</a>'s open-source
+ * <a href="http://opencsv.svn.sourceforge.net/viewvc/opencsv/trunk/src/au/com/bytecode/opencsv/CSVReader.java?&view=markup">CSVReader.java</a>
+ * file.
+ *
+ * <p>That file is Apache 2.0 licensed as well, making Glen's code a great starting point for us to modify to
+ * our needs.
+ *
+ * @param aLine the String to parse
+ * @param delimiter the delimiter by which the <tt>line</tt> argument is to be split
+ * @param beginQuoteChar the character signifying the start of quoted text (so the quoted text will not be split)
+ * @param endQuoteChar the character signifying the end of quoted text
+ * @param retainQuotes if the quotes themselves should be retained when constructing the corresponding token
+ * @param trimTokens if leading and trailing whitespace should be trimmed from discovered tokens.
+ * @return the tokens discovered from parsing the given delimited <tt>line</tt>.
+ */
+ public static String[] split(String aLine, char delimiter, char beginQuoteChar, char endQuoteChar,
+ boolean retainQuotes, boolean trimTokens) {
+ String line = clean(aLine);
+ if (line == null) {
+ return null;
+ }
+
+ List<String> tokens = new ArrayList<String>();
+ StringBuffer sb = new StringBuffer();
+ boolean inQuotes = false;
+
+ for (int i = 0; i < line.length(); i++) {
+
+ char c = line.charAt(i);
+ if (c == beginQuoteChar) {
+ // this gets complex... the quote may end a quoted block, or escape another quote.
+ // do a 1-char lookahead:
+ if (inQuotes // we are in quotes, therefore there can be escaped quotes in here.
+ && line.length() > (i + 1) // there is indeed another character to check.
+ && line.charAt(i + 1) == beginQuoteChar) { // ..and that char. is a quote also.
+ // we have two quote chars in a row == one quote char, so consume them both and
+ // put one on the token. we do *not* exit the quoted text.
+ sb.append(line.charAt(i + 1));
+ i++;
+ } else {
+ inQuotes = !inQuotes;
+ if (retainQuotes) {
+ sb.append(c);
+ }
+ }
+ } else if (c == endQuoteChar) {
+ inQuotes = !inQuotes;
+ if (retainQuotes) {
+ sb.append(c);
+ }
+ } else if (c == delimiter && !inQuotes) {
+ String s = sb.toString();
+ if (trimTokens) {
+ s = s.trim();
+ }
+ tokens.add(s);
+ sb = new StringBuffer(); // start work on next token
+ } else {
+ sb.append(c);
+ }
+ }
+ String s = sb.toString();
+ if (trimTokens) {
+ s = s.trim();
+ }
+ tokens.add(s);
+ return tokens.toArray(new String[tokens.size()]);
+ }
+
+}
diff --git a/core/src/org/jsecurity/util/ThreadContext.java b/core/src/org/jsecurity/util/ThreadContext.java
new file mode 100644
index 0000000..12b8aa6
--- /dev/null
+++ b/core/src/org/jsecurity/util/ThreadContext.java
@@ -0,0 +1,370 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.mgt.SecurityManager;
+import org.jsecurity.subject.Subject;
+
+import java.net.InetAddress;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A ThreadContext provides a means of binding and unbinding objects to the
+ * current thread based on key/value pairs.
+ *
+ * <p>An internal {@link java.util.HashMap} is used to maintain the key/value pairs
+ * for each thread.</p>
+ *
+ * <p>If the desired behavior is to ensure that bound data is not shared across
+ * threads in a pooled or reusable threaded environment, the application (or more likely a framework) must
+ * bind and remove any necessary values at the beginning and end of stack
+ * execution, respectively (i.e. individually explicitly or all via the <tt>clear</tt> method).</p>
+ *
+ * @author Les Hazlewood
+ * @see #clear()
+ * @since 0.1
+ */
+@SuppressWarnings(value = {"unchecked", "unsafe"})
+public abstract class ThreadContext {
+
+ /** Private internal log instance. */
+ private static final Log log = LogFactory.getLog(ThreadContext.class);
+
+ public static final String SECURITY_MANAGER_KEY = ThreadContext.class.getName() + "_SECURITY_MANAGER_KEY";
+ public static final String SUBJECT_KEY = ThreadContext.class.getName() + "_SUBJECT_KEY";
+ public static final String INET_ADDRESS_KEY = ThreadContext.class.getName() + "_INET_ADDRESS_KEY";
+
+ protected static ThreadLocal<Map<Object, Object>> resources =
+ new InheritableThreadLocal<Map<Object, Object>>() {
+ protected Map<Object, Object> initialValue() {
+ return new HashMap<Object, Object>();
+ }
+
+ /**
+ * This implementation was added to address a
+ * <a href="http://jsecurity.markmail.org/search/?q=#query:+page:1+mid:xqi2yxurwmrpqrvj+state:results">
+ * user-reported issue</a>.
+ * @param parentValue the parent value, a HashMap as defined in the {@link #initialValue()} method.
+ * @return the HashMap to be used by any parent-spawned child threads (a clone of the parent HashMap).
+ */
+ protected Map<Object, Object> childValue(Map<Object, Object> parentValue) {
+ if (parentValue != null) {
+ return (Map<Object, Object>) ((HashMap<Object, Object>) parentValue).clone();
+ } else {
+ return null;
+ }
+ }
+ };
+
+ /**
+ * Default no-argument constructor.
+ */
+ protected ThreadContext() {
+ }
+
+ /**
+ * Returns the ThreadLocal Map. This Map is used internally to bind objects
+ * to the current thread by storing each object under a unique key.
+ *
+ * @return the map of bound resources
+ */
+ protected static Map<Object, Object> getResources() {
+ return resources.get();
+ }
+
+ /**
+ * Returns the object for the specified <code>key</code> that is bound to
+ * the current thread.
+ *
+ * @param key the key that identifies the value to return
+ * @return the object keyed by <code>key</code> or <code>null</code> if
+ * no value exists for the specified <code>key</code>
+ */
+ public static Object get(Object key) {
+ if (log.isTraceEnabled()) {
+ String msg = "get() - in thread [" + Thread.currentThread().getName() + "]";
+ log.trace(msg);
+ }
+ Object value = getResources().get(key);
+ if ((value != null) && log.isTraceEnabled()) {
+ String msg = "Retrieved value of type [" + value.getClass().getName() + "] for key [" +
+ key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]";
+ log.trace(msg);
+ }
+ return value;
+ }
+
+ /**
+ * Binds <tt>value</tt> for the given <code>key</code> to the current thread.
+ *
+ * <p>A <tt>null</tt> <tt>value</tt> has the same effect as if <tt>remove</tt> was called for the given
+ * <tt>key</tt>, i.e.:
+ *
+ * <pre>
+ * if ( value == null ) {
+ * remove( key );
+ * }</pre>
+ *
+ * @param key The key with which to identify the <code>value</code>.
+ * @param value The value to bind to the thread.
+ * @throws IllegalArgumentException if the <code>key</code> argument is <tt>null</tt>.
+ */
+ public static void put(Object key, Object value) {
+ if (key == null) {
+ throw new IllegalArgumentException("key cannot be null");
+ }
+
+ if (value == null) {
+ remove(key);
+ return;
+ }
+
+ getResources().put(key, value);
+
+ if (log.isTraceEnabled()) {
+ String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" +
+ key + "] to thread " + "[" + Thread.currentThread().getName() + "]";
+ log.trace(msg);
+ }
+ }
+
+ /**
+ * Unbinds the value for the given <code>key</code> from the current
+ * thread.
+ *
+ * @param key The key identifying the value bound to the current thread.
+ * @return the object unbound or <tt>null</tt> if there was nothing bound
+ * under the specified <tt>key</tt> name.
+ */
+ public static Object remove(Object key) {
+ Object value = getResources().remove(key);
+
+ if ((value != null) && log.isTraceEnabled()) {
+ String msg = "Removed value of type [" + value.getClass().getName() + "] for key [" +
+ key + "]" + "from thread [" + Thread.currentThread().getName() + "]";
+ log.trace(msg);
+ }
+
+ return value;
+ }
+
+ /**
+ * Returns true if a value for the <code>key</code> is bound to the current thread, false otherwise.
+ *
+ * @param key the key that may identify a value bound to the current thread.
+ * @return true if a value for the key is bound to the current thread, false
+ * otherwise.
+ */
+ public static boolean containsKey(Object key) {
+ return getResources().containsKey(key);
+ }
+
+ /**
+ * Removes <em>all</em> values bound to this ThreadContext, which includes any Subject, Session, or InetAddress
+ * that may be bound by these respective objects' conveninece methods, as well as all values bound by your
+ * application code.
+ *
+ * <p>This operation is meant as a clean-up operation that may be called at the end of
+ * thread execution to prevent data corruption in a pooled thread environment.
+ */
+ public static void clear() {
+ getResources().clear();
+ if (log.isTraceEnabled()) {
+ log.trace("Removed all ThreadContext values from thread [" + Thread.currentThread().getName() + "]");
+ }
+ }
+
+ /**
+ * Convenience method that simplifies retrieval of the application's SecurityManager instance from the current
+ * thread. If there is no SecurityManager bound to the thread (probably because framework code did not bind it
+ * to the thread), this method returns <tt>null</tt>.
+ * <p/>
+ * It is merely a convenient wrapper for the following:
+ * <p/>
+ * <code>return (SecurityManager)get( SECURITY_MANAGER_KEY );</code>
+ * <p/>
+ * This method only returns the bound value if it exists - it does not remove it
+ * from the thread. To remove it, one must call {@link #unbindSecurityManager() unbindSecurityManager()} instead.
+ *
+ * @return the Subject object bound to the thread, or <tt>null</tt> if there isn't one bound.
+ * @since 0.9
+ */
+ public static SecurityManager getSecurityManager() {
+ return (SecurityManager) get(SECURITY_MANAGER_KEY);
+ }
+
+
+ /**
+ * Convenience method that simplifies binding the application's SecurityManager instance to the ThreadContext.
+ *
+ * <p>The method's existence is to help reduce casting in code and to simplify remembering of
+ * ThreadContext key names. The implementation is simple in that, if the SecurityManager is not <tt>null</tt>,
+ * it binds it to the thread, i.e.:
+ *
+ * <pre>
+ * if (securityManager != null) {
+ * put( SECURITY_MANAGER_KEY, securityManager);
+ * }</pre>
+ *
+ * @param securityManager the application's SecurityManager instance to bind to the thread. If the argument is
+ * null, nothing will be done.
+ * @since 0.9
+ */
+ public static void bind(SecurityManager securityManager) {
+ if (securityManager != null) {
+ put(SECURITY_MANAGER_KEY, securityManager);
+ }
+ }
+
+ /**
+ * Convenience method that simplifies removal of the application's SecurityManager instance from the thread.
+ * <p/>
+ * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is
+ * merely a conveient wrapper for the following:
+ * <p/>
+ * <code>return (SecurityManager)remove( SECURITY_MANAGER_KEY );</code>
+ * <p/>
+ * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later
+ * during thread execution), use the {@link #getSecurityManager() getSecurityManager()} method instead.
+ *
+ * @return the application's SecurityManager instance previously bound to the thread, or <tt>null</tt> if there
+ * was none bound.
+ * @since 0.9
+ */
+ public static SecurityManager unbindSecurityManager() {
+ return (SecurityManager) remove(SECURITY_MANAGER_KEY);
+ }
+
+ /**
+ * Convenience method that simplifies retrieval of a thread-bound Subject. If there is no
+ * Subject bound to the thread, this method returns <tt>null</tt>. It is merely a convenient wrapper
+ * for the following:
+ * <p/>
+ * <code>return (Subject)get( SUBJECT_KEY );</code>
+ * <p/>
+ * This method only returns the bound value if it exists - it does not remove it
+ * from the thread. To remove it, one must call {@link #unbindSubject() unbindSubject()} instead.
+ *
+ * @return the Subject object bound to the thread, or <tt>null</tt> if there isn't one bound.
+ * @since 0.2
+ */
+ public static Subject getSubject() {
+ return (Subject) get(SUBJECT_KEY);
+ }
+
+
+ /**
+ * Convenience method that simplifies binding a Subject to the ThreadContext.
+ *
+ * <p>The method's existence is to help reduce casting in your own code and to simplify remembering of
+ * ThreadContext key names. The implementation is simple in that, if the Subject is not <tt>null</tt>,
+ * it binds it to the thread, i.e.:
+ *
+ * <pre>
+ * if (subject != null) {
+ * put( SUBJECT_KEY, subject );
+ * }</pre>
+ *
+ * @param subject the Subject object to bind to the thread. If the argument is null, nothing will be done.
+ * @since 0.2
+ */
+ public static void bind(Subject subject) {
+ if (subject != null) {
+ put(SUBJECT_KEY, subject);
+ }
+ }
+
+ /**
+ * Convenience method that simplifies removal of a thread-local Subject from the thread.
+ * <p/>
+ * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is
+ * merely a conveient wrapper for the following:
+ * <p/>
+ * <code>return (Subject)remove( SUBJECT_KEY );</code>
+ * <p/>
+ * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later during
+ * thread execution), you should use the {@link #getSubject() getSubject()} method for that purpose.
+ *
+ * @return the Subject object previously bound to the thread, or <tt>null</tt> if there was none bound.
+ * @since 0.2
+ */
+ public static Subject unbindSubject() {
+ return (Subject) remove(SUBJECT_KEY);
+ }
+
+ /**
+ * Convenience method that simplifies retrieval of a thread-bound InetAddress. If there is no
+ * InetAddress bound to the thread, this method returns <tt>null</tt>. It is merely a convenient wrapper
+ * for the following:
+ * <p/>
+ * <code>return (InetAddress)get( INET_ADDRESS_KEY );</code>
+ * <p/>
+ * This method only returns the bound value if it exists - it does not remove it
+ * from the thread. To remove it, one must call {@link #unbindInetAddress() unbindInetAddress} instead.
+ *
+ * @return the InetAddress object bound to the thread, or <tt>null</tt> if there isn't one bound.
+ * @since 0.2
+ */
+ public static InetAddress getInetAddress() {
+ return (InetAddress) get(INET_ADDRESS_KEY);
+ }
+
+ /**
+ * Convenience method that simplifies binding an InetAddress to the ThreadContext.
+ *
+ * <p>The method's existence is to help reduce casting in your own code and to simplify remembering of
+ * ThreadContext key names. The implementation is simple in that, if the inetAddress is not <tt>null</tt>,
+ * it binds it to the thread, i.e.:
+ *
+ * <pre>
+ * if (inetAddress != null) {
+ * put( INET_ADDRESS_KEY, inetAddress );
+ * }</pre>
+ *
+ * @param inetAddress the InetAddress to bind to the thread. If the argument is null, nothing will be done.
+ * @since 0.2
+ */
+ public static void bind(InetAddress inetAddress) {
+ if (inetAddress != null) {
+ put(INET_ADDRESS_KEY, inetAddress);
+ }
+ }
+
+ /**
+ * Convenience method that simplifies removal of a thread-local InetAddress from the thread.
+ * <p/>
+ * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is
+ * merely a conveient wrapper for the following:
+ * <p/>
+ * <code>return (InetAddress)remove( INET_ADDRESS_KEY );</code>
+ * <p/>
+ * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later during
+ * thread execution), you should use the {@link #getInetAddress() getInetAddress()} method for that purpose.
+ *
+ * @return the InetAddress object previously bound to the thread, or <tt>null</tt> if there was none bound.
+ * @since 0.2
+ */
+ public static InetAddress unbindInetAddress() {
+ return (InetAddress) remove(INET_ADDRESS_KEY);
+ }
+}
+
diff --git a/core/src/org/jsecurity/util/UnavailableConstructorException.java b/core/src/org/jsecurity/util/UnavailableConstructorException.java
new file mode 100644
index 0000000..d099af8
--- /dev/null
+++ b/core/src/org/jsecurity/util/UnavailableConstructorException.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * Exception thrown when attempting to instantiate a Class via reflection, but a suitable constructor (depending
+ * on the number of expected arguments) doesn't exist or cannot be obtained.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class UnavailableConstructorException extends JSecurityException {
+
+ /**
+ * Creates a new UnavailableConstructorException.
+ */
+ public UnavailableConstructorException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnavailableConstructorException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnavailableConstructorException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnavailableConstructorException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnavailableConstructorException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnavailableConstructorException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnavailableConstructorException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/core/src/org/jsecurity/util/UnknownClassException.java b/core/src/org/jsecurity/util/UnknownClassException.java
new file mode 100644
index 0000000..51ad14e
--- /dev/null
+++ b/core/src/org/jsecurity/util/UnknownClassException.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import org.jsecurity.JSecurityException;
+
+/**
+ * The JSecurity framework's <code>RuntimeException</code> equivalent of the JDK's
+ * <code>ClassNotFoundException</code>, to maintain a RuntimeException paradigm.
+ *
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public class UnknownClassException extends JSecurityException {
+
+ /**
+ * Creates a new UnknownClassException.
+ */
+ public UnknownClassException() {
+ super();
+ }
+
+ /**
+ * Constructs a new UnknownClassException.
+ *
+ * @param message the reason for the exception
+ */
+ public UnknownClassException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new UnknownClassException.
+ *
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownClassException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new UnknownClassException.
+ *
+ * @param message the reason for the exception
+ * @param cause the underlying Throwable that caused this exception to be thrown.
+ */
+ public UnknownClassException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/test/org/jsecurity/AtUnitTestBase.java
similarity index 66%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/test/org/jsecurity/AtUnitTestBase.java
index 8e597f2..539e3dd 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/test/org/jsecurity/AtUnitTestBase.java
@@ -16,8 +16,21 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity;
+
+/*import atunit.AtUnit;
+import atunit.Container;
+import atunit.MockFramework;
+import org.junit.runner.RunWith;*/
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * Super class that simply provides boiler plate annotations for subclass tests.
+ *
+ * @author Jeremy Haile
+ * @since 0.9
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+/*@RunWith(AtUnit.class)
+@Container(Container.Option.SPRING)
+@MockFramework(MockFramework.Option.EASYMOCK)*/
+public class AtUnitTestBase {
+}
diff --git a/core/test/org/jsecurity/ExceptionTest.java b/core/test/org/jsecurity/ExceptionTest.java
new file mode 100644
index 0000000..1d5e723
--- /dev/null
+++ b/core/test/org/jsecurity/ExceptionTest.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity;
+
+import junit.framework.TestCase;
+import org.jsecurity.util.ClassUtils;
+import org.junit.Test;
+
+/**
+ * @author Les Hazlewood
+ */
+public abstract class ExceptionTest extends TestCase {
+
+ protected abstract Class getExceptionClass();
+
+ @Test
+ public void testNoArgConstructor() {
+ ClassUtils.newInstance(getExceptionClass());
+ }
+
+ @Test
+ public void testMsgConstructor() throws Exception {
+ ClassUtils.newInstance(getExceptionClass(), "Msg");
+ }
+
+ @Test
+ public void testCauseConstructor() throws Exception {
+ ClassUtils.newInstance(getExceptionClass(), new Throwable());
+ }
+
+ @Test
+ public void testMsgCauseConstructor() {
+ ClassUtils.newInstance(getExceptionClass(), "Msg", new Throwable());
+ }
+}
diff --git a/core/test/org/jsecurity/config/CompositeBean.java b/core/test/org/jsecurity/config/CompositeBean.java
new file mode 100644
index 0000000..d5d2651
--- /dev/null
+++ b/core/test/org/jsecurity/config/CompositeBean.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.config;
+
+/**
+ * @author Les Hazlewood
+ * @since Aug 5, 2008 10:17:37 AM
+ */
+public class CompositeBean
+{
+ private String stringProp;
+ private boolean booleanProp;
+ private int intProp;
+ private SimpleBean simpleBean;
+
+ public CompositeBean() {
+ }
+
+ public String getStringProp() {
+ return stringProp;
+ }
+
+ public void setStringProp(String stringProp) {
+ this.stringProp = stringProp;
+ }
+
+ public boolean isBooleanProp() {
+ return booleanProp;
+ }
+
+ public void setBooleanProp(boolean booleanProp) {
+ this.booleanProp = booleanProp;
+ }
+
+ public int getIntProp() {
+ return intProp;
+ }
+
+ public void setIntProp(int intProp) {
+ this.intProp = intProp;
+ }
+
+ public SimpleBean getSimpleBean() {
+ return simpleBean;
+ }
+
+ public void setSimpleBean(SimpleBean simpleBean) {
+ this.simpleBean = simpleBean;
+ }
+}
diff --git a/core/test/org/jsecurity/config/ReflectionBuilderTest.java b/core/test/org/jsecurity/config/ReflectionBuilderTest.java
new file mode 100644
index 0000000..b1d8cb0
--- /dev/null
+++ b/core/test/org/jsecurity/config/ReflectionBuilderTest.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.config;
+
+import static org.junit.Assert.*;
+import org.junit.Test;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * @author Les Hazlewood
+ * @since Aug 5, 2008 9:53:00 AM
+ */
+public class ReflectionBuilderTest {
+
+ @Test
+ public void testSimpleConfig() {
+ Map<String, String> defs = new LinkedHashMap<String, String>();
+ defs.put("compositeBean", "org.jsecurity.config.CompositeBean");
+ defs.put("compositeBean.stringProp", "blah");
+ defs.put("compositeBean.booleanProp", "true");
+ defs.put("compositeBean.intProp", "42");
+
+ ReflectionBuilder builder = new ReflectionBuilder();
+ Map beans = builder.buildObjects(defs);
+
+ CompositeBean compositeBean = (CompositeBean) beans.get("compositeBean");
+ assertNotNull(compositeBean);
+ assertEquals(compositeBean.getStringProp(), "blah");
+ assertTrue(compositeBean.isBooleanProp());
+ assertEquals(compositeBean.getIntProp(), 42);
+ }
+
+ @Test
+ public void testSimpleConfigWithDollarSignStringValue() {
+ Map<String, String> defs = new LinkedHashMap<String, String>();
+ defs.put("compositeBean", "org.jsecurity.config.CompositeBean");
+ defs.put("compositeBean.stringProp", "\\$500");
+
+ ReflectionBuilder builder = new ReflectionBuilder();
+ Map beans = builder.buildObjects(defs);
+
+ CompositeBean compositeBean = (CompositeBean) beans.get("compositeBean");
+ assertEquals(compositeBean.getStringProp(), "$500");
+ }
+
+ @Test
+ public void testObjectReferenceConfig() {
+ Map<String, String> defs = new LinkedHashMap<String, String>();
+ defs.put("simpleBean", "org.jsecurity.config.SimpleBean");
+ defs.put("simpleBean.intProp", "101");
+ defs.put("compositeBean", "org.jsecurity.config.CompositeBean");
+ defs.put("compositeBean.stringProp", "blah");
+ defs.put("compositeBean.simpleBean", "$simpleBean");
+
+ ReflectionBuilder builder = new ReflectionBuilder();
+ Map beans = builder.buildObjects(defs);
+
+ CompositeBean compositeBean = (CompositeBean) beans.get("compositeBean");
+ assertNotNull(compositeBean);
+ assertEquals(compositeBean.getStringProp(), "blah");
+ SimpleBean simpleBean = (SimpleBean) beans.get("simpleBean");
+ assertNotNull(simpleBean);
+ assertNotNull(compositeBean.getSimpleBean());
+ assertEquals(simpleBean, compositeBean.getSimpleBean());
+ assertEquals(simpleBean.getIntProp(), 101);
+ }
+
+ @Test(expected = ConfigurationException.class)
+ public void testObjectReferenceConfigWithTypeMismatch() {
+ Map<String, String> defs = new LinkedHashMap<String, String>();
+ defs.put("simpleBean", "org.jsecurity.config.SimpleBean");
+ defs.put("compositeBean", "org.jsecurity.config.CompositeBean");
+ defs.put("compositeBean.simpleBean", "simpleBean");
+ ReflectionBuilder builder = new ReflectionBuilder();
+ builder.buildObjects(defs);
+ }
+
+ @Test(expected = UnresolveableReferenceException.class)
+ public void testObjectReferenceConfigWithInvalidReference() {
+ Map<String, String> defs = new LinkedHashMap<String, String>();
+ defs.put("simpleBean", "org.jsecurity.config.SimpleBean");
+ defs.put("compositeBean", "org.jsecurity.config.CompositeBean");
+ defs.put("compositeBean.simpleBean", "$foo");
+ ReflectionBuilder builder = new ReflectionBuilder();
+ builder.buildObjects(defs);
+ }
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/test/org/jsecurity/config/SimpleBean.java
similarity index 60%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/test/org/jsecurity/config/SimpleBean.java
index 8e597f2..8241346 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/test/org/jsecurity/config/SimpleBean.java
@@ -1,23 +1,49 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.config;
+
+/**
+ * @author Les Hazlewood
+ * @since Aug 5, 2008 10:18:01 AM
+ */
+public class SimpleBean
+{
+
+ private String stringProp = null;
+ private int intProp;
+
+ public SimpleBean() {
+ }
+
+ public String getStringProp() {
+ return stringProp;
+ }
+
+ public void setStringProp(String stringProp) {
+ this.stringProp = stringProp;
+ }
+
+ public int getIntProp() {
+ return intProp;
+ }
+
+ public void setIntProp(int intProp) {
+ this.intProp = intProp;
+ }
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/test/org/jsecurity/io/ResourceExceptionTest.java
similarity index 76%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/test/org/jsecurity/io/ResourceExceptionTest.java
index 8e597f2..49cd1cf 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/test/org/jsecurity/io/ResourceExceptionTest.java
@@ -1,23 +1,31 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.io;
+
+import org.jsecurity.ExceptionTest;
+
+/**
+ * @author Les Hazlewood
+ */
+public class ResourceExceptionTest extends ExceptionTest {
+
+ protected Class getExceptionClass() {
+ return ResourceException.class;
+ }
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/core/test/org/jsecurity/io/SerializationExceptionTest.java
similarity index 75%
copy from src/org/jsecurity/mgt/package-info.java
copy to core/test/org/jsecurity/io/SerializationExceptionTest.java
index 8e597f2..42da467 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/core/test/org/jsecurity/io/SerializationExceptionTest.java
@@ -1,23 +1,31 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.io;
+
+import org.jsecurity.ExceptionTest;
+
+/**
+ * @author Les Hazlewood
+ */
+public class SerializationExceptionTest extends ExceptionTest {
+
+ protected Class getExceptionClass() {
+ return SerializationException.class;
+ }
+}
diff --git a/core/test/org/jsecurity/mgt/DefaultSecurityManagerTest.java b/core/test/org/jsecurity/mgt/DefaultSecurityManagerTest.java
new file mode 100644
index 0000000..af26f21
--- /dev/null
+++ b/core/test/org/jsecurity/mgt/DefaultSecurityManagerTest.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.UsernamePasswordToken;
+import org.jsecurity.session.Session;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.ThreadContext;
+import org.junit.After;
+import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class DefaultSecurityManagerTest {
+
+ DefaultSecurityManager sm = null;
+
+ @Before
+ public void setup() {
+ sm = new DefaultSecurityManager();
+ ThreadContext.clear();
+ }
+
+ @After
+ public void tearDown() {
+ sm.destroy();
+ ThreadContext.clear();
+ }
+
+ @Test
+ public void testDefaultConfig() {
+ Subject subject = sm.getSubject();
+
+ AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
+ subject.login(token);
+ assertTrue(subject.isAuthenticated());
+ assertTrue("guest".equals(subject.getPrincipal()));
+ assertTrue(subject.hasRole("guest"));
+
+ Session session = subject.getSession();
+ session.setAttribute("key", "value");
+ assertEquals(session.getAttribute("key"), "value");
+
+ subject.logout();
+
+ assertNull(subject.getSession(false));
+ assertNull(subject.getPrincipal());
+ assertNull(subject.getPrincipals());
+ }
+}
diff --git a/core/test/org/jsecurity/mgt/VMSingletonDefaultSecurityManagerTest.java b/core/test/org/jsecurity/mgt/VMSingletonDefaultSecurityManagerTest.java
new file mode 100644
index 0000000..113957e
--- /dev/null
+++ b/core/test/org/jsecurity/mgt/VMSingletonDefaultSecurityManagerTest.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.mgt;
+
+import org.jsecurity.SecurityUtils;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.UsernamePasswordToken;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.ThreadContext;
+import org.junit.After;
+import static org.junit.Assert.assertTrue;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author Les Hazlewood
+ * @since May 8, 2008 12:26:23 AM
+ */
+public class VMSingletonDefaultSecurityManagerTest {
+
+ @Before
+ public void setUp() {
+ ThreadContext.clear();
+ }
+
+ @After
+ public void tearDown() {
+ ThreadContext.clear();
+ }
+
+ @Test
+ public void testVMSingleton() {
+ DefaultSecurityManager sm = new DefaultSecurityManager();
+ SecurityUtils.setSecurityManager(sm);
+
+ Subject subject = SecurityUtils.getSubject();
+
+ AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
+ subject.login(token);
+ subject.getSession().setAttribute("key", "value");
+ assertTrue(subject.getSession().getAttribute("key").equals("value"));
+
+ subject = SecurityUtils.getSubject();
+
+ assertTrue(subject.isAuthenticated());
+ assertTrue(subject.getSession().getAttribute("key").equals("value"));
+
+ sm.destroy();
+ }
+}
diff --git a/core/test/org/jsecurity/subject/DelegatingSubjectTest.java b/core/test/org/jsecurity/subject/DelegatingSubjectTest.java
new file mode 100644
index 0000000..62a51d7
--- /dev/null
+++ b/core/test/org/jsecurity/subject/DelegatingSubjectTest.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.subject;
+
+import org.jsecurity.mgt.DefaultSecurityManager;
+import org.jsecurity.session.Session;
+import org.jsecurity.util.ThreadContext;
+import org.junit.After;
+import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.Serializable;
+
+/**
+ * @author Les Hazlewood
+ * @since Aug 1, 2008 2:11:17 PM
+ */
+public class DelegatingSubjectTest {
+
+ @Before
+ public void setup() {
+ ThreadContext.clear();
+ }
+
+ @After
+ public void tearDown() {
+ ThreadContext.clear();
+ }
+
+ @Test
+ public void testSessionStopThenStart() {
+ String key = "testKey";
+ String value = "testValue";
+ DefaultSecurityManager sm = new DefaultSecurityManager();
+
+ DelegatingSubject subject = new DelegatingSubject(sm);
+
+ Session session = subject.getSession();
+ session.setAttribute(key, value);
+ assertTrue(session.getAttribute(key).equals(value));
+ Serializable firstSessionId = session.getId();
+ assertNotNull(firstSessionId);
+
+ session.stop();
+
+ session = subject.getSession();
+ assertNotNull(session);
+ assertNull(session.getAttribute(key));
+ Serializable secondSessionId = session.getId();
+ assertNotNull(secondSessionId);
+ assertFalse(firstSessionId.equals(secondSessionId));
+
+ subject.logout();
+
+ sm.destroy();
+ }
+}
diff --git a/core/test/org/jsecurity/util/StringUtilsTest.java b/core/test/org/jsecurity/util/StringUtilsTest.java
new file mode 100644
index 0000000..a3144c8
--- /dev/null
+++ b/core/test/org/jsecurity/util/StringUtilsTest.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.util;
+
+import static org.junit.Assert.*;
+import org.junit.Test;
+
+/**
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class StringUtilsTest {
+
+ @Test
+ public void splitWithNullInput() {
+ String line = null;
+ String[] split = StringUtils.split(line);
+ assertNull(split);
+ }
+
+ @Test
+ public void splitWithCommas() {
+ String line = "shall,we,play,a,game?";
+ String[] split = StringUtils.split(line);
+ assertNotNull(split);
+ assertTrue(split.length == 5);
+ assertEquals("shall", split[0]);
+ assertEquals("we", split[1]);
+ assertEquals("play", split[2]);
+ assertEquals("a", split[3]);
+ assertEquals("game?", split[4]);
+ }
+
+ @Test
+ public void splitWithCommasAndSpaces() {
+ String line = "shall,we , play, a,game?";
+ String[] split = StringUtils.split(line);
+ assertNotNull(split);
+ assertTrue(split.length == 5);
+ assertEquals("shall", split[0]);
+ assertEquals("we", split[1]);
+ assertEquals("play", split[2]);
+ assertEquals("a", split[3]);
+ assertEquals("game?", split[4]);
+ }
+
+ @Test
+ public void splitWithQuotedCommasAndSpaces() {
+ String line = "shall, \"we, play\", a, game?";
+ String[] split = StringUtils.split(line);
+ assertNotNull(split);
+ assertTrue(split.length == 4);
+ assertEquals("shall", split[0]);
+ assertEquals("we, play", split[1]);
+ assertEquals("a", split[2]);
+ assertEquals("game?", split[3]);
+ }
+
+ @Test
+ public void splitWithQuotedCommasAndSpacesAndDifferentQuoteChars() {
+ String line = "authc, test[blah], test[1,2,3], test[]";
+ String[] split = StringUtils.split(line, ',', '[', ']', false, true);
+ assertNotNull(split);
+ assertTrue(split.length == 4);
+ assertEquals("authc", split[0]);
+ assertEquals("testblah", split[1]);
+ assertEquals("test1,2,3", split[2]);
+ assertEquals("test", split[3]);
+ }
+
+ @Test
+ public void splitWithQuotedCommasAndSpacesAndDifferentQuoteCharsWhileRetainingQuotes() {
+ String line = "authc, test[blah], test[1,2,3], test[]";
+ String[] split = StringUtils.split(line, ',', '[', ']', true, true);
+ assertNotNull(split);
+ assertTrue(split.length == 4);
+ assertEquals("authc", split[0]);
+ assertEquals("test[blah]", split[1]);
+ assertEquals("test[1,2,3]", split[2]);
+ assertEquals("test[]", split[3]);
+ }
+
+ @Test
+ public void splitWithQuotedCommasAndSpacesAndEscapedQuotes() {
+ String line = "shall, \"\"\"we, play\", a, \"\"\"game?";
+ String[] split = StringUtils.split(line);
+ assertNotNull(split);
+ assertTrue(split.length == 4);
+ assertEquals("shall", split[0]);
+ assertEquals("\"we, play", split[1]);
+ assertEquals("a", split[2]);
+ assertEquals("\"game?", split[3]);
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/DefaultWebSecurityManager.java b/web/src/org/jsecurity/web/DefaultWebSecurityManager.java
new file mode 100644
index 0000000..1831619
--- /dev/null
+++ b/web/src/org/jsecurity/web/DefaultWebSecurityManager.java
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.mgt.DefaultSecurityManager;
+import org.jsecurity.realm.Realm;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.mgt.SessionManager;
+import org.jsecurity.subject.PrincipalCollection;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.LifecycleUtils;
+import org.jsecurity.web.session.DefaultWebSessionManager;
+import org.jsecurity.web.session.ServletContainerSessionManager;
+import org.jsecurity.web.session.WebSessionManager;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.net.InetAddress;
+import java.util.Collection;
+
+/**
+ * SecurityManager implementation that should be used in web-based applications or any application that requires
+ * HTTP connectivity (SOAP, http remoting, etc).
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class DefaultWebSecurityManager extends DefaultSecurityManager {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(DefaultWebSecurityManager.class);
+
+ public static final String HTTP_SESSION_MODE = "http";
+ public static final String JSECURITY_SESSION_MODE = "jsecurity";
+
+ /**
+ * The key that is used to store subject principals in the session.
+ */
+ public static final String PRINCIPALS_SESSION_KEY = DefaultWebSecurityManager.class.getName() + "_PRINCIPALS_SESSION_KEY";
+
+ /**
+ * The key that is used to store whether or not the user is authenticated in the session.
+ */
+ public static final String AUTHENTICATED_SESSION_KEY = DefaultWebSecurityManager.class.getName() + "_AUTHENTICATED_SESSION_KEY";
+
+ private String sessionMode = HTTP_SESSION_MODE; //default
+
+ public DefaultWebSecurityManager() {
+ setRememberMeManager(new WebRememberMeManager());
+ }
+
+ public DefaultWebSecurityManager(Realm singleRealm) {
+ setRealm(singleRealm);
+ }
+
+ public DefaultWebSecurityManager(Collection<Realm> realms) {
+ setRealms(realms);
+ }
+
+ /**
+ * Sets the path used to store the remember me cookie. This determines which paths
+ * are able to view the remember me cookie.
+ *
+ * @param rememberMeCookiePath the path to use for the remember me cookie.
+ */
+ public void setRememberMeCookiePath(String rememberMeCookiePath) {
+ ((WebRememberMeManager) getRememberMeManager()).setCookiePath(rememberMeCookiePath);
+ }
+
+ /**
+ * Sets the maximum age allowed for the remember me cookie. This basically sets how long
+ * a user will be remembered by the "remember me" feature. Used when calling
+ * {@link javax.servlet.http.Cookie#setMaxAge(int) maxAge}. Please see that JavaDoc for the semantics on the
+ * repercussions of negative, zero, and positive values for the maxAge.
+ *
+ * @param rememberMeMaxAge the maximum age for the remember me cookie.
+ */
+ public void setRememberMeCookieMaxAge(Integer rememberMeMaxAge) {
+ ((WebRememberMeManager) getRememberMeManager()).setCookieMaxAge(rememberMeMaxAge);
+ }
+
+ private DefaultWebSessionManager getSessionManagerForCookieAttributes() {
+ SessionManager sessionManager = getSessionManager();
+ if (!(sessionManager instanceof DefaultWebSessionManager)) {
+ String msg = "The convenience passthrough methods for setting session id cookie attributes " +
+ "are only available when the underlying SessionManager implementation is " +
+ DefaultWebSessionManager.class.getName() + ", which is enabled by default when the " +
+ "sessionMode is 'jsecurity'.";
+ throw new IllegalStateException(msg);
+ }
+ return (DefaultWebSessionManager) sessionManager;
+ }
+
+ public void setSessionIdCookieName(String name) {
+ getSessionManagerForCookieAttributes().setSessionIdCookieName(name);
+ }
+
+ public void setSessionIdCookiePath(String path) {
+ getSessionManagerForCookieAttributes().setSessionIdCookiePath(path);
+ }
+
+ public void setSessionIdCookieMaxAge(int maxAge) {
+ getSessionManagerForCookieAttributes().setSessionIdCookieMaxAge(maxAge);
+ }
+
+ public void setSessionIdCookieSecure(boolean secure) {
+ getSessionManagerForCookieAttributes().setSessionIdCookieSecure(secure);
+ }
+
+ public String getSessionMode() {
+ return sessionMode;
+ }
+
+ public void setSessionMode(String sessionMode) {
+ if (sessionMode == null ||
+ (!sessionMode.equals(HTTP_SESSION_MODE) && !sessionMode.equals(JSECURITY_SESSION_MODE))) {
+ String msg = "Invalid sessionMode [" + sessionMode + "]. Allowed values are " +
+ "public static final String constants in the " + getClass().getName() + " class: '"
+ + HTTP_SESSION_MODE + "' or '" + JSECURITY_SESSION_MODE + "', with '" +
+ HTTP_SESSION_MODE + "' being the default.";
+ throw new IllegalArgumentException(msg);
+ }
+ boolean recreate = this.sessionMode == null || !this.sessionMode.equals(sessionMode);
+ this.sessionMode = sessionMode;
+ if (recreate) {
+ LifecycleUtils.destroy(getSessionManager());
+ SessionManager sm = createSessionManager();
+ setSessionManager(sm);
+ }
+ }
+
+ public boolean isHttpSessionMode() {
+ return this.sessionMode == null || this.sessionMode.equals(HTTP_SESSION_MODE);
+ }
+
+ protected SessionManager newSessionManagerInstance() {
+ if (isHttpSessionMode()) {
+ if (log.isInfoEnabled()) {
+ log.info(HTTP_SESSION_MODE + " mode - enabling ServletContainerSessionManager (Http Sessions)");
+ }
+ return new ServletContainerSessionManager();
+ } else {
+ if (log.isInfoEnabled()) {
+ log.info(JSECURITY_SESSION_MODE + " mode - enabling WebSessionManager (JSecurity heterogenous sessions)");
+ }
+ return new DefaultWebSessionManager();
+ }
+ }
+
+ protected PrincipalCollection getPrincipals(Session session) {
+ PrincipalCollection principals = null;
+ if (session != null) {
+ principals = (PrincipalCollection) session.getAttribute(PRINCIPALS_SESSION_KEY);
+ }
+ return principals;
+ }
+
+ protected PrincipalCollection getPrincipals(Session existing, ServletRequest servletRequest, ServletResponse servletResponse) {
+ PrincipalCollection principals = getPrincipals(existing);
+ if (principals == null) {
+ //check remember me:
+ principals = getRememberedIdentity();
+ if (principals != null && existing != null) {
+ existing.setAttribute(PRINCIPALS_SESSION_KEY, principals);
+ }
+ }
+ return principals;
+ }
+
+ protected boolean isAuthenticated(Session session) {
+ Boolean value = null;
+ if (session != null) {
+ value = (Boolean) session.getAttribute(AUTHENTICATED_SESSION_KEY);
+ }
+ return value != null && value;
+ }
+
+ protected boolean isAuthenticated(Session existing, ServletRequest servletRequest, ServletResponse servletResponse) {
+ return isAuthenticated(existing);
+ }
+
+ public Subject createSubject() {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ return createSubject(request, response);
+ }
+
+ public Subject createSubject(ServletRequest request, ServletResponse response) {
+ Session session = ((WebSessionManager) getSessionManager()).getSession(request, response);
+ if (session == null) {
+ if (log.isTraceEnabled()) {
+ log.trace("No session found for the incoming request. The Subject instance created for " +
+ "the incoming request will not have an associated Session.");
+ }
+ }
+ return createSubject(session, request, response);
+ }
+
+ public Subject createSubject(Session existing, ServletRequest request, ServletResponse response) {
+ PrincipalCollection principals = getPrincipals(existing, request, response);
+ boolean authenticated = isAuthenticated(existing, request, response);
+ return createSubject(principals, authenticated, existing, request, response);
+ }
+
+ protected Subject createSubject(PrincipalCollection principals,
+ boolean authenticated,
+ Session existing,
+ ServletRequest request,
+ ServletResponse response) {
+ InetAddress inetAddress = WebUtils.getInetAddress(request);
+ return createSubject(principals, existing, authenticated, inetAddress);
+ }
+
+ protected void bind(Subject subject) {
+ super.bind(subject);
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ bind(subject, request, response);
+ }
+
+ protected void bind(Subject subject, ServletRequest request, ServletResponse response) {
+
+ PrincipalCollection principals = subject.getPrincipals();
+ if (principals != null && !principals.isEmpty()) {
+ Session session = subject.getSession();
+ session.setAttribute(PRINCIPALS_SESSION_KEY, principals);
+ } else {
+ Session session = subject.getSession(false);
+ if (session != null) {
+ session.removeAttribute(PRINCIPALS_SESSION_KEY);
+ }
+ }
+
+ if (subject.isAuthenticated()) {
+ Session session = subject.getSession();
+ session.setAttribute(AUTHENTICATED_SESSION_KEY, subject.isAuthenticated());
+ } else {
+ Session session = subject.getSession(false);
+ if (session != null) {
+ session.removeAttribute(AUTHENTICATED_SESSION_KEY);
+ }
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/RedirectView.java b/web/src/org/jsecurity/web/RedirectView.java
new file mode 100644
index 0000000..b554c52
--- /dev/null
+++ b/web/src/org/jsecurity/web/RedirectView.java
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.util.JavaEnvironment;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Map;
+
+/**
+ * <p>View that redirects to an absolute, context relative, or current request
+ * relative URL, exposing all model attributes as HTTP query parameters.
+ *
+ * <p>A URL for this view is supposed to be a HTTP redirect URL, i.e.
+ * suitable for HttpServletResponse's <code>sendRedirect</code> method, which
+ * is what actually does the redirect if the HTTP 1.0 flag is on, or via sending
+ * back an HTTP 303 code - if the HTTP 1.0 compatibility flag is off.
+ *
+ * <p>Note that while the default value for the "contextRelative" flag is off,
+ * you will probably want to almost always set it to true. With the flag off,
+ * URLs starting with "/" are considered relative to the web server root, while
+ * with the flag on, they are considered relative to the web application root.
+ * Since most web apps will never know or care what their context path actually
+ * is, they are much better off setting this flag to true, and submitting paths
+ * which are to be considered relative to the web application root.
+ *
+ * <p>Note that in a Servlet 2.2 environment, i.e. a servlet container which
+ * is only compliant to the limits of this spec, this class will probably fail
+ * when feeding in URLs which are not fully absolute, or relative to the current
+ * request (no leading "/"), as these are the only two types of URL that
+ * <code>sendRedirect</code> supports in a Servlet 2.2 environment.
+ *
+ * <p><em>This class was borrowed from a nearly identical version found in
+ * the <a href="http://www.springframework.org/">Spring Framework</a>, with minor modifications to
+ * avoid a dependency on Spring itself for a very small amount of code - we couldn't have done it better, and
+ * don't want to repeat all of their great effort ;).
+ * The original author names and copyright (Apache 2.0) has been left in place. A special
+ * thanks to Rod Johnson, Juergen Hoeller, and Colin Sampaleanu for making this available.</em>
+ *
+ * @author Rod Johnson
+ * @author Juergen Hoeller
+ * @author Colin Sampaleanu
+ * @see #setContextRelative
+ * @see #setHttp10Compatible
+ * @see javax.servlet.http.HttpServletResponse#sendRedirect
+ * @since 0.2
+ */
+@SuppressWarnings({"deprecation"})
+public class RedirectView {
+
+ //TODO - complete JavaDoc
+
+ /**
+ * The default encoding scheme: UTF-8
+ */
+ public static final String DEFAULT_ENCODING_SCHEME = "UTF-8";
+
+ private static final Log log = LogFactory.getLog(RedirectView.class);
+
+ private String url;
+
+ private boolean contextRelative = false;
+
+ private boolean http10Compatible = true;
+
+ private String encodingScheme = DEFAULT_ENCODING_SCHEME;
+
+ /**
+ * Constructor for use as a bean.
+ */
+ public RedirectView() {
+ }
+
+ /**
+ * Create a new RedirectView with the given URL.
+ * <p>The given URL will be considered as relative to the web server,
+ * not as relative to the current ServletContext.
+ *
+ * @param url the URL to redirect to
+ * @see #RedirectView(String, boolean)
+ */
+ public RedirectView(String url) {
+ setUrl(url);
+ }
+
+ /**
+ * Create a new RedirectView with the given URL.
+ *
+ * @param url the URL to redirect to
+ * @param contextRelative whether to interpret the given URL as
+ * relative to the current ServletContext
+ */
+ public RedirectView(String url, boolean contextRelative) {
+ this(url);
+ this.contextRelative = contextRelative;
+ }
+
+ /**
+ * Create a new RedirectView with the given URL.
+ *
+ * @param url the URL to redirect to
+ * @param contextRelative whether to interpret the given URL as
+ * relative to the current ServletContext
+ * @param http10Compatible whether to stay compatible with HTTP 1.0 clients
+ */
+ public RedirectView(String url, boolean contextRelative, boolean http10Compatible) {
+ this(url);
+ this.contextRelative = contextRelative;
+ this.http10Compatible = http10Compatible;
+ }
+
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ /**
+ * Set whether to interpret a given URL that starts with a slash ("/")
+ * as relative to the current ServletContext, i.e. as relative to the
+ * web application root.
+ * <p>Default is "false": A URL that starts with a slash will be interpreted
+ * as absolute, i.e. taken as-is. If true, the context path will be
+ * prepended to the URL in such a case.
+ *
+ * @see javax.servlet.http.HttpServletRequest#getContextPath
+ */
+ public void setContextRelative(boolean contextRelative) {
+ this.contextRelative = contextRelative;
+ }
+
+ /**
+ * Set whether to stay compatible with HTTP 1.0 clients.
+ * <p>In the default implementation, this will enforce HTTP status code 302
+ * in any case, i.e. delegate to <code>HttpServletResponse.sendRedirect</code>.
+ * Turning this off will send HTTP status code 303, which is the correct
+ * code for HTTP 1.1 clients, but not understood by HTTP 1.0 clients.
+ * <p>Many HTTP 1.1 clients treat 302 just like 303, not making any
+ * difference. However, some clients depend on 303 when redirecting
+ * after a POST request; turn this flag off in such a scenario.
+ *
+ * @see javax.servlet.http.HttpServletResponse#sendRedirect
+ */
+ public void setHttp10Compatible(boolean http10Compatible) {
+ this.http10Compatible = http10Compatible;
+ }
+
+ /**
+ * Set the encoding scheme for this view. Default is UTF-8.
+ */
+ public void setEncodingScheme(String encodingScheme) {
+ this.encodingScheme = encodingScheme;
+ }
+
+
+ /**
+ * Convert model to request parameters and redirect to the given URL.
+ *
+ * @see #appendQueryProperties
+ * @see #sendRedirect
+ */
+ public final void renderMergedOutputModel(
+ Map model, HttpServletRequest request, HttpServletResponse response) throws IOException {
+
+ // Prepare name URL.
+ StringBuffer targetUrl = new StringBuffer();
+ if (this.contextRelative && getUrl().startsWith("/")) {
+ // Do not apply context path to relative URLs.
+ targetUrl.append(request.getContextPath());
+ }
+ targetUrl.append(getUrl());
+ appendQueryProperties(targetUrl, model, this.encodingScheme);
+
+ sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);
+ }
+
+ /**
+ * Append query properties to the redirect URL.
+ * Stringifies, URL-encodes and formats model attributes as query properties.
+ *
+ * @param targetUrl the StringBuffer to append the properties to
+ * @param model Map that contains model attributes
+ * @param encodingScheme the encoding scheme to use
+ * @throws java.io.UnsupportedEncodingException
+ * if string encoding failed
+ * @see #queryProperties
+ */
+ protected void appendQueryProperties(StringBuffer targetUrl, Map model, String encodingScheme)
+ throws UnsupportedEncodingException {
+
+ // Extract anchor fragment, if any.
+ // The following code does not use JDK 1.4's StringBuffer.indexOf(String)
+ // method to retain JDK 1.3 compatibility.
+ String fragment = null;
+ int anchorIndex = targetUrl.toString().indexOf('#');
+ if (anchorIndex > -1) {
+ fragment = targetUrl.substring(anchorIndex);
+ targetUrl.delete(anchorIndex, targetUrl.length());
+ }
+
+ // If there aren't already some parameters, we need a "?".
+ boolean first = (getUrl().indexOf('?') < 0);
+ Map queryProps = queryProperties(model);
+
+ if (queryProps != null) {
+ for (Object o : queryProps.entrySet()) {
+ if (first) {
+ targetUrl.append('?');
+ first = false;
+ } else {
+ targetUrl.append('&');
+ }
+ Map.Entry entry = (Map.Entry) o;
+ String encodedKey = urlEncode(entry.getKey().toString(), encodingScheme);
+ String encodedValue =
+ (entry.getValue() != null ? urlEncode(entry.getValue().toString(), encodingScheme) : "");
+ targetUrl.append(encodedKey).append('=').append(encodedValue);
+ }
+ }
+
+ // Append anchor fragment, if any, to end of URL.
+ if (fragment != null) {
+ targetUrl.append(fragment);
+ }
+ }
+
+ /**
+ * URL-encode the given input String with the given encoding scheme.
+ * <p>Default implementation uses <code>URLEncoder.encode(input, enc)</code>
+ * on JDK 1.4+, falling back to <code>URLEncoder.encode(input)</code>
+ * (which uses the platform default encoding) on JDK 1.3.
+ *
+ * @param input the unencoded input String
+ * @param encodingScheme the encoding scheme
+ * @return the encoded output String
+ * @throws UnsupportedEncodingException if thrown by the JDK URLEncoder
+ * @see java.net.URLEncoder#encode(String, String)
+ * @see java.net.URLEncoder#encode(String)
+ */
+ protected String urlEncode(String input, String encodingScheme) throws UnsupportedEncodingException {
+ if (!JavaEnvironment.isAtLeastVersion14()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Only JDK 1.3 URLEncoder available: using platform default encoding " +
+ "instead of the requested scheme '" + encodingScheme + "'");
+ }
+ return URLEncoder.encode(input);
+ }
+ return URLEncoder.encode(input, encodingScheme);
+ }
+
+ /**
+ * Determine name-value pairs for query strings, which will be stringified,
+ * URL-encoded and formatted by appendQueryProperties.
+ * <p>This implementation returns all model elements as-is.
+ *
+ * @see #appendQueryProperties
+ */
+ protected Map queryProperties(Map model) {
+ return model;
+ }
+
+ /**
+ * Send a redirect back to the HTTP client
+ *
+ * @param request current HTTP request (allows for reacting to request method)
+ * @param response current HTTP response (for sending response headers)
+ * @param targetUrl the name URL to redirect to
+ * @param http10Compatible whether to stay compatible with HTTP 1.0 clients
+ * @throws IOException if thrown by response methods
+ */
+ protected void sendRedirect(
+ HttpServletRequest request, HttpServletResponse response, String targetUrl, boolean http10Compatible)
+ throws IOException {
+
+ if (http10Compatible) {
+ // Always send status code 302.
+ response.sendRedirect(response.encodeRedirectURL(targetUrl));
+ } else {
+ // Correct HTTP status code is 303, in particular for POST requests.
+ response.setStatus(303);
+ response.setHeader("Location", response.encodeRedirectURL(targetUrl));
+ }
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/SavedRequest.java b/web/src/org/jsecurity/web/SavedRequest.java
new file mode 100644
index 0000000..b45d796
--- /dev/null
+++ b/web/src/org/jsecurity/web/SavedRequest.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * Maintains request data for a request that was redirected, so that after authentication
+ * the user can be redirected to the originally requested page.
+ *
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public class SavedRequest {
+
+ //TODO - complete JavaDoc
+
+ private String method;
+ private String queryString;
+ private String requestURI;
+
+ /**
+ * Constructs a new instance from the given HTTP request.
+ * @param request the current request to save.
+ */
+ public SavedRequest( HttpServletRequest request ) {
+ this.method = request.getMethod();
+ this.queryString = request.getQueryString();
+ this.requestURI = request.getRequestURI();
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public String getQueryString() {
+ return queryString;
+ }
+
+ public String getRequestURI() {
+ return requestURI;
+ }
+
+ public String getRequestUrl() {
+ StringBuilder requestUrl = new StringBuilder( getRequestURI() );
+ if( getQueryString() != null ) {
+ requestUrl.append( "?" ).append( getQueryString() );
+ }
+ return requestUrl.toString();
+ }
+}
diff --git a/web/src/org/jsecurity/web/WebRememberMeManager.java b/web/src/org/jsecurity/web/WebRememberMeManager.java
new file mode 100644
index 0000000..f2739ab
--- /dev/null
+++ b/web/src/org/jsecurity/web/WebRememberMeManager.java
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.codec.Base64;
+import org.jsecurity.subject.AbstractRememberMeManager;
+import org.jsecurity.web.attr.CookieAttribute;
+import org.jsecurity.web.attr.WebAttribute;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * Remembers a Subject's identity by using a {@link WebAttribute WebAttribute} instance to retain
+ * the identity value between web requests.
+ *
+ * <p>This class's default <code>WebAttribute</code> instance is a {@link CookieAttribute CookieAttribute}, storing
+ * the Subject's {@link org.jsecurity.subject.Subject#getPrincipals principals} in a <code>Cookie</code>. Note that
+ * because this class subclasses the <code>AbstractRememberMeManager</code> which already provides serialization and
+ * encryption logic, this class utilizes both for added security before setting the cookie value.</p>
+ *
+ * <p>This class also contains "passthrough" JavaBeans-compatible getters/setters for the underlying
+ * <code>CookieAttribute</code>'s properties to make configuration easier.</p>
+ *
+ * <p>Note however as a basic sanity check, these passthrough methods will first assert that the underlying
+ * {@link #getIdentityAttribute identityAttribute} is actually a {@link CookieAttribute CookieAttribute}. If it
+ * is not, an {@link IllegalStateException} will be thrown. Because the default instance of this class <em>is</em>
+ * already <code>CookieAttribute</code>, you would only ever experience the exception if you explicitly
+ * override the internal instance with a different type and accidentally call one of these JavaBeans passthrough
+ * methods.</p>
+ *
+ * <p>Just be aware of this if you manually override the {@link #getIdentityAttribute identityAttribute} property
+ * to be an instance of something <em>other</em> than a <code>CookieAttribute</code>.</p>
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class WebRememberMeManager extends AbstractRememberMeManager {
+
+ //TODO - complete JavaDoc
+
+ private static transient final Log log = LogFactory.getLog( WebRememberMeManager.class );
+
+ /**
+ * The default name of the underlying rememberMe cookie which is <code>rememberMe</code>.
+ */
+ public static final String DEFAULT_REMEMBER_ME_COOKIE_NAME = "rememberMe";
+
+ protected WebAttribute<String> identityAttribute = null;
+
+ public WebRememberMeManager() {
+ CookieAttribute<String> attr = new CookieAttribute<String>(DEFAULT_REMEMBER_ME_COOKIE_NAME);
+ attr.setCheckRequestParams(false);
+ //Peter (JSecurity developer) said that Jetty didn't like the CookieAttribute.INDEFINITE value
+ // (Tomcat was ok with it), so just default to a few years for now. If anyone doesn't visit a site in 3 years
+ // after last login, I doubt any JSecurity users would mind their end-users to be forced to log in. - LAH.
+ attr.setMaxAge(CookieAttribute.ONE_YEAR * 3);
+ this.identityAttribute = attr;
+ }
+
+ public WebAttribute<String> getIdentityAttribute() {
+ return identityAttribute;
+ }
+
+ public void setIdentityAttribute(WebAttribute<String> identityAttribute) {
+ this.identityAttribute = identityAttribute;
+ }
+
+ protected void assertCookieAttribute() {
+ if (!(this.identityAttribute instanceof CookieAttribute)) {
+ String msg = "Attempting to access a Cookie property, but the underlying " +
+ WebAttribute.class.getName() + " instance is not a " +
+ CookieAttribute.class.getName() + " instance. This is expected if you " +
+ "are accessing or modifying a cookie property.";
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ /**
+ * Passthrough JavaBeans property that will get the underyling rememberMe cookie's name.
+ *
+ * <p>The default value is {@link #DEFAULT_REMEMBER_ME_COOKIE_NAME}</p>
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @return the underlying rememberMe cookie's name
+ */
+ public String getCookieName() {
+ assertCookieAttribute();
+ return ((CookieAttribute) this.identityAttribute).getName();
+ }
+
+ /**
+ * Passthrough JavaBeans property that will set the underyling rememberMe cookie's name.
+ *
+ * <p>The default value is {@link #DEFAULT_REMEMBER_ME_COOKIE_NAME}</p>
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @param name the name to assign to the underlying rememberMe cookie
+ */
+ public void setCookieName(String name) {
+ assertCookieAttribute();
+ ((CookieAttribute) this.identityAttribute).setName(name);
+ }
+
+ /**
+ * Passthrough JavaBeans property that will get the underyling rememberMe cookie's path.
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @return the underlying rememberMe cookie's path
+ */
+ public String getCookiePath() {
+ assertCookieAttribute();
+ return ((CookieAttribute) this.identityAttribute).getPath();
+ }
+
+ /**
+ * Passthrough JavaBeans property that will set the underyling rememberMe cookie's path.
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @param path the path to assign to the underlying rememberMe cookie
+ */
+ public void setCookiePath(String path) {
+ assertCookieAttribute();
+ ((CookieAttribute) this.identityAttribute).setPath(path);
+ }
+
+ /**
+ * Passthrough JavaBeans property that will get the underyling rememberMe cookie's max age.
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @return the underlying rememberMe cookie's max age.
+ */
+ public int getCookieMaxAge() {
+ assertCookieAttribute();
+ return ((CookieAttribute) this.identityAttribute).getMaxAge();
+ }
+
+ /**
+ * Passthrough JavaBeans property that will get the underyling rememberMe cookie's max age.
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @param maxAge the max age to assign to the underlying rememberMe cookie
+ */
+ public void setCookieMaxAge(int maxAge) {
+ assertCookieAttribute();
+ ((CookieAttribute) this.identityAttribute).setMaxAge(maxAge);
+ }
+
+ /**
+ * Passthrough JavaBeans property that will get the underyling rememberMe cookie's 'secure' status.
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @return the underlying rememberMe cookie's 'secure' flag
+ */
+ public boolean isCookieSecure() {
+ assertCookieAttribute();
+ return ((CookieAttribute) this.identityAttribute).isSecure();
+ }
+
+ /**
+ * Passthrough JavaBeans property that will set the underyling rememberMe cookie's 'secure' status.
+ *
+ * <p>This method performs a quick <code>CookieAttribute</code> sanity check as described in the class-level JavaDoc.</p>
+ *
+ * @param secure the 'secure' flag to assign to the underlying rememberMe cookie.
+ */
+ public void setCookieSecure(boolean secure) {
+ assertCookieAttribute();
+ ((CookieAttribute) this.identityAttribute).setSecure(secure);
+ }
+
+ protected void rememberSerializedIdentity(byte[] serialized) {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ //base 64 encode it and store as a cookie:
+ String base64 = Base64.encodeToString(serialized);
+ getIdentityAttribute().storeValue(base64, request, response);
+ }
+
+ protected byte[] getSerializedRememberedIdentity() {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ String base64 = getIdentityAttribute().retrieveValue(request, response);
+ if (base64 != null) {
+ if ( log.isTraceEnabled() ) {
+ log.trace( "Acquired Base64 encoded identity [" + base64 + "]" );
+ }
+ byte[] decoded = Base64.decode(base64);
+ if ( log.isTraceEnabled() ) {
+ log.trace( "Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes." );
+ }
+ return decoded;
+ } else {
+ //no cookie set - new site visitor?
+ return null;
+ }
+ }
+
+ protected void forgetIdentity() {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ getIdentityAttribute().removeValue(request, response);
+ }
+}
diff --git a/web/src/org/jsecurity/web/WebUtils.java b/web/src/org/jsecurity/web/WebUtils.java
new file mode 100644
index 0000000..141dd7f
--- /dev/null
+++ b/web/src/org/jsecurity/web/WebUtils.java
@@ -0,0 +1,554 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.SecurityUtils;
+import org.jsecurity.session.Session;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.StringUtils;
+import org.jsecurity.util.ThreadContext;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.InetAddress;
+import java.net.URLDecoder;
+import java.net.UnknownHostException;
+import java.util.Map;
+
+/**
+ * Simple utility class for operations used across multiple class hierarchies in the web framework code.
+ *
+ * <p>Some methods in this class were copied from the Spring Framework so we didn't have to re-invent the wheel,
+ * and in these cases, we have retained all license, copyright and author information.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @author Rod Johnson
+ * @author Juergen Hoeller
+ * @since 0.9
+ */
+public class WebUtils {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(WebUtils.class);
+
+
+ /**
+ * Message displayed when a servlet request or response is not bound to the current thread context when expected.
+ */
+ private static final String NOT_BOUND_ERROR_MESSAGE =
+ "Make sure WebUtils.bind() is being called. (typically called by JSecurityFilter) " +
+ "This could also happen when running integration tests that don't properly call WebUtils.bind().";
+
+ public static final String SERVLET_REQUEST_KEY = ServletRequest.class.getName() + "_JSECURITY_THREAD_CONTEXT_KEY";
+ public static final String SERVLET_RESPONSE_KEY = ServletResponse.class.getName() + "_JSECURITY_THREAD_CONTEXT_KEY";
+
+ /**
+ * {@link Session Session} key used to save a request and later restore it, for example when redirecting to a
+ * requested page after login, equal to <code>jsecuritySavedRequest</code>.
+ */
+ public static final String SAVED_REQUEST_KEY = "jsecuritySavedRequest";
+
+
+ /**
+ * Standard Servlet 2.3+ spec request attributes for include URI and paths.
+ * <p>If included via a RequestDispatcher, the current resource will see the
+ * originating request. Its own URI and paths are exposed as request attributes.
+ */
+ public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
+ public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path";
+ public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = "javax.servlet.include.servlet_path";
+ public static final String INCLUDE_PATH_INFO_ATTRIBUTE = "javax.servlet.include.path_info";
+ public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = "javax.servlet.include.query_string";
+
+ /**
+ * Standard Servlet 2.4+ spec request attributes for forward URI and paths.
+ * <p>If forwarded to via a RequestDispatcher, the current resource will see its
+ * own URI and paths. The originating URI and paths are exposed as request attributes.
+ */
+ public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";
+ public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path";
+ public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path";
+ public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info";
+ public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";
+
+ /**
+ * Default character encoding to use when <code>request.getCharacterEncoding</code>
+ * returns <code>null</code>, according to the Servlet spec.
+ *
+ * @see javax.servlet.ServletRequest#getCharacterEncoding
+ */
+ public static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";
+
+ /**
+ * Return the path within the web application for the given request.
+ * <p>Detects include request URL if called within a RequestDispatcher include.
+ * <p/>
+ * For example, for a request to URL
+ * <p/>
+ * <code>http://www.somehost.com/myapp/my/url.jsp</code>,
+ * <p/>
+ * for an application deployed to <code>/mayapp</code> (the application's context path), this method would return
+ * <p/>
+ * <code>/my/url.jsp</code>.
+ *
+ * @param request current HTTP request
+ * @return the path within the web application
+ */
+ public static String getPathWithinApplication(HttpServletRequest request) {
+ String contextPath = getContextPath(request);
+ String requestUri = getRequestUri(request);
+ if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) {
+ // Normal case: URI contains context path.
+ String path = requestUri.substring(contextPath.length());
+ return (StringUtils.hasText(path) ? path : "/");
+ } else {
+ // Special case: rather unusual.
+ return requestUri;
+ }
+ }
+
+ /**
+ * Return the request URI for the given request, detecting an include request
+ * URL if called within a RequestDispatcher include.
+ * <p>As the value returned by <code>request.getRequestURI()</code> is <i>not</i>
+ * decoded by the servlet container, this method will decode it.
+ * <p>The URI that the web container resolves <i>should</i> be correct, but some
+ * containers like JBoss/Jetty incorrectly include ";" strings like ";jsessionid"
+ * in the URI. This method cuts off such incorrect appendices.
+ *
+ * @param request current HTTP request
+ * @return the request URI
+ */
+ public static String getRequestUri(HttpServletRequest request) {
+ String uri = (String) request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE);
+ if (uri == null) {
+ uri = request.getRequestURI();
+ }
+ return decodeAndCleanUriString(request, uri);
+ }
+
+ /**
+ * Decode the supplied URI string and strips any extraneous portion after a ';'.
+ *
+ * @param request the incoming HttpServletRequest
+ * @param uri the application's URI string
+ * @return the supplied URI string stripped of any extraneous portion after a ';'.
+ */
+ private static String decodeAndCleanUriString(HttpServletRequest request, String uri) {
+ uri = decodeRequestString(request, uri);
+ int semicolonIndex = uri.indexOf(';');
+ return (semicolonIndex != -1 ? uri.substring(0, semicolonIndex) : uri);
+ }
+
+ /**
+ * Return the context path for the given request, detecting an include request
+ * URL if called within a RequestDispatcher include.
+ * <p>As the value returned by <code>request.getContextPath()</code> is <i>not</i>
+ * decoded by the servlet container, this method will decode it.
+ *
+ * @param request current HTTP request
+ * @return the context path
+ */
+ public static String getContextPath(HttpServletRequest request) {
+ String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE);
+ if (contextPath == null) {
+ contextPath = request.getContextPath();
+ }
+ if ("/".equals(contextPath)) {
+ // Invalid case, but happens for includes on Jetty: silently adapt it.
+ contextPath = "";
+ }
+ return decodeRequestString(request, contextPath);
+ }
+
+ /**
+ * Decode the given source string with a URLDecoder. The encoding will be taken
+ * from the request, falling back to the default "ISO-8859-1".
+ * <p>The default implementation uses <code>URLDecoder.decode(input, enc)</code>.
+ *
+ * @param request current HTTP request
+ * @param source the String to decode
+ * @return the decoded String
+ * @see #DEFAULT_CHARACTER_ENCODING
+ * @see javax.servlet.ServletRequest#getCharacterEncoding
+ * @see java.net.URLDecoder#decode(String, String)
+ * @see java.net.URLDecoder#decode(String)
+ */
+ @SuppressWarnings({"deprecation"})
+ public static String decodeRequestString(HttpServletRequest request, String source) {
+ String enc = determineEncoding(request);
+ try {
+ return URLDecoder.decode(source, enc);
+ }
+ catch (UnsupportedEncodingException ex) {
+ if (log.isWarnEnabled()) {
+ log.warn("Could not decode request string [" + source + "] with encoding '" + enc +
+ "': falling back to platform default encoding; exception message: " + ex.getMessage());
+ }
+ return URLDecoder.decode(source);
+ }
+ }
+
+ /**
+ * Determine the encoding for the given request.
+ * Can be overridden in subclasses.
+ * <p>The default implementation checks the request's
+ * {@link ServletRequest#getCharacterEncoding() character encoding}, and if that
+ * <code>null</code>, falls back to the {@link #DEFAULT_CHARACTER_ENCODING}.
+ *
+ * @param request current HTTP request
+ * @return the encoding for the request (never <code>null</code>)
+ * @see javax.servlet.ServletRequest#getCharacterEncoding()
+ */
+ protected static String determineEncoding(HttpServletRequest request) {
+ String enc = request.getCharacterEncoding();
+ if (enc == null) {
+ enc = DEFAULT_CHARACTER_ENCODING;
+ }
+ return enc;
+ }
+
+ /**
+ * Returns the <code>InetAddress</code> associated with the current request, or <code>null</code> if the
+ * address cannot be resolved/determined.
+ * <p/>
+ * This implementation returns the InetAddress resolved from the request's
+ * {@link javax.servlet.ServletRequest#getRemoteHost() remoteHost} value. The returned <code>String</code>
+ * is resolved to an InetAddress by calling
+ * {@link InetAddress#getByName(String) InetAddress.getByName(remoteHost)}. If the remote host is <code>null</code>
+ * or <code>getByName(remoteHost)</code> throws an exception, <code>null</code> is returned.
+ *
+ * @param request the incoming ServletRequest
+ * @return the <code>InetAddress</code> associated with the current request, or <code>null</code> if the
+ * address cannot be resolved/determined.
+ */
+ public static InetAddress getInetAddress(ServletRequest request) {
+ InetAddress clientAddress = null;
+ //get the Host/IP the client is coming from:
+ String addrString = request.getRemoteHost();
+ try {
+ clientAddress = InetAddress.getByName(addrString);
+ } catch (UnknownHostException e) {
+ if (log.isInfoEnabled()) {
+ log.info("Unable to acquire InetAddress from ServletRequest", e);
+ }
+ }
+
+ return clientAddress;
+ }
+
+ /**
+ * A convenience method that merely casts the incoming <code>ServletRequest</code> to an
+ * <code>HttpServletRequest</code>:
+ * <p/>
+ * <code>return (HttpServletRequest)request;</code>
+ * <p/>
+ * Logic could be changed in the future for logging or throwing an meaningful exception in
+ * non HTTP request environments (e.g. Portlet API).
+ *
+ * @param request the incoming ServletRequest
+ * @return the <code>request</code> argument casted to an <code>HttpServletRequest</code>.
+ */
+ public static HttpServletRequest toHttp(ServletRequest request) {
+ return (HttpServletRequest) request;
+ }
+
+ /**
+ * A convenience method that merely casts the incoming <code>ServletResponse</code> to an
+ * <code>HttpServletResponse</code>:
+ * <p/>
+ * <code>return (HttpServletResponse)response;</code>
+ * <p/>
+ * Logic could be changed in the future for logging or throwing an meaningful exception in
+ * non HTTP request environments (e.g. Portlet API).
+ *
+ * @param response the outgoing ServletResponse
+ * @return the <code>response</code> argument casted to an <code>HttpServletResponse</code>.
+ */
+ public static HttpServletResponse toHttp(ServletResponse response) {
+ return (HttpServletResponse) response;
+ }
+
+ public static void bindInetAddressToThread(ServletRequest request) {
+ InetAddress ip = getInetAddress(request);
+ if (ip != null) {
+ ThreadContext.bind(ip);
+ }
+ }
+
+ public static void unbindInetAddressFromThread() {
+ ThreadContext.unbindInetAddress();
+ }
+
+ /**
+ * Convenience method that simplifies retrieval of a required thread-bound ServletRequest. If there is no
+ * ServletRequest bound to the thread when this method is called, an <code>IllegalStateException</code> is
+ * thrown.
+ * <p/>
+ * This method is basically a convenient wrapper for the following:
+ * <p/>
+ * <code>(ServletRequest){@link ThreadContext#get ThreadContext.get}( SERVLET_REQUEST_KEY );</code>
+ * <p/>
+ * But throws an <code>IllegalStateException</code> if the value is not bound to the <code>ThreadContext</code>.
+ * <p/>
+ * This method only returns the bound value if it exists - it does not remove it
+ * from the thread. To remove it, one must call {@link #unbindServletRequest() unbindServletRequest} instead.
+ *
+ * @return the ServletRequest bound to the thread. Never returns null.
+ * @throws IllegalStateException if no servlet request is bound in the {@link ThreadContext ThreadContext}.
+ */
+ public static ServletRequest getRequiredServletRequest() throws IllegalStateException {
+ ServletRequest request = (ServletRequest) ThreadContext.get(SERVLET_REQUEST_KEY);
+ if (request == null) {
+ throw new IllegalStateException("No ServletRequest found in ThreadContext. " + NOT_BOUND_ERROR_MESSAGE);
+ }
+ return request;
+ }
+
+ /**
+ * Convenience method that simplifies binding a ServletRequest to the current thread (via the ThreadContext).
+ *
+ * <p>The method's existence is to help reduce casting in your own code and to simplify remembering of
+ * ThreadContext key names. The implementation is simple in that, if the servletRequest is not <tt>null</tt>,
+ * it binds it to the thread, i.e.:
+ *
+ * <pre>
+ * if (servletRequest != null) {
+ * ThreadContext.put( SERVLET_REQUEST_KEY, servletRequest );
+ * }</pre>
+ *
+ * @param servletRequest the ServletRequest object to bind to the thread. If the argument is null, nothing will be done.
+ */
+ public static void bind(ServletRequest servletRequest) {
+ if (servletRequest != null) {
+ ThreadContext.put(SERVLET_REQUEST_KEY, servletRequest);
+ }
+ }
+
+ /**
+ * Convenience method that simplifies removal of a thread-local ServletRequest from the thread.
+ * <p/>
+ * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is
+ * merely a conveient wrapper for the following:
+ * <p/>
+ * <code>return (ServletRequest)ThreadContext.remove( SERVLET_REQUEST_KEY );</code>
+ * <p/>
+ * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later during
+ * thread execution), you should use the {@link #getRequiredServletRequest() getRequiredServletRequest()} method
+ * for that purpose.
+ *
+ * @return the Session object previously bound to the thread, or <tt>null</tt> if there was none bound.
+ */
+ public static ServletRequest unbindServletRequest() {
+ return (ServletRequest) ThreadContext.remove(SERVLET_REQUEST_KEY);
+ }
+
+ /**
+ * Convenience method that simplifies retrieval of a required thread-bound ServletResponse. If there is no
+ * ServletResponse bound to the thread when this method is called, an <code>IllegalStateException</code> is
+ * thrown.
+ * <p/>
+ * This method is basically a convenient wrapper for the following:
+ * <p/>
+ * <code>return (ServletResponse){@link ThreadContext#get ThreadContext.get}( SERVLET_RESPONSE_KEY );</code>
+ * <p/>
+ * But throws an <code>IllegalStateException</code> if the value is not bound to the <code>ThreadContext</code>.
+ * <p/>
+ * This method only returns the bound value if it exists - it does not remove it
+ * from the thread. To remove it, one must call {@link #unbindServletResponse() unbindServletResponse} instead.
+ *
+ * @return the ServletResponse bound to the thread. Never returns null.
+ * @throws IllegalStateException if no <code>ServletResponse> is bound in the {@link ThreadContext ThreadContext}
+ */
+ public static ServletResponse getRequiredServletResponse() throws IllegalStateException {
+ ServletResponse response = (ServletResponse) ThreadContext.get(SERVLET_RESPONSE_KEY);
+ if (response == null) {
+ throw new IllegalStateException("No ServletResponse found in ThreadContext. " + NOT_BOUND_ERROR_MESSAGE);
+ }
+ return response;
+ }
+
+ /**
+ * Convenience method that simplifies binding a ServletResponse to the thread via the ThreadContext.
+ *
+ * <p>The method's existence is to help reduce casting in your own code and to simplify remembering of
+ * ThreadContext key names. The implementation is simple in that, if the servletResponse is not <tt>null</tt>,
+ * it binds it to the thread, i.e.:
+ *
+ * <pre>
+ * if (servletResponse != null) {
+ * ThreadContext.put( SERVLET_RESPONSE_KEY, servletResponse );
+ * }</pre>
+ *
+ * @param servletResponse the ServletResponse object to bind to the thread. If the argument is null, nothing will be done.
+ */
+ public static void bind(ServletResponse servletResponse) {
+ if (servletResponse != null) {
+ ThreadContext.put(SERVLET_RESPONSE_KEY, servletResponse);
+ }
+ }
+
+ /**
+ * Convenience method that simplifies removal of a thread-local ServletResponse from the thread.
+ * <p/>
+ * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is
+ * merely a conveient wrapper for the following:
+ * <p/>
+ * <code>return (ServletResponse)ThreadContext.remove( SERVLET_RESPONSE_KEY );</code>
+ * <p/>
+ * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later during
+ * thread execution), you should use the {@link #getRequiredServletResponse() getRequiredServletResponse()} method
+ * for that purpose.
+ *
+ * @return the Session object previously bound to the thread, or <tt>null</tt> if there was none bound.
+ */
+ public static ServletResponse unbindServletResponse() {
+ return (ServletResponse) ThreadContext.remove(SERVLET_RESPONSE_KEY);
+ }
+
+ /**
+ * Redirects the current request to a new URL based on the given parameters.
+ *
+ * @param request the servlet request.
+ * @param response the servlet response.
+ * @param url the URL to redirect the user to.
+ * @param queryParams a map of parameters that should be set as request parameters for the new request.
+ * @param contextRelative true if the URL is relative to the servlet context path, or false if the URL is absolute.
+ * @param http10Compatible whether to stay compatible with HTTP 1.0 clients.
+ * @throws java.io.IOException if thrown by response methods.
+ */
+ public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams, boolean contextRelative, boolean http10Compatible) throws IOException {
+ RedirectView view = new RedirectView(url, contextRelative, http10Compatible);
+ view.renderMergedOutputModel(queryParams, toHttp(request), toHttp(response));
+ }
+
+ /**
+ * Redirects the current request to a new URL based on the given parameters and default values
+ * for unspecified parameters.
+ *
+ * @param request the servlet request.
+ * @param response the servlet response.
+ * @param url the URL to redirect the user to.
+ * @throws java.io.IOException if thrown by response methods.
+ */
+ public static void issueRedirect(ServletRequest request, ServletResponse response, String url) throws IOException {
+ issueRedirect(request, response, url, null, true, true);
+ }
+
+ /**
+ * Redirects the current request to a new URL based on the given parameters and default values
+ * for unspecified parameters.
+ *
+ * @param request the servlet request.
+ * @param response the servlet response.
+ * @param url the URL to redirect the user to.
+ * @param queryParams a map of parameters that should be set as request parameters for the new request.
+ * @throws java.io.IOException if thrown by response methods.
+ */
+ public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams) throws IOException {
+ issueRedirect(request, response, url, queryParams, true, true);
+ }
+
+ /**
+ * Redirects the current request to a new URL based on the given parameters and default values
+ * for unspecified parameters.
+ *
+ * @param request the servlet request.
+ * @param response the servlet response.
+ * @param url the URL to redirect the user to.
+ * @param queryParams a map of parameters that should be set as request parameters for the new request.
+ * @param contextRelative true if the URL is relative to the servlet context path, or false if the URL is absolute.
+ * @throws java.io.IOException if thrown by response methods.
+ */
+ public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams, boolean contextRelative) throws IOException {
+ issueRedirect(request, response, url, queryParams, contextRelative, true);
+ }
+
+ /**
+ * <p>Checks to see if a request param is considered true using a loose matching strategy for
+ * general values that indicate that something is true or enabled, etc.</p>
+ *
+ * <p>Values that are considered "true" include (case-insensitive): true, t, 1, enabled, y, yes, on.</p>
+ *
+ * @param request the servlet request
+ * @param paramName @return true if the param value is considered true or false if it isn't.
+ * @return true if the given parameter is considered "true" - false otherwise.
+ */
+ public static boolean isTrue(ServletRequest request, String paramName) {
+ String value = getCleanParam(request, paramName);
+ return value != null &&
+ (value.equalsIgnoreCase("true") ||
+ value.equalsIgnoreCase("t") ||
+ value.equalsIgnoreCase("1") ||
+ value.equalsIgnoreCase("enabled") ||
+ value.equalsIgnoreCase("y") ||
+ value.equalsIgnoreCase("yes") ||
+ value.equalsIgnoreCase("on"));
+ }
+
+ /**
+ * Convenience method that returns a request parameter value, first running it through
+ * {@link StringUtils#clean(String)}.
+ *
+ * @param request the servlet request.
+ * @param paramName the parameter name.
+ * @return the clean param value, or null if the param does not exist or is empty.
+ */
+ public static String getCleanParam(ServletRequest request, String paramName) {
+ return StringUtils.clean(request.getParameter(paramName));
+ }
+
+ public static void saveRequest(ServletRequest request) {
+ Subject subject = SecurityUtils.getSubject();
+ Session session = subject.getSession();
+ HttpServletRequest httpRequest = toHttp(request);
+ SavedRequest savedRequest = new SavedRequest(httpRequest);
+ session.setAttribute(SAVED_REQUEST_KEY, savedRequest);
+ }
+
+ public static SavedRequest getAndClearSavedRequest(ServletRequest request) {
+ SavedRequest savedRequest = getSavedRequest(request);
+ if (savedRequest != null) {
+ Subject subject = SecurityUtils.getSubject();
+ Session session = subject.getSession();
+ session.removeAttribute(SAVED_REQUEST_KEY);
+ }
+ return savedRequest;
+ }
+
+ public static SavedRequest getSavedRequest(ServletRequest request) {
+ SavedRequest savedRequest = null;
+ Subject subject = SecurityUtils.getSubject();
+ Session session = subject.getSession(false);
+ if (session != null) {
+ savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST_KEY);
+ }
+ return savedRequest;
+ }
+
+
+}
diff --git a/web/src/org/jsecurity/web/attr/AbstractWebAttribute.java b/web/src/org/jsecurity/web/attr/AbstractWebAttribute.java
new file mode 100644
index 0000000..2d147e0
--- /dev/null
+++ b/web/src/org/jsecurity/web/attr/AbstractWebAttribute.java
@@ -0,0 +1,242 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.attr;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.JSecurityException;
+import org.jsecurity.util.ClassUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.beans.PropertyEditor;
+
+/**
+ * Convenient superclass for implementations of the {@link WebAttribute} interface. This class encapsulates
+ * converting values from a String form to Object form and vice versa through the use of a <tt>PropertyEditor</tt>
+ * configured using {@link #setEditorClass(Class)}. Subclasses are expected to implement the
+ * {@link #onStoreValue(Object, javax.servlet.ServletRequest, javax.servlet.ServletResponse)} and
+ * {@link #onRetrieveValue(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
+ * methods that perform the actual storing and retrieving of a String value. This class also contains convenience
+ * methods for retrieving the value of a request parameter to be stored.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public abstract class AbstractWebAttribute<T> implements WebAttribute<T> {
+
+ //TODO - complete JavaDoc
+
+ public static final String DEFAULT_NAME = "name";
+
+ private static final Log log = LogFactory.getLog(AbstractWebAttribute.class);
+
+ protected String name = DEFAULT_NAME;
+
+ protected boolean checkRequestParams = true;
+ protected boolean checkRequestParamsFirst = true;
+
+ protected boolean mutable = true;
+
+ /**
+ * Property editor class to use to convert attributes to and from strings.
+ */
+ private Class<? extends PropertyEditor> editorClass = null;
+
+ public AbstractWebAttribute() {
+ this(DEFAULT_NAME, true);
+ }
+
+ public AbstractWebAttribute(String name) {
+ this(name, true);
+ }
+
+ public AbstractWebAttribute(String name, boolean checkRequestParams) {
+ setName(name);
+ setCheckRequestParams(checkRequestParams);
+ }
+
+ public AbstractWebAttribute(String name, Class<? extends PropertyEditor> editorClass) {
+ this(name, true, editorClass);
+ }
+
+ public AbstractWebAttribute(String name, boolean checkRequestParams, Class<? extends PropertyEditor> editorClass) {
+ setName(name);
+ setCheckRequestParams(checkRequestParams);
+ setEditorClass(editorClass);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public boolean isCheckRequestParams() {
+ return checkRequestParams;
+ }
+
+ public void setCheckRequestParams(boolean checkRequestParams) {
+ this.checkRequestParams = checkRequestParams;
+ }
+
+ public boolean isCheckRequestParamsFirst() {
+ return checkRequestParamsFirst;
+ }
+
+ public void setCheckRequestParamsFirst(boolean checkRequestParamsFirst) {
+ this.checkRequestParamsFirst = checkRequestParamsFirst;
+ }
+
+ public Class<? extends PropertyEditor> getEditorClass() {
+ return editorClass;
+ }
+
+ /**
+ * If set, an instance of this class will be used to convert a the object value to a string value (and vice versa)
+ * when reading and populating values in
+ * {@link javax.servlet.http.HttpServletRequest HttpServletRequest}s, {@link javax.servlet.http.Cookie Cookie}s or
+ * {@link javax.servlet.http.HttpSession HttpSession}s.
+ *
+ * <p>If not set, the string itself will be used.
+ *
+ * @param editorClass {@link PropertyEditor PropertyEditor} implementation used to
+ * convert between string values and sessionId objects.
+ */
+ public void setEditorClass(Class<? extends PropertyEditor> editorClass) {
+ this.editorClass = editorClass;
+ }
+
+ /**
+ * Returns <tt>true</tt> if the value stored can be changed once it has been set, <tt>false</tt> if it cannot.
+ * <p>Default is <tt>true</tt>.
+ *
+ * @return <tt>true</tt> if the value stored can be changed once it has been set, <tt>false</tt> if it cannot.
+ */
+ public boolean isMutable() {
+ return mutable;
+ }
+
+ public void setMutable(boolean mutable) {
+ this.mutable = mutable;
+ }
+
+ @SuppressWarnings({"unchecked"})
+ protected T fromStringValue(String stringValue) {
+ Class clazz = getEditorClass();
+ if (clazz == null) {
+ try {
+ return (T) stringValue;
+ } catch (Exception e) {
+ String msg = "If the type is not String, you must specify the 'editorClass' property.";
+ throw new JSecurityException(msg, e);
+ }
+ } else {
+ PropertyEditor editor = (PropertyEditor) ClassUtils.newInstance(getEditorClass());
+ editor.setAsText(stringValue);
+ Object value = editor.getValue();
+ try {
+ return (T) value;
+ } catch (ClassCastException e) {
+ String msg = "Returned value from PropertyEditor does not match the specified type.";
+ throw new JSecurityException(msg, e);
+ }
+ }
+ }
+
+ protected String toStringValue(T value) {
+ Class clazz = getEditorClass();
+ if (clazz == null) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("No 'editorClass' property set - returning value.toString() as the string value for " +
+ "method argument.");
+ }
+ return value.toString();
+ } else {
+ PropertyEditor editor = (PropertyEditor) ClassUtils.newInstance(getEditorClass());
+ editor.setValue(value);
+ return editor.getAsText();
+ }
+ }
+
+ protected T getFromRequestParam(ServletRequest request) {
+ T value = null;
+
+ String paramName = getName();
+ String paramValue = request.getParameter(paramName);
+ if (paramValue != null) {
+ if (log.isTraceEnabled()) {
+ log.trace("Found string value [" + paramValue + "] from HttpServletRequest parameter [" + paramName + "]");
+ }
+ value = fromStringValue(paramValue);
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("No string value found in the HttpServletRequest under parameter named [" + paramName + "]");
+ }
+ }
+
+ return value;
+ }
+
+ public final T retrieveValue(ServletRequest request, ServletResponse response) {
+ T value = null;
+ if (isCheckRequestParams() && isCheckRequestParamsFirst()) {
+ value = getFromRequestParam(request);
+ }
+
+ if (value == null) {
+ value = onRetrieveValue(request, response);
+ }
+
+ if (value == null) {
+ if (isCheckRequestParams() && !isCheckRequestParamsFirst()) {
+ value = getFromRequestParam(request);
+ }
+ }
+
+ return value;
+ }
+
+ protected abstract T onRetrieveValue(ServletRequest request, ServletResponse response);
+
+ public void storeValue(T value, ServletRequest request, ServletResponse response) {
+ if (value == null && isMutable()) {
+ removeValue(request, response);
+ return;
+ }
+
+ if (!isMutable()) {
+ Object existing = onRetrieveValue(request, response);
+ if (existing != null) {
+ if (log.isDebugEnabled()) {
+ log.debug("Found existing value stored under name [" + getName() + "]. Ignoring new " +
+ "storage request - this store is immutable after the value has initially been set.");
+ }
+ }
+ return;
+ }
+
+ onStoreValue(value, request, response);
+ }
+
+ protected abstract void onStoreValue(T value, ServletRequest request, ServletResponse response);
+}
diff --git a/web/src/org/jsecurity/web/attr/CookieAttribute.java b/web/src/org/jsecurity/web/attr/CookieAttribute.java
new file mode 100644
index 0000000..5b887fa
--- /dev/null
+++ b/web/src/org/jsecurity/web/attr/CookieAttribute.java
@@ -0,0 +1,287 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.attr;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import static org.jsecurity.web.WebUtils.toHttp;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.beans.PropertyEditor;
+
+/**
+ * A <tt>CookieAttribute</tt> stores an object as a {@link Cookie} for access on later requests.
+ *
+ * @author Les Hazlewood
+ * @author Peter Ledbrook
+ * @since 0.2
+ */
+public class CookieAttribute<T> extends AbstractWebAttribute<T> {
+
+ //TODO - complete JavaDoc
+
+ /** Private internal log instance. */
+ private static final Log log = LogFactory.getLog(CookieAttribute.class);
+
+ /**
+ * The number of seconds in one year (= 60 * 60 * 24 * 365).
+ */
+ public static final int ONE_YEAR = 60 * 60 * 24 * 365;
+ /**
+ * This is the same value as Integer.MAX_VALUE, and while Tomcat does fine with cookie max age with this value,
+ * Jetty apparently has problems with it. If you're using Jetty, you might want to use the
+ * {@link #ONE_YEAR ONE_YEAR} constant or another value.
+ */
+ public static final int INDEFINITE = Integer.MAX_VALUE;
+
+ /**
+ * <code>null</code>, indicating the cookie should be set on the request context root.
+ */
+ public static final String DEFAULT_PATH = null;
+ /**
+ * <code>-1</code>, indicating the cookie should expire when the browser closes.
+ */
+ public static final int DEFAULT_MAX_AGE = -1;
+ /**
+ * Default value is <code>false</code>.
+ */
+ public static final boolean DEFAULT_SECURE = false;
+
+ private String path = DEFAULT_PATH;
+ private int maxAge = DEFAULT_MAX_AGE;
+ private boolean secure = DEFAULT_SECURE;
+
+ public CookieAttribute() {
+ }
+
+ /**
+ * Constructs a <tt>CookieAttribute</tt> using a {@link Cookie Cookie} with the specified {@link Cookie#getName() name}
+ * using the request context's path and with a {@link Cookie#setMaxAge(int) maxAge} of <tt>-1</tt>, indicating the
+ * Cookie will persist until browser shutdown.
+ *
+ * @param name the Cookie {@link Cookie#getName() name}
+ */
+ public CookieAttribute(String name) {
+ super(name);
+ }
+
+ /**
+ * Constructs a <tt>CookieAttribute</tt> using a {@link Cookie Cookie} with the specified
+ * {@link Cookie#getName() name} and {@link Cookie#getPath() path}.
+ *
+ * <p>A <tt>null</tt> <tt>path</tt> value means the request context's path will be used by default.
+ *
+ * <p>The Cookie's {@link Cookie#getMaxAge() maxAge} will be <tt>-1</tt>, indicating the Cookie will persist until
+ * browser shutdown.
+ *
+ * @param name the Cookie {@link Cookie#getName() name}
+ * @param path the Cookie {@link Cookie#setPath(String) path}.
+ */
+ public CookieAttribute(String name, String path) {
+ super(name);
+ setPath(path);
+ }
+
+ /**
+ * Constructs a <tt>CookieAttribute</tt> using a {@link Cookie Cookie} with the specified
+ * {@link Cookie#getName() name} and {@link Cookie#getMaxAge() maxAge}.
+ *
+ * <p>The Cookie's {@link javax.servlet.http.Cookie#getPath() path} will be the <tt>Request</tt>'s
+ * {@link javax.servlet.http.HttpServletRequest#getContextPath() context path}.
+ *
+ * @param name the Cookie {@link javax.servlet.http.Cookie#getName() name};
+ * @param maxAge the Cookie {@link Cookie#getMaxAge() maxAge}
+ */
+ public CookieAttribute(String name, int maxAge) {
+ super(name);
+ setMaxAge(maxAge);
+ }
+
+ /**
+ * Constructs a <tt>CookieAttribute</tt> using a {@link Cookie Cookie} with the specified
+ * {@link Cookie#getName() name}, {@link javax.servlet.http.Cookie#getPath() path}, and
+ * {@link Cookie#getMaxAge() maxAge}.
+ *
+ * @param name the Cookie {@link Cookie#getName() name}
+ * @param path the Cookie {@link Cookie#setPath(String) path}.
+ * @param maxAge the Cookie {@link Cookie#getMaxAge() maxAge}
+ */
+ public CookieAttribute(String name, String path, int maxAge) {
+ this(name, path);
+ setMaxAge(maxAge);
+ }
+
+ /**
+ * Constructs a <tt>CookieAttribute</tt> using a {@link Cookie Cookie} with the specified
+ * {@link Cookie#getName() name}, {@link javax.servlet.http.Cookie#getPath() path}, and
+ * {@link Cookie#getMaxAge() maxAge}, utilizing the specified <tt>PropertyEditor</tt> to perform value/string
+ * conversion on the object stored as a cookie.
+ *
+ * @param name the Cookie {@link Cookie#getName() name}
+ * @param path the Cookie {@link Cookie#setPath(String) path}.
+ * @param maxAge the Cookie {@link Cookie#getMaxAge() maxAge}
+ * @param editorClass the <tt>PropertyEditor</tt> to perform value/string conversion on the object stored as a
+ * Cookie.
+ */
+ public CookieAttribute(String name, String path, int maxAge, Class<? extends PropertyEditor> editorClass) {
+ super(name, editorClass);
+ setPath(path);
+ setMaxAge(maxAge);
+ }
+
+ /**
+ * Returns the Cookie's {@link Cookie#getPath() path} setting. If <tt>null</tt>, the <tt>request</tt>'s
+ * {@link javax.servlet.http.HttpServletRequest#getContextPath() context path} will be used.
+ *
+ * <p>The default is <code>null</code>.</p>
+ *
+ * @return the Cookie's path, or <tt>null</tt> if the request's context path should be used as the path when the
+ * cookie is created.
+ */
+ public String getPath() {
+ return path;
+ }
+
+ /**
+ * Sets the Cookie's {@link Cookie#getPath() path} setting. If the argument is <tt>null</tt>, the <tt>request</tt>'s
+ * {@link javax.servlet.http.HttpServletRequest#getContextPath() context path} will be used.
+ *
+ * <p>The default is <code>null</code>.</p>
+ *
+ * @param path the Cookie's path, or <tt>null</tt> if the request's context path should be used as the path when the
+ * cookie is created.
+ */
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ /**
+ * Returns the Cookie's {@link Cookie#setMaxAge(int) maxAge} setting. Please see that JavaDoc for the semantics on
+ * the repercussions of negative, zero, and positive values for the maxAge.
+ *
+ * <p>The default value is <code>-1</code>, meaning the cookie will expire when the browser is closed.</p>
+ *
+ * @return the Cookie's {@link Cookie#setMaxAge(int) maxAge}
+ */
+ public int getMaxAge() {
+ return maxAge;
+ }
+
+ /**
+ * Sets the Cookie's {@link Cookie#setMaxAge(int) maxAge} setting. Please see that JavaDoc for the semantics on
+ * the repercussions of negative, zero, and positive values for the maxAge.
+ *
+ * <p>The default value is <code>-1</code>, meaning the cookie will expire when the browser is closed.</p>
+ *
+ * @param maxAge the Cookie's {@link Cookie#setMaxAge(int) maxAge}
+ */
+ public void setMaxAge(int maxAge) {
+ this.maxAge = maxAge;
+ }
+
+ public boolean isSecure() {
+ return secure;
+ }
+
+ public void setSecure(boolean secure) {
+ this.secure = secure;
+ }
+
+ /**
+ * Returns the cookie with the given name from the request or <tt>null</tt> if no cookie
+ * with that name could be found.
+ *
+ * @param request the current executing http request.
+ * @param cookieName the name of the cookie to find and return.
+ * @return the cookie with the given name from the request or <tt>null</tt> if no cookie
+ * with that name could be found.
+ */
+ private static Cookie getCookie(HttpServletRequest request, String cookieName) {
+ Cookie cookies[] = request.getCookies();
+ if (cookies != null) {
+ for (Cookie cookie : cookies) {
+ if (cookie.getName().equals(cookieName)) {
+ return cookie;
+ }
+ }
+ }
+ return null;
+ }
+
+ public T onRetrieveValue(ServletRequest request, ServletResponse response) {
+ T value = null;
+
+ String stringValue;
+ Cookie cookie = getCookie(toHttp(request), getName());
+ if (cookie != null && cookie.getMaxAge() != 0 ) {
+ stringValue = cookie.getValue();
+ if (log.isInfoEnabled()) {
+ log.info("Found string value [" + stringValue + "] from HttpServletRequest Cookie [" + getName() + "]");
+ }
+ value = fromStringValue(stringValue);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("No value found in request Cookies under cookie name [" + getName() + "]");
+ }
+ }
+
+ return value;
+ }
+
+ public void onStoreValue(T value, ServletRequest servletRequest, ServletResponse servletResponse) {
+
+ HttpServletRequest request = toHttp(servletRequest);
+ HttpServletResponse response = toHttp(servletResponse);
+
+ String name = getName();
+ int maxAge = getMaxAge();
+ String path = getPath() != null ? getPath() : request.getContextPath();
+
+ String stringValue = toStringValue(value);
+ Cookie cookie = new Cookie(name, stringValue);
+ cookie.setMaxAge(maxAge);
+ cookie.setPath(path);
+ if (isSecure()) {
+ cookie.setSecure(true);
+ }
+
+ response.addCookie(cookie);
+ if (log.isTraceEnabled()) {
+ log.trace("Added Cookie [" + name + "] to path [" + path + "] with value [" +
+ stringValue + "] to the HttpServletResponse.");
+ }
+ }
+
+ public void removeValue(ServletRequest servletRequest, ServletResponse response) {
+ HttpServletRequest request = toHttp(servletRequest);
+ Cookie cookie = getCookie(request, getName());
+ if (cookie != null) {
+ cookie.setMaxAge(0);
+ //JSEC-94: Must set the path on the outgoing cookie (some browsers don't retain it from the
+ //retrieved cookie?)
+ cookie.setPath(getPath() == null ? request.getContextPath() : getPath());
+ cookie.setSecure(isSecure());
+ toHttp(response).addCookie(cookie);
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/attr/RequestParamAttribute.java b/web/src/org/jsecurity/web/attr/RequestParamAttribute.java
new file mode 100644
index 0000000..96c6cda
--- /dev/null
+++ b/web/src/org/jsecurity/web/attr/RequestParamAttribute.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.attr;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class RequestParamAttribute<T> extends AbstractWebAttribute<T> {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(RequestParamAttribute.class);
+
+ public RequestParamAttribute() {
+ setMutable(false);
+ setCheckRequestParams(false);
+ }
+
+ public RequestParamAttribute(String name) {
+ super(name);
+ setMutable(false);
+ setCheckRequestParams(false);
+ }
+
+ protected T onRetrieveValue(ServletRequest request, ServletResponse response) {
+ return getFromRequestParam(request);
+ }
+
+ protected void onStoreValue(T value, ServletRequest request, ServletResponse response) {
+ throw new UnsupportedOperationException("RequestParamStores are read-only.");
+ }
+
+ public void removeValue(ServletRequest request, ServletResponse response) {
+ //no op - can't alter request attributes
+ if (log.isWarnEnabled()) {
+ String msg = "Asked to remove WebAttribute value. A " + getClass().getName() + " implementation " +
+ "cannot remove values from the request params.";
+ log.warn(msg);
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/attr/WebAttribute.java b/web/src/org/jsecurity/web/attr/WebAttribute.java
new file mode 100644
index 0000000..47ef5b1
--- /dev/null
+++ b/web/src/org/jsecurity/web/attr/WebAttribute.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.attr;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * A <tt>WebAttribute</tt> is a storage mechanism for a single object accessible during a web request.
+ *
+ * <p>It is used to make objects associated with the transient request persistent beyond the request so that they can
+ * be retrieved at a later time.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public interface WebAttribute<T> {
+
+ //TODO - complete JavaDoc
+
+ T retrieveValue(ServletRequest request, ServletResponse response);
+
+ void storeValue(T value, ServletRequest request, ServletResponse response);
+
+ void removeValue(ServletRequest request, ServletResponse response);
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/attr/package-info.java
similarity index 77%
rename from src/org/jsecurity/mgt/package-info.java
rename to web/src/org/jsecurity/web/attr/package-info.java
index 8e597f2..e822720 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/attr/package-info.java
@@ -1,23 +1,23 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Supporting implementation of JSecurity's concept of a {@link org.jsecurity.web.attr.WebAttribute WebAttribute}, a
+ * component that can save and recall an object beyond transient requests.
+ */
+package org.jsecurity.web.attr;
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/config/IniWebConfiguration.java b/web/src/org/jsecurity/web/config/IniWebConfiguration.java
new file mode 100644
index 0000000..59979e8
--- /dev/null
+++ b/web/src/org/jsecurity/web/config/IniWebConfiguration.java
@@ -0,0 +1,432 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.config;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.config.ConfigurationException;
+import org.jsecurity.config.IniConfiguration;
+import org.jsecurity.config.ReflectionBuilder;
+import org.jsecurity.mgt.RealmSecurityManager;
+import org.jsecurity.util.AntPathMatcher;
+import org.jsecurity.util.PatternMatcher;
+import static org.jsecurity.util.StringUtils.split;
+import org.jsecurity.web.DefaultWebSecurityManager;
+import org.jsecurity.web.WebUtils;
+import org.jsecurity.web.filter.PathConfigProcessor;
+import org.jsecurity.web.filter.authc.AnonymousFilter;
+import org.jsecurity.web.filter.authc.BasicHttpAuthenticationFilter;
+import org.jsecurity.web.filter.authc.FormAuthenticationFilter;
+import org.jsecurity.web.filter.authc.UserFilter;
+import org.jsecurity.web.filter.authz.PermissionsAuthorizationFilter;
+import org.jsecurity.web.filter.authz.RolesAuthorizationFilter;
+import org.jsecurity.web.servlet.AdviceFilter;
+import org.jsecurity.web.servlet.ProxiedFilterChain;
+
+import javax.servlet.*;
+import java.util.*;
+
+/**
+ * A <code>WebConfiguration</code> that supports configuration via the
+ * <a href="http://en.wikipedia.org/wiki/INI_file">.ini format</a>.
+ *
+ * @author Les Hazlewood
+ * @since Jun 1, 2008 11:02:44 PM
+ */
+public class IniWebConfiguration extends IniConfiguration implements WebConfiguration {
+
+ //TODO - complete JavaDoc
+
+ private static final transient Log log = LogFactory.getLog(IniWebConfiguration.class);
+
+ public static final String FILTERS = "filters";
+ public static final String URLS = "urls";
+
+ protected FilterConfig filterConfig;
+
+ protected Map<String, List<Filter>> chains;
+
+ protected PatternMatcher pathMatcher = new AntPathMatcher();
+
+ public IniWebConfiguration() {
+ chains = new LinkedHashMap<String, List<Filter>>();
+ }
+
+ /**
+ * Returns the <code>PatternMatcher</code> used when determining if an incoming request's path
+ * matches a configured filter chain path in the <code>[urls]</code> section. Unless overridden, the
+ * default implementation is an {@link org.jsecurity.util.AntPathMatcher AntPathMatcher}.
+ *
+ * @return the <code>PatternMatcher</code> used when determining if an incoming request's path
+ * matches a configured filter chain path in the <code>[urls]</code> section.
+ * @since 0.9.0
+ */
+ public PatternMatcher getPathMatcher() {
+ return pathMatcher;
+ }
+
+ /**
+ * Sets the <code>PatternMatcher</code> used when determining if an incoming request's path
+ * matches a configured filter chain path in the <code>[urls]</code> section. Unless overridden, the
+ * default implementation is an {@link org.jsecurity.util.AntPathMatcher AntPathMatcher}.
+ *
+ * @param pathMatcher the <code>PatternMatcher</code> used when determining if an incoming request's path
+ * matches a configured filter chain path in the <code>[urls]</code> section.
+ * @since 0.9.0
+ */
+ public void setPathMatcher(PatternMatcher pathMatcher) {
+ this.pathMatcher = pathMatcher;
+ }
+
+ /**
+ * Returns the <code>FilterConfig</code> provided by the Servlet container at webapp startup.
+ *
+ * @return the <code>FilterConfig</code> provided by the Servlet container at webapp startup.
+ */
+ public FilterConfig getFilterConfig() {
+ return filterConfig;
+ }
+
+ /**
+ * Sets the <code>FilterConfig</code> provided by the Servlet container at webapp startup.
+ *
+ * @param filterConfig the <code>FilterConfig</code> provided by the Servlet container at webapp startup.
+ */
+ public void setFilterConfig(FilterConfig filterConfig) {
+ this.filterConfig = filterConfig;
+ }
+
+ //TODO - JAVADOC
+ public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
+ if (this.chains == null || this.chains.isEmpty()) {
+ return null;
+ }
+
+ String requestURI = getPathWithinApplication(request);
+
+ for (String path : this.chains.keySet()) {
+
+ // If the path does match, then pass on to the subclass implementation for specific checks:
+ if (pathMatches(path, requestURI)) {
+ if (log.isTraceEnabled()) {
+ log.trace("Matched path [" + path + "] for requestURI [" + requestURI + "]. " +
+ "Utilizing corresponding filter chain...");
+ }
+ return getChain(path, originalChain);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns the <code>FilterChain</code> to use for the specified application path, or <code>null</code> if the
+ * original <code>FilterChain</code> should be used.
+ * <p/>
+ * The default implementation simply calls <code>this.chains.get(chainUrl)</code> to acquire the configured
+ * <code>List<Filter></code> filter chain. If that configured chain is non-null and not empty, it is
+ * returned, otherwise <code>null</code> is returned to indicate that the <code>originalChain</code> should be
+ * used instead.
+ *
+ * @param chainUrl the configured filter chain url
+ * @param originalChain the original FilterChain given by the Servlet container.
+ * @return the <code>FilterChain</code> to use for the specified application path, or <code>null</code> if the
+ * original <code>FilterChain</code> should be used.
+ */
+ protected FilterChain getChain(String chainUrl, FilterChain originalChain) {
+ List<Filter> pathFilters = this.chains.get(chainUrl);
+ if (pathFilters != null && !pathFilters.isEmpty()) {
+ return createChain(pathFilters, originalChain);
+ }
+ return null;
+ }
+
+ /**
+ * Creates a new FilterChain based on the specified configured url filter chain and original chain.
+ * <p/>
+ * The input arguments are expected be be non-null and non-empty, since these conditions are accounted for in the
+ * {@link #getChain(String, javax.servlet.FilterChain) getChain(chainUrl,originalChain)} implementation that
+ * calls this method.
+ * <p/>
+ * The default implementation merely returns
+ * <code>new {@link org.jsecurity.web.servlet.ProxiedFilterChain FilterChainWrapper(filters, originalChain)}</code>,
+ * and can be overridden by subclasses for custom creation.
+ *
+ * @param filters the configured filter chain for the incoming request application path
+ * @param originalChain the original FilterChain given by the Servlet container.
+ * @return a new FilterChain based on the specified configured url filter chain and original chain.
+ */
+ protected FilterChain createChain(List<Filter> filters, FilterChain originalChain) {
+ return new ProxiedFilterChain(originalChain, filters);
+ }
+
+ /**
+ * Returns <code>true</code> if an incoming request's path (the <code>path</code> argument)
+ * matches a configured filter chain path in the <code>[urls]</code> section (the <code>pattern</code> argument),
+ * <code>false</code> otherwise.
+ * <p/>
+ * Simply delegates to
+ * <b><code>{@link #getPathMatcher() getPathMatcher()}.{@link org.jsecurity.util.PatternMatcher#matches(String, String) matches(pattern,path)}</code></b>,
+ * but can be overridden by subclasses for custom matching behavior.
+ *
+ * @param pattern the pattern to match against
+ * @param path the value to match with the specified <code>pattern</code>
+ * @return <code>true</code> if the request <code>path</code> matches the specified filter chain url <code>pattern</code>,
+ * <code>false</code> otherwise.
+ */
+ protected boolean pathMatches(String pattern, String path) {
+ PatternMatcher pathMatcher = getPathMatcher();
+ return pathMatcher.matches(pattern, path);
+ }
+
+ /**
+ * Merely returns
+ * <code>WebUtils.{@link WebUtils#getPathWithinApplication(javax.servlet.http.HttpServletRequest) getPathWithinApplication(request)}</code>
+ * and can be overridden by subclasses for custom request-to-application-path resolution behavior.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @return the request's path within the appliation.
+ */
+ protected String getPathWithinApplication(ServletRequest request) {
+ return WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
+ }
+
+ /**
+ * Creates a new, uninitialized <code>SecurityManager</code> instance that will be used to build up
+ * the JSecurity environment for the web application.
+ * <p/>
+ * The default implementation simply returns
+ * <code>new {@link org.jsecurity.web.DefaultWebSecurityManager DefaultWebSecurityManager()};</code>
+ *
+ * @return a new, uninitialized <code>SecurityManager</code> instance that will be used to build up
+ * the JSecurity environment for the web application.
+ */
+ protected RealmSecurityManager newSecurityManagerInstance() {
+ return new DefaultWebSecurityManager();
+ }
+
+ /**
+ * This implementation:
+ * <ol>
+ * <li>First builds the filter instances by processing the [filters] section</li>
+ * <li>Builds a collection filter chains according to the definitions in the [urls] section</li>
+ * <li>Initializes the filter instances in the order in which they were defined</li>
+ * </ol>
+ *
+ * @param sections the configured .ini sections where the key is the section name (without [] brackets)
+ * and the value is the key/value pairs inside that section.
+ */
+ protected void afterSecurityManagerSet(Map<String, Map<String, String>> sections) {
+ //filters section:
+ Map<String, String> section = sections.get(FILTERS);
+ Map<String, Filter> filters = getFilters(section);
+
+ //urls section:
+ section = sections.get(URLS);
+ this.chains = createChains(section, filters);
+
+ initFilters(this.chains);
+ }
+
+ protected void initFilters(Map<String, List<Filter>> chains) {
+ if (chains == null || chains.isEmpty()) {
+ return;
+ }
+
+ //add 'em to a set so we only initialize each one once:
+ Set<Filter> filters = new LinkedHashSet<Filter>();
+ for (List<Filter> pathFilters : chains.values()) {
+ filters.addAll(pathFilters);
+ }
+
+ //now initialize each one:
+ for (Filter filter : filters) {
+ initFilter(filter);
+ }
+ }
+
+ /**
+ * Initializes the filter by calling <code>filter.init( {@link #getFilterConfig() getFilterConfig()} );</code>.
+ *
+ * @param filter the filter to initialize with the <code>FilterConfig</code>.
+ */
+ protected void initFilter(Filter filter) {
+ try {
+ filter.init(getFilterConfig());
+ } catch (ServletException e) {
+ throw new ConfigurationException(e);
+ }
+ }
+
+ @SuppressWarnings({"unchecked"})
+ protected Map<String, Filter> getFilters(Map<String, String> section) {
+
+ Map<String, Filter> filters = createDefaultFilters();
+
+ if (section != null && !section.isEmpty()) {
+ ReflectionBuilder builder = new ReflectionBuilder(filters);
+ Map built = builder.buildObjects(section);
+ assertFilters(built);
+ filters = (Map<String, Filter>) built;
+ }
+
+ return filters;
+ }
+
+ protected void assertFilters(Map<String, ?> map) {
+ if (map == null || map.isEmpty()) {
+ return;
+ }
+ for (Map.Entry<String, ?> entry : map.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ assertFilter(key, value);
+ }
+ }
+
+ protected void assertFilter(String name, Object o) throws ConfigurationException {
+ if (!(o instanceof Filter)) {
+ String msg = "[" + FILTERS + "] section specified a filter named '" + name + "', which does not " +
+ "implement the " + Filter.class.getName() + " interface. Only Filter implementations may be " +
+ "defined.";
+ throw new ConfigurationException(msg);
+ }
+ }
+
+ protected Map<String, Filter> createDefaultFilters() {
+ Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
+
+ String name = "anon";
+ AdviceFilter filter = new AnonymousFilter();
+ filter.setName(name);
+ filters.put(name, filter);
+
+ name = "user";
+ filter = new UserFilter();
+ filter.setName(name);
+ filters.put(name, filter);
+
+ name = "authc";
+ filter = new FormAuthenticationFilter();
+ filter.setName(name);
+ filters.put(name, filter);
+
+ name = "authcBasic";
+ filter = new BasicHttpAuthenticationFilter();
+ filter.setName(name);
+ filters.put(name, filter);
+
+ name = "roles";
+ filter = new RolesAuthorizationFilter();
+ filter.setName(name);
+ filters.put(name, filter);
+
+ name = "perms";
+ filter = new PermissionsAuthorizationFilter();
+ filter.setName(name);
+ filters.put(name, filter);
+
+ return filters;
+ }
+
+ public Map<String, List<Filter>> createChains(Map<String, String> urls, Map<String, Filter> filters) {
+ if (urls == null || urls.isEmpty()) {
+ if (log.isDebugEnabled()) {
+ log.debug("No urls to process.");
+ }
+ return null;
+ }
+ if (filters == null || filters.isEmpty()) {
+ if (log.isDebugEnabled()) {
+ log.debug("No filters to process.");
+ }
+ return null;
+ }
+
+ if (log.isTraceEnabled()) {
+ log.trace("Before url processing.");
+ }
+
+ Map<String, List<Filter>> pathChains = new LinkedHashMap<String, List<Filter>>(urls.size());
+
+ for (Map.Entry<String, String> entry : urls.entrySet()) {
+ String path = entry.getKey();
+ String value = entry.getValue();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Processing path [" + path + "] with value [" + value + "]");
+ }
+
+ List<Filter> pathFilters = new ArrayList<Filter>();
+
+ //parse the value by tokenizing it to get the resulting filter-specific config entries
+ //
+ //e.g. for a value of
+ //
+ // "authc, roles[admin,user], perms[file:edit]"
+ //
+ // the resulting token array would equal
+ //
+ // { "authc", "roles[admin,user]", "perms[file:edit]" }
+ //
+ String[] filterTokens = split(value, ',', '[', ']', true, true);
+
+ //each token is specific to each filter.
+ //strip the name and extract any filter-specific config between brackets [ ]
+ for (String token : filterTokens) {
+ String[] nameAndConfig = token.split("\\[", 2);
+ String name = nameAndConfig[0];
+ String config = null;
+
+ if (nameAndConfig.length == 2) {
+ config = nameAndConfig[1];
+ //if there was an open bracket, there was a close bracket, so strip it too:
+ config = config.substring(0, config.length() - 1);
+ }
+
+ //now we have the filter name, path and (possibly null) path-specific config. Let's apply them:
+ Filter filter = filters.get(name);
+ if (filter == null) {
+ String msg = "Path [" + path + "] specified a filter named '" + name + "', but that " +
+ "filter has not been specified in the [" + FILTERS + "] section.";
+ throw new ConfigurationException(msg);
+ }
+ if (filter instanceof PathConfigProcessor) {
+ if (log.isDebugEnabled()) {
+ log.debug("Applying path [" + path + "] to filter [" + name + "] " +
+ "with config [" + config + "]");
+ }
+ ((PathConfigProcessor) filter).processPathConfig(path, config);
+ }
+
+ pathFilters.add(filter);
+ }
+
+ if (!pathFilters.isEmpty()) {
+ pathChains.put(path, pathFilters);
+ }
+ }
+
+ if (pathChains.isEmpty()) {
+ return null;
+ }
+
+ return pathChains;
+ }
+}
diff --git a/web/src/org/jsecurity/web/config/WebConfiguration.java b/web/src/org/jsecurity/web/config/WebConfiguration.java
new file mode 100644
index 0000000..b894c6b
--- /dev/null
+++ b/web/src/org/jsecurity/web/config/WebConfiguration.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.config;
+
+import org.jsecurity.config.Configuration;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * A <code>WebConfiguration</code> configures JSecurity components in a web-enabled application.
+ * <p/>
+ * In addition to enabling configuration of a <code>SecurityManager</code>, as required by the parent interface,
+ * it also allows configuration of arbitrary filter chains to be executed for any given request or URI/URL.
+ * <p/>
+ * This is incredibly powerful and <em>much</em> more flexible than normal servlet filter definitions or Servlet
+ * security: it allows arbitrary filter chains to be defined per URL in a much more concise and easy to read manner,
+ * and even allows filter chains to be dynamically resolved or construtected at runtime if the underlying implementation
+ * supports it.
+ *
+ * @author Les Hazlewood
+ * @since Jun 1, 2008 11:13:32 PM
+ */
+public interface WebConfiguration extends Configuration {
+
+ /**
+ * Returns the filter chain that should be executed for the given request, or <code>null</code> if the
+ * original chain should be used.
+ *
+ * <p>This method allows a Configuration implementation to define arbitrary security {@link Filter Filter}
+ * chains for any given request or URL pattern.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @param originalChain the original <code>FilterChain</code> intercepted by the JSecurityFilter.
+ * @return the filter chain that should be executed for the given request, or <code>null</code> if the
+ * original chain should be used.
+ */
+ FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain);
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/config/package-info.java
similarity index 77%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/config/package-info.java
index 8e597f2..32791ab 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/config/package-info.java
@@ -1,23 +1,22 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Web-specific implementation extensions to the <code>org.jsecurity.config</code> components.
+ */
+package org.jsecurity.web.config;
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/filter/AccessControlFilter.java b/web/src/org/jsecurity/web/filter/AccessControlFilter.java
new file mode 100644
index 0000000..225ce1d
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/AccessControlFilter.java
@@ -0,0 +1,213 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter;
+
+import org.jsecurity.SecurityUtils;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.web.WebUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+/**
+ * Superclass for any filter that controls access to a resource and may redirect the user to the login page
+ * if they are not authenticated. This superclass provides the method
+ * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
+ * which is used by many subclasses as the behavior when a user is unauthenticated.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AccessControlFilter extends PathMatchingFilter {
+
+ /**
+ * Simple default login URL equal to <code>/login.jsp</code>, which can be overridden by calling the
+ * {@link #setLoginUrl(String) setLoginUrl} method.
+ */
+ public static final String DEFAULT_LOGIN_URL = "/login.jsp";
+
+ /**
+ * Constant representing the HTTP 'GET' request method, equal to <code>GET</code>.
+ */
+ public static final String GET_METHOD = "GET";
+
+ /**
+ * Constant representing the HTTP 'POST' request method, equal to <code>POST</code>.
+ */
+ public static final String POST_METHOD = "POST";
+
+ /**
+ * The login url to used to authenticate a user, used when redirecting users if authentication is required.
+ */
+ private String loginUrl = DEFAULT_LOGIN_URL;
+
+ /**
+ * Returns the login URL used to authenticate a user.
+ * <p/>
+ * Most JSecurity filters use this url
+ * as the location to redirect a user when the filter requires authentication. Unless overridden, the
+ * {@link #DEFAULT_LOGIN_URL DEFAULT_LOGIN_URL} is assumed, which can be overridden via
+ * {@link #setLoginUrl(String) setLoginUrl}.
+ *
+ * @return the login URL used to authenticate a user, used when redirecting users if authentication is required.
+ */
+ protected String getLoginUrl() {
+ return loginUrl;
+ }
+
+ /**
+ * Sets the login URL used to authenticate a user.
+ * <p/>
+ * Most JSecurity filters use this url as the location to redirect a user when the filter requires
+ * authentication. Unless overridden, the {@link #DEFAULT_LOGIN_URL DEFAULT_LOGIN_URL} is assumed.
+ *
+ * @param loginUrl the login URL used to authenticate a user, used when redirecting users if authentication is required.
+ */
+ public void setLoginUrl(String loginUrl) {
+ this.loginUrl = loginUrl;
+ }
+
+ /**
+ * Convenience method that acquires the Subject associated with the request.
+ * <p/>
+ * The default implementation simply returns
+ * {@link org.jsecurity.SecurityUtils#getSubject() SecurityUtils.getSubject()}.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @return the Subject associated with the request.
+ */
+ protected Subject getSubject(ServletRequest request, ServletResponse response) {
+ return SecurityUtils.getSubject();
+ }
+
+ /**
+ * Returns <code>true</code> if the request is allowed to proceed through the filter normally, or <code>false</code>
+ * if the request should be handled by the
+ * {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse) onAccessDenied(request,response)}
+ * method instead.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @param mappedValue the filter-specific config value mapped to this filter in the URL rules mappings.
+ * @return <code>true</code> if the request should proceed through the filter normally, <code>false</code> if the
+ * request should be processed by this filter's
+ * {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method instead.
+ * @throws Exception if an error occurs during processing.
+ */
+ protected abstract boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception;
+
+ /**
+ * Processes requests where the subject was denied access as determined by the
+ * {@link #isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) isAccessAllowed}
+ * method.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @return <code>true</code> if the request should continue to be processed; false if the subclass will
+ * handle/render the response directly.
+ * @throws Exception if there is an error processing the request.
+ */
+ protected abstract boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception;
+
+ /**
+ * Returns <code>true</code> if
+ * {@link #isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) isAccessAllowed},
+ * otherwise returns the result of
+ * {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse) onAccessDenied}.
+ *
+ * @return <code>true</code> if
+ * {@link #isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) isAccessAllowed},
+ * otherwise returns the result of
+ * {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse) onAccessDenied}.
+ * @throws Exception if an error occurs.
+ */
+ public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
+ //mapped value is ignored - not needed for most (if not all) authc Filters.
+ return isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response);
+ }
+
+ /**
+ * Returns <code>true</code> if the incoming request is a login request, <code>false</code> otherwise.
+ * <p/>
+ * The default implementation merely returns <code>true</code> if the incoming request matches the configured
+ * {@link #getLoginUrl() loginUrl} by calling
+ * <code>{@link #pathsMatch(String, String) pathsMatch(loginUrl, request)}</code>.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @return <code>true</code> if the incoming request is a login request, <code>false</code> otherwise.
+ */
+ protected boolean isLoginRequest(ServletRequest request, ServletResponse response) {
+ return pathsMatch(getLoginUrl(), request);
+ }
+
+ /**
+ * Convenience method for subclasses to use when a login redirect is required.
+ * <p/>
+ * This implementation simply calls {@link #saveRequest(javax.servlet.ServletRequest) saveRequest(request)}
+ * and then {@link #redirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse) redirectToLogin(request,response)}.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @throws IOException if an error occurs.
+ */
+ protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
+ saveRequest(request);
+ redirectToLogin(request, response);
+ }
+
+ /**
+ * Convenience method merely delegates to
+ * {@link WebUtils#saveRequest(javax.servlet.ServletRequest) WebUtils.saveRequest(request)} to save the request
+ * state for reuse later. This is mostly used to retain user request state when a redirect is issued to
+ * return the user to their originally requested url/resource.
+ * <p/>
+ * If you need to save and then immediately redirect the user to login, consider using
+ * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
+ * saveRequestAndRedirectToLogin(request,response)} directly.
+ *
+ * @param request the incoming ServletRequest to save for re-use later (for example, after a redirect).
+ */
+ protected void saveRequest(ServletRequest request) {
+ WebUtils.saveRequest(request);
+ }
+
+ /**
+ * Convenience method for subclasses that merely acquires the {@link #getLoginUrl() getLoginUrl} and redirects
+ * the request to that url.
+ * <p/>
+ * <b>N.B.</b> If you want to issue a redirect with the intention of allowing the user to then return to their
+ * originally requested URL, don't use this method directly. Instead you should call
+ * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
+ * saveRequestAndRedirectToLogin(request,response)}, which will save the current request state so that it can
+ * be reconstructed and re-used after a successful login.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @throws IOException if an error occurs.
+ */
+ protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
+ String loginUrl = getLoginUrl();
+ WebUtils.issueRedirect(request, response, loginUrl);
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/filter/PathConfigProcessor.java
similarity index 72%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/filter/PathConfigProcessor.java
index 8e597f2..1eb6cf0 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/filter/PathConfigProcessor.java
@@ -16,8 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.web.filter;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * A PathConfigProcessor processes configuration entries on a per path (per url) basis.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public interface PathConfigProcessor {
+
+ //TODO - complete JavaDoc
+
+ void processPathConfig(String path, String config);
+}
diff --git a/web/src/org/jsecurity/web/filter/PathMatchingFilter.java b/web/src/org/jsecurity/web/filter/PathMatchingFilter.java
new file mode 100644
index 0000000..ab0173c
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/PathMatchingFilter.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.util.AntPathMatcher;
+import org.jsecurity.util.PatternMatcher;
+import static org.jsecurity.util.StringUtils.split;
+import org.jsecurity.web.WebUtils;
+import org.jsecurity.web.servlet.AdviceFilter;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * <p>Base class for Filters that will process only specified paths and allow all others to pass through.</p>
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public abstract class PathMatchingFilter extends AdviceFilter implements PathConfigProcessor {
+
+ /**
+ * Log available to this class only
+ */
+ private static final Log log = LogFactory.getLog(PathMatchingFilter.class);
+
+ /**
+ * PatternMatcher used in determining which paths to react to for a given request.
+ */
+ protected PatternMatcher pathMatcher = new AntPathMatcher();
+
+ /**
+ * A collection of path-to-config entries where the key is a path which this filter should process and
+ * the value is the (possibly null) configuration element specific to this Filter for that specific path.
+ *
+ * <p>To put it another way, the keys are the paths (urls) that this Filter will process.
+ * <p>The values are filter-specific data that this Filter should use when processing the corresponding
+ * key (path). The values can be null if no Filter-specific config was specified for that url.
+ */
+ protected Map<String, Object> appliedPaths = new LinkedHashMap<String, Object>();
+
+ /**
+ * Splits any comma-delmited values that might be found in the <code>config</code> argument and sets the resulting
+ * <code>String[]</code> array on the <code>appliedPaths</code> internal Map.
+ * <p/>
+ * That is:
+ * <pre><code>
+ * String[] values = null;
+ * if (config != null) {
+ * values = split(config);
+ * }
+ *
+ * this.{@link #appliedPaths appliedPaths}.put(path, values);
+ * </code></pre>
+ *
+ * @param path the application context path to match for executing this filter.
+ * @param config the specified for <em>this particular filter only</em> for the given <code>path</code>
+ */
+ public void processPathConfig(String path, String config) {
+ String[] values = null;
+ if (config != null) {
+ values = split(config);
+ }
+
+ this.appliedPaths.put(path, values);
+ }
+
+ /**
+ * Returns the context path within the application based on the specified <code>request</code>.
+ * <p/>
+ * This implementation merely delegates to
+ * {@link WebUtils#getPathWithinApplication(javax.servlet.http.HttpServletRequest) WebUtils.getPathWithinApplication(request)},
+ * but can be overridden by subclasses for custom logic.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @return the context path within the application.
+ */
+ protected String getPathWithinApplication(ServletRequest request) {
+ return WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
+ }
+
+ /**
+ * Returns <code>true</code> if the incoming <code>request</code> matches the specified <code>path</code> pattern,
+ * <code>false</code> otherwise.
+ * <p/>
+ * The default implementation acquires the <code>request</code>'s path within the application and determines
+ * if that matches:
+ * <p/>
+ * <code>String requestURI = {@link #getPathWithinApplication(javax.servlet.ServletRequest) getPathWithinApplication(request)};<br/>
+ * return {@link #pathsMatch(String, String) pathsMatch(path,requestURI)}</code>
+ *
+ * @param path the configured url pattern to check the incoming request against.
+ * @param request the incoming ServletRequest
+ * @return <code>true</code> if the incoming <code>request</code> matches the specified <code>path</code> pattern,
+ * <code>false</code> otherwise.
+ */
+ protected boolean pathsMatch(String path, ServletRequest request) {
+ String requestURI = getPathWithinApplication(request);
+ if (log.isTraceEnabled()) {
+ log.trace("Attempting to match pattern [" + path + "] with current requestURI [" + requestURI + "]...");
+ }
+ return pathsMatch(path, requestURI);
+ }
+
+ /**
+ * Returns <code>true</code> if the <code>path</code> matches the specified <code>pattern</code> string,
+ * <code>false</code> otherwise.
+ * <p/>
+ * Simply delegates to
+ * <b><code>this.pathMatcher.{@link PatternMatcher#matches(String, String) matches(pattern,path)}</code></b>,
+ * but can be overridden by subclasses for custom matching behavior.
+ *
+ * @param pattern the pattern to match against
+ * @param path the value to match with the specified <code>pattern</code>
+ * @return <code>true</code> if the <code>path</code> matches the specified <code>pattern</code> string,
+ * <code>false</code> otherwise.
+ */
+ protected boolean pathsMatch(String pattern, String path) {
+ return pathMatcher.matches(pattern, path);
+ }
+
+ /**
+ * Implementation that handles path-matching behavior before a request is evaluated. If the path matches,
+ * the request will be allowed through via the result from
+ * {@link #onPreHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) onPreHandle}. If the
+ * path does not match, this filter will allow passthrough immediately.
+ *
+ * <p>In order to retain path-matching functionality, subclasses should not override this method if at all
+ * possible, and instead override
+ * {@link #onPreHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Object) onPreHandle} instead.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @return true - allow the request chain to continue in this default implementation
+ * @throws Exception
+ */
+ public boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
+
+ if (this.appliedPaths == null || this.appliedPaths.isEmpty()) {
+ if (log.isTraceEnabled()) {
+ log.trace("appliedPaths property is null or empty. This Filter will passthrough immediately.");
+ }
+ return true;
+ }
+
+ for (String path : this.appliedPaths.keySet()) {
+ // If the path does match, then pass on to the subclass implementation for specific checks
+ //(first match 'wins'):
+ if (pathsMatch(path, request)) {
+ if (log.isTraceEnabled()) {
+ log.trace("Current requestURI matches pattern [" + path + "]. Performing onPreHandle check...");
+ }
+ Object config = this.appliedPaths.get(path);
+ return onPreHandle(request, response, config);
+ }
+ }
+
+ //no path matched, allow the request to go through:
+ return true;
+ }
+
+ /**
+ * Default implementation always returns <code>true</code>. Should be overridden by subclasses for custom
+ * logic.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @param mappedValue the filter-specific config value mapped to this filter in the URL rules mappings.
+ * @return <code>true</code> if the request should be able to continue, <code>false</code> if the filter will
+ * handle the response directly.
+ * @throws Exception if an error occurs
+ */
+ protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
+ return true;
+ }
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/AnonymousFilter.java b/web/src/org/jsecurity/web/filter/authc/AnonymousFilter.java
new file mode 100644
index 0000000..56c2913
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/AnonymousFilter.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import org.jsecurity.web.filter.PathMatchingFilter;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * Filter that allows access to a path immeidately without performing security checks of any kind.
+ * <p/>
+ * This filter is useful primarily in exclusionary policies, where you have defined a url pattern
+ * to require a certain security level, but maybe only subset of urls in that pattern should allow any access.
+ * <p/>
+ * For example, if you had a user-only section of a website, you might want to require that access to
+ * any url in that section must be from an authenticated user.
+ * <p/>
+ * Here is how that would look in the JSecurityFilter configuration:
+ * <p/>
+ * <code>[urls]<br/>
+ * /user/** = authc</code>
+ * <p/>
+ * But if you wanted <code>/user/signup/**</code> to be available to anyone, you have to exclude that path since
+ * it is a subset of the first. This is where the AnonymousFilter ('anon') is useful:
+ * <p/>
+ * <code>[urls]<br/>
+ * /user/signup/** = anon<br/>
+ * /user/** = authc</code>>
+ * <p/>
+ * Since the url pattern definitions follow a 'first match wins' paradigm, the <code>anon</code> filter will
+ * match the <code>/user/signup/**</code> paths and the <code>/user/**</code> path chain will not be evaluated.
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class AnonymousFilter extends PathMatchingFilter {
+
+ /**
+ * Always returns <code>true</code> allowing unchecked access to the underlying path or resource.
+ *
+ * @return <code>true</code> always, allowing unchecked access to the underlying path or resource.
+ */
+ @Override
+ public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
+ // Always return true since we allow access to anyone
+ return true;
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/AuthenticatingFilter.java b/web/src/org/jsecurity/web/filter/authc/AuthenticatingFilter.java
new file mode 100644
index 0000000..c247c2c
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/AuthenticatingFilter.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.UsernamePasswordToken;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.web.WebUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.net.InetAddress;
+
+/**
+ * An <code>AuthenticationFilter</code> that is capable of automatically performing an authentication attempt
+ * based on the incoming request.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AuthenticatingFilter extends AuthenticationFilter {
+
+ //TODO - complete JavaDoc
+
+ protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
+ AuthenticationToken token = createToken(request, response);
+ if (token == null) {
+ String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
+ "must be created in order to execute a login attempt.";
+ throw new IllegalStateException(msg);
+ }
+ try {
+ Subject subject = getSubject(request, response);
+ subject.login(token);
+ return onLoginSuccess(token, subject, request, response);
+ } catch (AuthenticationException e) {
+ return onLoginFailure(token, e, request, response);
+ }
+ }
+
+ protected abstract AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception;
+
+ protected AuthenticationToken createToken(String username, String password,
+ ServletRequest request, ServletResponse response) {
+ boolean rememberMe = isRememberMe(request);
+ InetAddress inet = getInetAddress(request);
+ return createToken(username, password, rememberMe, inet);
+ }
+
+ protected AuthenticationToken createToken(String username, String password,
+ boolean rememberMe, InetAddress inet) {
+ return new UsernamePasswordToken(username, password, rememberMe, inet);
+ }
+
+ protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
+ ServletRequest request, ServletResponse response) throws Exception {
+ return true;
+ }
+
+ protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
+ ServletRequest request, ServletResponse response) {
+ return false;
+ }
+
+ /**
+ * Returns the InetAddress associated with the current subject. This method is primarily provided for use
+ * during construction of an <code>AuthenticationToken</code>.
+ * <p/>
+ * The default implementation merely returns
+ * {@link WebUtils#getInetAddress(javax.servlet.ServletRequest) WebUtils.getInetAddress(request)}.
+ *
+ * @param request the incoming ServletRequest
+ * @return the <code>InetAddress</code> to associate with the login attempt.
+ */
+ protected InetAddress getInetAddress(ServletRequest request) {
+ return WebUtils.getInetAddress(request);
+ }
+
+ /**
+ * Returns <code>true</code> if "rememberMe" should be enabled for the login attempt associated with the
+ * current <code>request</code>, <code>false</code> otherwise.
+ * <p/>
+ * This implementation always returns <code>false</code> and is provided as a template hook to subclasses that
+ * support <code>rememberMe</code> logins and wish to determine <code>rememberMe</code> in a custom mannner
+ * based on the current <code>request</code>.
+ *
+ * @param request the incoming ServletRequest
+ * @return <code>true</code> if "rememberMe" should be enabled for the login attempt associated with the
+ * current <code>request</code>, <code>false</code> otherwise.
+ */
+ protected boolean isRememberMe(ServletRequest request) {
+ return false;
+ }
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/AuthenticationFilter.java b/web/src/org/jsecurity/web/filter/authc/AuthenticationFilter.java
new file mode 100644
index 0000000..f61b08d
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/AuthenticationFilter.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import org.jsecurity.subject.Subject;
+import org.jsecurity.web.SavedRequest;
+import org.jsecurity.web.WebUtils;
+import org.jsecurity.web.filter.AccessControlFilter;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * <p>Base class for all Filters that require the current user to be authenticated. This class encapsulates the
+ * logic of checking whether a user is already authenticated in the system. If the user is not authenticated, we use
+ * the template method pattern to delegate the processing of an unauthenticated request to sub classes.</p>
+ *
+ * @author Allan Ditzel
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AuthenticationFilter extends AccessControlFilter {
+
+ //TODO - complete JavaDoc
+
+ public static final String DEFAULT_SUCCESS_URL = "/index.jsp";
+
+ private String successUrl = DEFAULT_SUCCESS_URL;
+
+ protected String getSuccessUrl() {
+ return successUrl;
+ }
+
+ /**
+ * Sets the success URL that is the default location a user is sent to after logging in when
+ * {@link #issueSuccessRedirect(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
+ * is called by subclasses of this filter.
+ *
+ * @param successUrl the success URL to redirect the user to after a successful login.
+ */
+ public void setSuccessUrl(String successUrl) {
+ this.successUrl = successUrl;
+ }
+
+
+ /**
+ * Determines whether the current subject is authenticated.
+ * <p/>
+ * The default implementation {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) acquires}
+ * the currently executing Subject and then returns
+ * {@link org.jsecurity.subject.Subject#isAuthenticated() subject.isAuthenticated()};
+ *
+ * @return true if the subject is authenticated; false if the subject is unauthenticated
+ */
+ protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
+ Subject subject = getSubject(request, response);
+ return subject.isAuthenticated();
+ }
+
+ protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
+
+ String successUrl = null;
+ boolean contextRelative = true;
+ SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
+ if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(GET_METHOD)) {
+ successUrl = savedRequest.getRequestUrl();
+ contextRelative = false;
+ }
+
+ if (successUrl == null) {
+ successUrl = getSuccessUrl();
+ }
+
+ if (successUrl == null) {
+ throw new IllegalStateException("Success URL not available via saved request or by calling " +
+ "getSuccessUrl(). One of these must be non-null for issueSuccessRedirect() to work.");
+ }
+
+ WebUtils.issueRedirect(request, response, successUrl, null, contextRelative);
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/BasicHttpAuthenticationFilter.java b/web/src/org/jsecurity/web/filter/authc/BasicHttpAuthenticationFilter.java
new file mode 100644
index 0000000..629cb49
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/BasicHttpAuthenticationFilter.java
@@ -0,0 +1,357 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.codec.Base64;
+import org.jsecurity.web.WebUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Requires the requesting user to be {@link org.jsecurity.subject.Subject#isAuthenticated() authenticated} for the
+ * request to continue, and if they're not, forces the user to login via the HTTP Basic protocol-specific challenge.
+ * Upon successful login, they're allowed to continue on to the requested resource/url.
+ *
+ * <p>This implementation is a 'clean room' Java implementation of Basic HTTP Authentication specification per
+ * <a href="ftp://ftp.isi.edu/in-notes/rfc2617.txt">RFC 2617</a>.</p>
+ *
+ * <p>Basic authentication functions as follows:</p>
+ *
+ * <ol>
+ * <li>A request comes in for a resource that requires authentication.</li>
+ * <li>The server replies with a 401 response status, sets the <code>WWW-Authenticate</code> header, and the contents of a
+ * page informing the user that the incoming resource requires authentication.</li>
+ * <li>Upon receiving this <code>WWW-Authenticate</code> challenge from the server, the client then takes a
+ * username and a password and puts them in the following format:
+ * <p><code>username:password</code></p></li>
+ * <li>This token is then base 64 encoded.</li>
+ * <li>The client then sends another request for the same resource with the following header:<p/>
+ * <p><code>Authorization: Basic <em>Base64_encoded_username_and_password</em></code></p></li>
+ * </ol>
+ *
+ * <p>The {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method will
+ * only be called if the subject making the request is not
+ * {@link org.jsecurity.subject.Subject#isAuthenticated() authenticated} </p>
+ *
+ * @author Allan Ditzel
+ * @author Les Hazlewood
+ * @see <a href="ftp://ftp.isi.edu/in-notes/rfc2617.txt">RFC 2617</a>
+ * @see <a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic Access Authentication</a>
+ * @since 0.9
+ */
+public class BasicHttpAuthenticationFilter extends AuthenticatingFilter {
+
+ /**
+ * This class's private logger.
+ */
+ private static final Log log = LogFactory.getLog(BasicHttpAuthenticationFilter.class);
+
+ /**
+ * HTTP Authorization header, equal to <code>Authorization</code>
+ */
+ protected static final String AUTHORIZATION_HEADER = "Authorization";
+
+ /**
+ * HTTP Authentication header, equal to <code>WWW-Authenticate</code>
+ */
+ protected static final String AUTHENTICATE_HEADER = "WWW-Authenticate";
+
+ /**
+ * The name that is displayed during the challenge process of authentication, defauls to <code>application</code>
+ * and can be overridden by the {@link #setApplicationName(String) setApplicationName} method.
+ */
+ private String applicationName = "application";
+
+ /**
+ * The authcScheme to look for in the <code>Authorization</code> header, defaults to <code>BASIC</code>
+ */
+ private String authcScheme = HttpServletRequest.BASIC_AUTH;
+
+ /**
+ * The authzScheme value to look for in the <code>Authorization</code> header, defaults to <code>BASIC</code>
+ */
+ private String authzScheme = HttpServletRequest.BASIC_AUTH;
+
+ /**
+ * Returns the name to use in the ServletResponse's <b><code>WWW-Authenticate</code></b> header.
+ * <p/>
+ * Per RFC 2617, this name name is displayed to the end user when they are asked to authenticate. Unless overridden
+ * by the {@link #setApplicationName(String) setApplicationName(String)} method, the default value is 'application'.
+ * <p/>
+ * Please see {@link #setApplicationName(String) setApplicationName(String)} for an example of how this functions.
+ *
+ * @return the name to use in the ServletResponse's 'WWW-Authenticate' header.
+ */
+ public String getApplicationName() {
+ return applicationName;
+ }
+
+ /**
+ * Sets the name to use in the ServletResponse's <b><code>WWW-Authenticate</code></b> header.
+ * <p/>
+ * Per RFC 2617, this name name is displayed to the end user when they are asked to authenticate. Unless overridden
+ * by this method, the default value is "application"
+ * <p/>
+ * For example, setting this property to the value <b><code>Awesome Webapp</code></b> will result in the
+ * following header:
+ * <p/>
+ * <code>WWW-Authenticate: Basic realm="<b>Awesome Webapp</b>"</code>
+ * <p/>
+ * Side note: As you can see from the header text, the HTTP Basic specification calls
+ * this the authentication 'realm', but we call this the 'applicationName' instead to avoid confusion with
+ * JSecurity's Realm constructs.
+ *
+ * @param applicationName the name to use in the ServletResponse's 'WWW-Authenticate' header.
+ */
+ public void setApplicationName(String applicationName) {
+ this.applicationName = applicationName;
+ }
+
+ /**
+ * Returns the HTTP <b><code>Authorization</code></b> header value that this filter will respond to as indicating
+ * a login request.
+ * <p/>
+ * Unless overridden by the {@link #setAuthzScheme(String) setAuthzScheme(String)} method, the
+ * default value is <code>BASIC</code>.
+ *
+ * @return the Http 'Authorization' header value that this filter will respond to as indicating a login request
+ */
+ public String getAuthzScheme() {
+ return authzScheme;
+ }
+
+ /**
+ * Sets the HTTP <b><code>Authorization</code></b> header value that this filter will respond to as indicating a
+ * login request.
+ * <p/>
+ * Unless overridden by this method, the default value is <code>BASIC</code>
+ *
+ * @param authzScheme the HTTP <code>Authorization</code> header value that this filter will respond to as
+ * indicating a login request.
+ */
+ public void setAuthzScheme(String authzScheme) {
+ this.authzScheme = authzScheme;
+ }
+
+ /**
+ * Returns the HTTP <b><code>WWW-Authenticate</code></b> header scheme that this filter will use when sending
+ * the HTTP Basic challenge response. The default value is <code>BASIC</code>.
+ *
+ * @return the HTTP <code>WWW-Authenticate</code> header scheme that this filter will use when sending the HTTP
+ * Basic challenge response.
+ * @see #sendChallenge
+ */
+ public String getAuthcScheme() {
+ return authcScheme;
+ }
+
+ /**
+ * Sets the HTTP <b><code>WWW-Authenticate</code></b> header scheme that this filter will use when sending the
+ * HTTP Basic challenge response. The default value is <code>BASIC</code>.
+ *
+ * @param authcScheme the HTTP <code>WWW-Authenticate</code> header scheme that this filter will use when
+ * sending the Http Basic challenge response.
+ * @see #sendChallenge
+ */
+ public void setAuthcScheme(String authcScheme) {
+ this.authcScheme = authcScheme;
+ }
+
+ /**
+ * Processes unauthenticated requests. It handles the two-stage request/challenge authentication protocol.
+ *
+ * @param request incoming ServletRequest
+ * @param response outgoing ServletResponse
+ * @return true if the request should be processed; false if the request should not continue to be processed
+ */
+ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
+ boolean loggedIn = false; //false by default or we wouldn't be in this method
+ if (isLoginAttempt(request, response)) {
+ loggedIn = executeLogin(request, response);
+ }
+ if (!loggedIn) {
+ sendChallenge(request, response);
+ }
+ return loggedIn;
+ }
+
+ /**
+ * Determines whether the incoming request is an attempt to log in.
+ * <p/>
+ * The default implementation obtains the value of the request's
+ * {@link #AUTHORIZATION_HEADER AUTHORIZATION_HEADER}, and if it is not <code>null</code>, delegates
+ * to {@link #isLoginAttempt(String) isLoginAttempt(authzHeaderValue)}. If the header is <code>null</code>,
+ * <code>false</code> is returned.
+ *
+ * @param request incoming ServletRequest
+ * @param response outgoing ServletResponse
+ * @return true if the incoming request is an attempt to log in based, false otherwise
+ */
+ protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
+ String authzHeader = getAuthzHeader(request);
+ return authzHeader != null && isLoginAttempt(authzHeader);
+ }
+
+ /**
+ * Returns the {@link #AUTHORIZATION_HEADER AUTHORIZATION_HEADER} from the specified ServletRequest.
+ * <p/>
+ * This implementation merely casts the request to an <code>HttpServletRequest</code> and returns the header:
+ * <p/>
+ * <code>HttpServletRequest httpRequest = {@link WebUtils#toHttp(javax.servlet.ServletRequest) toHttp(reaquest)};<br/>
+ * return httpRequest.getHeader({@link #AUTHORIZATION_HEADER AUTHORIZATION_HEADER});</code>
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @return the <code>Authorization</code> header's value.
+ */
+ protected String getAuthzHeader(ServletRequest request) {
+ HttpServletRequest httpRequest = WebUtils.toHttp(request);
+ return httpRequest.getHeader(AUTHORIZATION_HEADER);
+ }
+
+ /**
+ * Default implementation that returns <code>true</code> if the specified <code>authzHeader</code>
+ * starts with the same (case-insensitive) characters specified by the
+ * {@link #getAuthzScheme() authzScheme}, <code>false</code> otherwise.
+ * <p/>
+ * That is:
+ * <p/>
+ * <code>String authzScheme = getAuthzScheme().toLowerCase();<br/>
+ * return authzHeader.toLowerCase().startsWith(authzScheme);</code>
+ *
+ * @param authzHeader the 'Authorization' header value (guaranteed to be non-null if the
+ * {@link #isLoginAttempt(javax.servlet.ServletRequest, javax.servlet.ServletResponse)} method is not overriden).
+ * @return <code>true</code> if the authzHeader value matches that configured as defined by
+ * the {@link #getAuthzScheme() authzScheme}.
+ */
+ protected boolean isLoginAttempt(String authzHeader) {
+ String authzScheme = getAuthzScheme().toLowerCase();
+ return authzHeader.toLowerCase().startsWith(authzScheme);
+ }
+
+ /**
+ * Builds the challenge for authorization by setting a HTTP <code>401</code> (Unauthorized) status as well as the
+ * response's {@link #AUTHENTICATE_HEADER AUTHENTICATE_HEADER}.
+ * <p/>
+ * The header value constructed is equal to:
+ * <p/>
+ * <code>{@link #getAuthcScheme() getAuthcScheme()} + " realm=\"" + {@link #getApplicationName() getApplicationName()} + "\"";</code>
+ *
+ * @param request incoming ServletRequest, ignored by this implementation
+ * @param response outgoing ServletResponse
+ * @return false - this sends the challenge to be sent back
+ */
+ protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
+ if (log.isDebugEnabled()) {
+ log.debug("Authentication required: sending 401 Authentication challenge response.");
+ }
+ HttpServletResponse httpResponse = WebUtils.toHttp(response);
+ httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ String authcHeader = getAuthcScheme() + " realm=\"" + getApplicationName() + "\"";
+ httpResponse.setHeader(AUTHENTICATE_HEADER, authcHeader);
+ return false;
+ }
+
+ /**
+ * Creates an AuthenticationToken for use during login attempt with the provided credentials in the http header.
+ * <p/>
+ * This implementation:
+ * <ol><li>acquires the username and password based on the request's
+ * {@link #getAuthzHeader(javax.servlet.ServletRequest) authorization header} via the
+ * {@link #getPrincipalsAndCredentials(String, javax.servlet.ServletRequest) getPrincipalsAndCredentials} method</li>
+ * <li>The return value of that method is converted to an <code>AuthenticationToken</code> via the
+ * {@link #createToken(String, String, javax.servlet.ServletRequest, javax.servlet.ServletResponse) createToken} method</li>
+ * <li>The created <code>AuthenticationToken</code> is returned.</li>
+ * </ol>
+ *
+ * @param request incoming ServletRequest
+ * @param response outgoing ServletResponse
+ * @return the AuthenticationToken used to execute the login attempt
+ */
+ protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
+ String authorizationHeader = getAuthzHeader(request);
+ if (authorizationHeader == null || authorizationHeader.length() == 0) {
+ return null;
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("Attempting to execute login with headers [" + authorizationHeader + "]");
+ }
+
+ String[] prinCred = getPrincipalsAndCredentials(authorizationHeader, request);
+ if (prinCred == null || prinCred.length < 2) {
+ return null;
+ }
+
+ String username = prinCred[0];
+ String password = prinCred[1];
+
+ return createToken(username, password, request, response);
+ }
+
+ /**
+ * Returns the username obtained from the
+ * {@link #getAuthzHeader(javax.servlet.ServletRequest) authorizationHeader}.
+ * <p/>
+ * Once the <code>authzHeader is split per the RFC (based on the space character, " "), the resulting split tokens
+ * are translated into the username/password pair by the
+ * {@link #getPrincipalsAndCredentials(String, String) getPrincipalsAndCredentials(scheme,encoded)} method.
+ *
+ * @param authorizationHeader the authorization header obtained from the request.
+ * @param request the incoming ServletRequest
+ * @return the username (index 0)/password pair (index 1) submitted by the user for the given header value and request.
+ * @see #getAuthzHeader(javax.servlet.ServletRequest)
+ */
+ protected String[] getPrincipalsAndCredentials(String authorizationHeader, ServletRequest request) {
+ if (authorizationHeader == null) {
+ return null;
+ }
+ String[] authTokens = authorizationHeader.split(" ");
+ if (authTokens == null || authTokens.length < 2) {
+ return null;
+ }
+ return getPrincipalsAndCredentials(authTokens[0], authTokens[1]);
+ }
+
+ /**
+ * Returns the username and password pair based on the specified <code>encoded</code> String obtained from
+ * the request's authorization header.
+ * <p/>
+ * Per RFC 2617, the default implementation first Base64 decodes the string and then splits the resulting decoded
+ * string into two based on the ":" character. That is:
+ * <p/>
+ * <code>String decoded = Base64.decodeToString(encoded);<br/>
+ * return decoded.split(":");</code>
+ *
+ * @param scheme the {@link #getAuthcScheme() authcScheme} found in the request
+ * {@link #getAuthzHeader(javax.servlet.ServletRequest) authzHeader}. It is ignored by this implementation,
+ * but available to overriding implementations should they find it useful.
+ * @param encoded the Base64-encoded username:password value found after the scheme in the header
+ * @return the username (index 0)/password (index 1) pair obtained from the encoded header data.
+ */
+ protected String[] getPrincipalsAndCredentials(String scheme, String encoded) {
+ String decoded = Base64.decodeToString(encoded);
+ return decoded.split(":");
+ }
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/FormAuthenticationFilter.java b/web/src/org/jsecurity/web/filter/authc/FormAuthenticationFilter.java
new file mode 100644
index 0000000..33c5554
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/FormAuthenticationFilter.java
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authc.AuthenticationException;
+import org.jsecurity.authc.AuthenticationToken;
+import org.jsecurity.authc.UsernamePasswordToken;
+import org.jsecurity.subject.Subject;
+import org.jsecurity.web.WebUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * Requires the requesting user to be authenticated for the request to continue, and if they are not, forces the user
+ * to login via by redirecting them to the {@link #setLoginUrl(String) loginUrl} you configure.
+ *
+ * <p>This filter constructs a {@link UsernamePasswordToken UsernamePasswordToken} with the values found in
+ * {@link #setUsernameParam(String) username}, {@link #setPasswordParam(String) password},
+ * and {@link #setRememberMeParam(String) rememberMe} request parameters. It then calls
+ * {@link org.jsecurity.subject.Subject#login(org.jsecurity.authc.AuthenticationToken) Subject.login(usernamePasswordToken)},
+ * effectively automatically performing a login attempt. Note that the login attempt will only occur when the
+ * {@link #isLoginSubmission(javax.servlet.ServletRequest, javax.servlet.ServletResponse) isLoginSubmission(request,response)}
+ * is <code>true</code>, which by default occurs when the request is for the {@link #setLoginUrl(String) loginUrl} and
+ * is a POST request.
+ *
+ * <p>If the login attempt fails, the resulting <code>AuthenticationException</code> fully qualified class name will
+ * be set as a request attribute under the {@link #setFailureKeyAttribute(String) failureKeyAttribute} key. This
+ * FQCN can be used as an i18n key or lookup mechanism to explain to the user why their login attempt failed
+ * (e.g. no account, incorrect password, etc).
+ *
+ * <p>If you would prefer to handle the authentication validation and login in your own code, consider using the
+ * {@link org.jsecurity.web.filter.authc.PassThruAuthenticationFilter} instead, which allows requests to the
+ * {@link #loginUrl} to pass through to your application's code directly.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @see org.jsecurity.web.filter.authc.PassThruAuthenticationFilter
+ * @since 0.9
+ */
+public class FormAuthenticationFilter extends AuthenticatingFilter {
+
+ //TODO - complete JavaDoc
+
+ public static final String DEFAULT_ERROR_KEY_ATTRIBUTE_NAME = "jsecLoginFailure";
+
+ public static final String DEFAULT_USERNAME_PARAM = "username";
+ public static final String DEFAULT_PASSWORD_PARAM = "password";
+ public static final String DEFAULT_REMEMBER_ME_PARAM = "rememberMe";
+
+ private static final Log log = LogFactory.getLog(FormAuthenticationFilter.class);
+
+ private String usernameParam = DEFAULT_USERNAME_PARAM;
+ private String passwordParam = DEFAULT_PASSWORD_PARAM;
+ private String rememberMeParam = DEFAULT_REMEMBER_ME_PARAM;
+
+ private String failureKeyAttribute = DEFAULT_ERROR_KEY_ATTRIBUTE_NAME;
+
+ public FormAuthenticationFilter() {
+ setLoginUrl(DEFAULT_LOGIN_URL);
+ }
+
+ public String getUsernameParam() {
+ return usernameParam;
+ }
+
+ /**
+ * Sets the request parameter name to look for when acquiring the username. Unless overridden by calling this
+ * method, the default is <code>username</code>.
+ *
+ * @param usernameParam the name of the request param to check for acquiring the username.
+ */
+ public void setUsernameParam(String usernameParam) {
+ this.usernameParam = usernameParam;
+ }
+
+ public String getPasswordParam() {
+ return passwordParam;
+ }
+
+ /**
+ * Sets the request parameter name to look for when acquiring the password. Unless overridden by calling this
+ * method, the default is <code>password</code>.
+ *
+ * @param passwordParam the name of the request param to check for acquiring the password.
+ */
+ public void setPasswordParam(String passwordParam) {
+ this.passwordParam = passwordParam;
+ }
+
+ public String getRememberMeParam() {
+ return rememberMeParam;
+ }
+
+ /**
+ * Sets the request parameter name to look for when acquiring the rememberMe boolean value. Unless overridden
+ * by calling this method, the default is <code>rememberMe</code>.
+ * <p/>
+ * RememberMe will be <code>true</code> if the parameter value equals any of those supported by
+ * {@link WebUtils#isTrue(javax.servlet.ServletRequest, String) WebUtils.isTrue(request,value)}, <code>false</code>
+ * otherwise.
+ *
+ * @param rememberMeParam the name of the request param to check for acquiring the rememberMe boolean value.
+ */
+ public void setRememberMeParam(String rememberMeParam) {
+ this.rememberMeParam = rememberMeParam;
+ }
+
+ public String getFailureKeyAttribute() {
+ return failureKeyAttribute;
+ }
+
+ public void setFailureKeyAttribute(String failureKeyAttribute) {
+ this.failureKeyAttribute = failureKeyAttribute;
+ }
+
+ @Override
+ protected void onFilterConfigSet() throws Exception {
+ if (log.isTraceEnabled()) {
+ log.trace("Adding default login url to applied paths.");
+ }
+ this.appliedPaths.put(getLoginUrl(), null);
+ }
+
+ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
+ if (isLoginRequest(request, response)) {
+ if (isLoginSubmission(request, response)) {
+ if (log.isTraceEnabled()) {
+ log.trace("Login submission detected. Attempting to execute login.");
+ }
+ return executeLogin(request, response);
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Login page view.");
+ }
+ //allow them to see the login page ;)
+ return true;
+ }
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Attempting to access a path which requires authentication. Forwarding to the " +
+ "Authentication url [" + getLoginUrl() + "]");
+ }
+
+ saveRequestAndRedirectToLogin(request, response);
+ return false;
+ }
+ }
+
+ /**
+ * This default implementation merely returns <code>true</code> if the request is an HTTP <code>POST</code>,
+ * <code>false</code> otherwise. Can be overridden by subclasses for custom login submission detection behavior.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse.
+ * @return <code>true</code> if the request is an HTTP <code>POST</code>, <code>false</code> otherwise.
+ */
+ protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
+ return (request instanceof HttpServletRequest) && WebUtils.toHttp(request).getMethod().equalsIgnoreCase(POST_METHOD);
+ }
+
+ protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
+ String username = getUsername(request);
+ String password = getPassword(request);
+ return createToken(username, password, request, response);
+ }
+
+ protected boolean isRememberMe(ServletRequest request) {
+ return WebUtils.isTrue(request, getRememberMeParam());
+ }
+
+ protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
+ ServletRequest request, ServletResponse response) throws Exception {
+ issueSuccessRedirect(request, response);
+ //we handled the success redirect directly, prevent the chain from continuing:
+ return false;
+ }
+
+ protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
+ ServletRequest request, ServletResponse response) {
+ setFailureAttribute(request, e);
+ //login failed, let request continue back to the login page:
+ return true;
+ }
+
+ protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
+ String className = ae.getClass().getName();
+ request.setAttribute(getFailureKeyAttribute(), className);
+ }
+
+ protected String getUsername(ServletRequest request) {
+ return WebUtils.getCleanParam(request, getUsernameParam());
+ }
+
+ protected String getPassword(ServletRequest request) {
+ return WebUtils.getCleanParam(request, getPasswordParam());
+ }
+
+
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/PassThruAuthenticationFilter.java b/web/src/org/jsecurity/web/filter/authc/PassThruAuthenticationFilter.java
new file mode 100644
index 0000000..f9ff960
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/PassThruAuthenticationFilter.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * An authentication filter that redirects the user to the login page when they are trying to access
+ * a protected resource. However, if the user is trying to access the login page, the filter lets
+ * the request pass through to the application code.
+ * <p/>
+ * The difference between this filter and the {@link FormAuthenticationFilter FormAuthenticationFilter} is that
+ * on a login submission (by default an HTTP POST to the login URL), the <code>FormAuthenticationFilter</code> filter
+ * attempts to automatically authenticate the user by passing the <code>username</code> and <code>password</code>
+ * request parameter values to
+ * {@link org.jsecurity.subject.Subject#login(org.jsecurity.authc.AuthenticationToken) Subject.login(usernamePasswordToken)}
+ * directly.
+ * <p/>
+ * Conversely, this controller always passes all requests to the {@link #setLoginUrl loginUrl} through, both GETs and
+ * POSTs. This is useful in cases where the developer wants to write their own login behavior, which should include a
+ * call to {@link org.jsecurity.subject.Subject#login(org.jsecurity.authc.AuthenticationToken) Subject.login(AuthenticationToken)}
+ * at some point. For example, if the developer has their own custom MVC login controller or validator,
+ * this <code>PassThruAuthenticationFilter</code> may be appropriate.
+ *
+ * @author Jeremy Haile
+ * @see FormAuthenticationFilter
+ * @since 0.9
+ */
+public class PassThruAuthenticationFilter extends AuthenticationFilter {
+
+ //TODO - complete JavaDoc
+
+ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
+ if (isLoginRequest(request, response)) {
+ return true;
+ } else {
+ saveRequestAndRedirectToLogin(request, response);
+ return false;
+ }
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/filter/authc/UserFilter.java b/web/src/org/jsecurity/web/filter/authc/UserFilter.java
new file mode 100644
index 0000000..44b8470
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authc/UserFilter.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authc;
+
+import org.jsecurity.subject.Subject;
+import org.jsecurity.web.filter.AccessControlFilter;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * Filter that allows access to resources if the accessor is a known user, which is defined as
+ * having a known principal. This means that any user who is authenticated or remembered via a
+ * 'remember me' feature will be allowed access from this filter.
+ * <p/>
+ * If the accessor is not a known user, then they will be redirected to the {@link #setLoginUrl(String) loginUrl}</p>
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class UserFilter extends AccessControlFilter {
+
+ /**
+ * Returns <code>true</code> if the request is a
+ * {@link #isLoginRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse) loginRequest} or
+ * if the current {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) subject}
+ * is not <code>null</code>, <code>false</code> otherwise.
+ *
+ * @return <code>true</code> if the request is a
+ * {@link #isLoginRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse) loginRequest} or
+ * if the current {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) subject}
+ * is not <code>null</code>, <code>false</code> otherwise.
+ */
+ protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
+ if (isLoginRequest(request, response)) {
+ return true;
+ } else {
+ Subject subject = getSubject(request, response);
+ // If principal is not null, then the user is known and should be allowed access.
+ return subject.getPrincipal() != null;
+ }
+ }
+
+ /**
+ * This default implementation simply calls
+ * {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse) saveRequestAndRedirectToLogin}
+ * and then immediately returns <code>false</code>, thereby preventing the chain from continuing so the redirect may
+ * execute.
+ */
+ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
+ saveRequestAndRedirectToLogin(request, response);
+ return false;
+ }
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/filter/authc/package-info.java
similarity index 76%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/filter/authc/package-info.java
index 8e597f2..987c4c5 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/filter/authc/package-info.java
@@ -1,23 +1,23 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Servlet {@link javax.servlet.Filter Filter} implementations specific to controlling access based on a
+ * subject's authentication status, or those that can execute authentications (log-ins) directly.
+ */
+package org.jsecurity.web.filter.authc;
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/filter/authz/AuthorizationFilter.java b/web/src/org/jsecurity/web/filter/authz/AuthorizationFilter.java
new file mode 100644
index 0000000..8b8f20c
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authz/AuthorizationFilter.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authz;
+
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.StringUtils;
+import org.jsecurity.web.WebUtils;
+import org.jsecurity.web.filter.AccessControlFilter;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * Superclass for authorization-related filters. For unauthorized requests, this filter redirects to the
+ * login page if the current user is unknown (i.e. not authenticated or remembered). If the user is known,
+ * the filter redirects to an unauthorized URL or returns an unauthorized HTTP status code if no unauthorized
+ * URL is specified.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public abstract class AuthorizationFilter extends AccessControlFilter {
+
+ //TODO - complete JavaDoc
+
+ private String unauthorizedUrl;
+
+ protected String getUnauthorizedUrl() {
+ return unauthorizedUrl;
+ }
+
+ public void setUnauthorizedUrl(String unauthorizedUrl) {
+ this.unauthorizedUrl = unauthorizedUrl;
+ }
+
+ protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
+
+ Subject subject = getSubject(request, response);
+ // If the subject isn't identified, redirect to login URL
+ if (subject.getPrincipal() == null) {
+ saveRequestAndRedirectToLogin(request, response);
+ return false;
+ } else {
+
+ // If subject is known but not authorized, redirect to the unauthorized URL if there is one
+ // If no unauthorized URL is specified, just return an unauthorized HTTP status code
+ WebUtils.toHttp(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ if (StringUtils.hasText(getUnauthorizedUrl())) {
+ WebUtils.issueRedirect(request, response, getUnauthorizedUrl());
+ }
+
+ }
+ return false;
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/filter/authz/PermissionsAuthorizationFilter.java b/web/src/org/jsecurity/web/filter/authz/PermissionsAuthorizationFilter.java
new file mode 100644
index 0000000..cb79f7a
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authz/PermissionsAuthorizationFilter.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authz;
+
+import org.jsecurity.subject.Subject;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+/**
+ * Filter that allows access if the current user has the permissions specified by the mapped value, or denies access
+ * if the user does not have all of the permissions specified.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public class PermissionsAuthorizationFilter extends AuthorizationFilter {
+
+ //TODO - complete JavaDoc
+
+ public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
+
+ Subject subject = getSubject(request, response);
+ String[] perms = (String[]) mappedValue;
+
+ boolean isPermitted = true;
+ if (perms != null && perms.length > 0) {
+ if (perms.length == 1) {
+ if (!subject.isPermitted(perms[0])) {
+ isPermitted = false;
+ }
+ } else {
+ if (!subject.isPermittedAll(perms)) {
+ isPermitted = false;
+ }
+ }
+ }
+
+ return isPermitted;
+ }
+}
diff --git a/web/src/org/jsecurity/web/filter/authz/RolesAuthorizationFilter.java b/web/src/org/jsecurity/web/filter/authz/RolesAuthorizationFilter.java
new file mode 100644
index 0000000..2a584c1
--- /dev/null
+++ b/web/src/org/jsecurity/web/filter/authz/RolesAuthorizationFilter.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.filter.authz;
+
+import org.jsecurity.subject.Subject;
+import org.jsecurity.util.CollectionUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+import java.util.Set;
+
+/**
+ * Filter that allows access if the current user has the roles specified by the mapped value, or denies access
+ * if the user does not have all of the roles specified.
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.9
+ */
+public class RolesAuthorizationFilter extends AuthorizationFilter {
+
+ //TODO - complete JavaDoc
+
+ @SuppressWarnings({"unchecked"})
+ public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
+
+ Subject subject = getSubject(request, response);
+ String[] rolesArray = (String[]) mappedValue;
+
+ if (rolesArray == null || rolesArray.length == 0) {
+ //no roles specified, so nothing to check - allow access.
+ return true;
+ }
+
+ Set<String> roles = CollectionUtils.asSet(rolesArray);
+ return subject.hasAllRoles(roles);
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/filter/authz/package-info.java
similarity index 77%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/filter/authz/package-info.java
index 8e597f2..a0aecb3 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/filter/authz/package-info.java
@@ -1,23 +1,23 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Servlet {@link javax.servlet.Filter Filter} implementations that perform authorization (access control)
+ * checks based on the Subject's abilities (for example, role or permission checks).
+ */
+package org.jsecurity.web.filter.authz;
\ No newline at end of file
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/filter/package-info.java
similarity index 77%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/filter/package-info.java
index 8e597f2..00a652c 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/filter/package-info.java
@@ -1,23 +1,23 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Base package supporting all Servlet {@link javax.servlet.Filter Filter} implementations used to control
+ * access to web pages and URL resources.
+ */
+package org.jsecurity.web.filter;
\ No newline at end of file
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/package-info.java
similarity index 77%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/package-info.java
index 8e597f2..b10a89b 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/package-info.java
@@ -1,23 +1,22 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Framework support for any web-enabled application.
+ */
+package org.jsecurity.web;
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/servlet/AdviceFilter.java b/web/src/org/jsecurity/web/servlet/AdviceFilter.java
new file mode 100644
index 0000000..4fafc86
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/AdviceFilter.java
@@ -0,0 +1,192 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+/**
+ * A Servlet Filter that enables AOP-style advice for a SerlvetRequest via
+ * {@link #preHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse) preHandle},
+ * {@link #postHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse) postHandle},
+ * and {@link #afterCompletion(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Exception) afterCompletion}
+ * hooks.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public abstract class AdviceFilter extends OncePerRequestFilter {
+
+ /** The static logger available to this class only */
+ private static final Log log = LogFactory.getLog(AdviceFilter.class);
+
+ /**
+ * Returns <code>true</code> if the filter chain should be allowed to continue, <code>false</code> otherwise.
+ * It is called before the chain is actually consulted/executed.
+ * <p/>
+ * The default implementation returns <code>true</code> always and exists as a template method for subclasses.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @return <code>true</code> if the filter chain should be allowed to continue, <code>false</code> otherwise.
+ * @throws Exception if there is any error.
+ */
+ protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
+ return true;
+ }
+
+ /**
+ * Allows 'post' advice logic to be called, but only if no exception occurs during filter chain execution. That
+ * is, if {@link #executeChain executeChain} throws an exception, this method will never be called. Be aware of
+ * this when implementing logic. Most resource 'cleanup' behavior is often done in the
+ * {@link #afterCompletion(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Exception) afterCompletion(request,response,exception)}
+ * implementation, which is guaranteed to be called for every request, even when the chain processing throws
+ * an Exception.
+ * <p/>
+ * The default implementation does nothing (no-op) and exists as a template method for subclasses.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @throws Exception if an error occurs.
+ */
+ protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
+ }
+
+ /**
+ * Called in all cases in a <code>finally</code> block even if {@link #preHandle preHandle} returns
+ * <code>false</code> or if an exception is thrown during filter chain processing. Can be used for resource
+ * cleanup if so desired.
+ * <p/>
+ * The default implementation does nothing (no-op) and exists as a template method for subclasses.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @param exception any exception thrown during {@link #preHandle preHandle}, {@link #executeChain executeChain},
+ * or {@link #postHandle postHandle} execution, or <code>null</code> if no exception was thrown
+ * (i.e. the chain processed successfully).
+ * @throws Exception if an error occurs.
+ */
+ public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception {
+ }
+
+ /**
+ * Actually executes the specified filter chain by calling <code>chain.doFilter(request,response);</code>.
+ * <p/>
+ * Can be overridden by subclasses for custom logic.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @param chain the filter chain to execute
+ * @throws Exception if there is any error executing the chain.
+ */
+ protected void executeChain(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception {
+ chain.doFilter(request, response);
+ }
+
+ /**
+ * Actually implements the chain execution logic, utilizing
+ * {@link #preHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse) pre},
+ * {@link #postHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse) post}, and
+ * {@link #afterCompletion(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Exception) after}
+ * advice hooks.
+ *
+ * @param request the incoming ServletRequest
+ * @param response the outgoing ServletResponse
+ * @param chain the filter chain to execute
+ * @throws ServletException if a servlet-related error occurs
+ * @throws IOException if an IO error occurs
+ */
+ @SuppressWarnings({"ThrowFromFinallyBlock"})
+ public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws ServletException, IOException {
+
+ Exception exception = null;
+
+ try {
+
+ boolean continueChain = preHandle(request, response);
+ if (log.isTraceEnabled()) {
+ log.trace("Invked preHandle method. Continuing chain?: [" + continueChain + "]");
+ }
+
+ if (continueChain) {
+ executeChain(request, response, chain);
+ }
+
+ postHandle(request, response);
+ if (log.isTraceEnabled()) {
+ log.trace("Successfully invoked postHandle method");
+ }
+
+ } catch (Exception e) {
+ exception = e;
+ } finally {
+ cleanup( request, response, exception );
+ }
+ }
+
+ /**
+ * Executes cleanup logic in the <code>finally</code> code block in the
+ * {@link #doFilterInternal(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) doFilterInternal}
+ * implementation.
+ * <p/>
+ * This implementation specifically calls
+ * {@link #afterCompletion(javax.servlet.ServletRequest, javax.servlet.ServletResponse, Exception) afterCompletion}
+ * as well as handles any exceptions properly.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @param existing any exception that might have occurred while executing the <code>FilterChain</code> or
+ * pre or post advice, or <code>null</code> if the pre/chain/post excution did not throw an <code>Exception</code>.
+ * @throws ServletException if any exception other than an <code>IOException</code> is thrown.
+ * @throws IOException if the pre/chain/post execution throw an <code>IOException</code>
+ */
+ protected void cleanup( ServletRequest request, ServletResponse response, Exception existing )
+ throws ServletException, IOException {
+ Exception exception = existing;
+ try {
+ afterCompletion(request, response, exception);
+ if (log.isTraceEnabled()) {
+ log.trace("Successfully invoked afterCompletion method.");
+ }
+ } catch (Exception e) {
+ if (exception == null) {
+ exception = e;
+ }
+ }
+ if (exception != null) {
+ if (exception instanceof ServletException) {
+ throw (ServletException) exception;
+ } else if (exception instanceof IOException) {
+ throw (IOException) exception;
+ } else {
+ String msg = "Filter execution resulted in an unexpected Exception " +
+ "(not IOException or ServletException as the Filter api recommends). " +
+ "Wrapping in ServletException and propagating.";
+ throw new ServletException(msg, exception);
+ }
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/JSecurityFilter.java b/web/src/org/jsecurity/web/servlet/JSecurityFilter.java
new file mode 100644
index 0000000..f297c1c
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/JSecurityFilter.java
@@ -0,0 +1,397 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import org.apache.commons.beanutils.PropertyUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.config.Configuration;
+import org.jsecurity.config.ConfigurationException;
+import org.jsecurity.mgt.SecurityManager;
+import org.jsecurity.util.ClassUtils;
+import org.jsecurity.util.LifecycleUtils;
+import static org.jsecurity.util.StringUtils.clean;
+import org.jsecurity.util.ThreadContext;
+import org.jsecurity.web.DefaultWebSecurityManager;
+import org.jsecurity.web.WebUtils;
+import org.jsecurity.web.config.IniWebConfiguration;
+import org.jsecurity.web.config.WebConfiguration;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.beans.PropertyDescriptor;
+import java.io.IOException;
+import java.net.InetAddress;
+
+/**
+ * Main ServletFilter that configures and enables all JSecurity functions within a web application.
+ *
+ * The following is a fully commented example that documents how to configure it:
+ *
+ * <pre><filter>
+ * <filter-name>JSecurityFilter</filter-name>
+ * <filter-class>org.jsecurity.web.servlet.JSecurityFilter</filter-class>
+ * <init-param><param-name>config</param-name><param-value>
+ *
+ * #NOTE: This config looks pretty long - but its not - its only 5 lines of actual config.
+ * # Everything else is just heavily commented to explain things in-depth. Feel free to delete any
+ * # comments that you don't want to read from your own configuration ;)
+ * #
+ * # Any commented values below are JSecurity's defaults. If you want to change any values, you only
+ * # need to uncomment the lines you want to change.
+ *
+ * [main]
+ * # The 'main' section defines JSecurity-wide configuration.
+ * #
+ * # Session Mode: By default, JSecurity's Session infrastructure in a web environment will use the
+ * # Servlet container's HttpSession. However, if you need to share session state across client types
+ * # (e.g. Web MVC plus Java Web Start or Flash), or are doing distributed/shared Sessions for
+ * # Single Sign On, HttpSessions aren't good enough. You'll need to use JSecurity's more powerful
+ * # (and client-agnostic) session management. You can enable this by uncommenting the following line
+ * # and changing 'http' to 'jsecurity'
+ * #
+ * #securityManager = {@link org.jsecurity.web.DefaultWebSecurityManager org.jsecurity.web.DefaultWebSecurityManager}
+ * #securityManager.{@link org.jsecurity.web.DefaultWebSecurityManager#setSessionMode(String) sessionMode} = http
+ *
+ * [filters]
+ * # This section defines the 'pool' of all Filters available to the url path definitions in the [urls] section below.
+ * #
+ * # The following commented values are already provided by JSecurity by default and are immediately usable
+ * # in the [urls] definitions below. If you like, you may override any values by uncommenting only the lines
+ * # you need to change.
+ * #
+ * # Each Filter is configured based on its functionality and/or protocol. You should read each
+ * # Filter's JavaDoc to fully understand what each does and how it works as well as how it would
+ * # affect the user experience.
+ * #
+ * # Form-based Authentication filter:
+ * #<a name="authc"></a>authc = {@link org.jsecurity.web.filter.authc.FormAuthenticationFilter}
+ * #authc.{@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#setLoginUrl(String) loginUrl} = /login.jsp
+ * #authc.{@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#setUsernameParam(String) usernameParam} = username
+ * #authc.{@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#setPasswordParam(String) passwordParam} = password
+ * #authc.{@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#setRememberMeParam(String) rememberMeParam} = rememberMe
+ * #authc.{@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#setSuccessUrl(String) successUrl} = /login.jsp
+ * #authc.{@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#setFailureKeyAttribute(String) failureKeyAttribute} = {@link org.jsecurity.web.filter.authc.FormAuthenticationFilter#DEFAULT_ERROR_KEY_ATTRIBUTE_NAME}
+ * #
+ * # Http BASIC Authentication filter:
+ * #<a name="authcBasic"></a>authcBasic = {@link org.jsecurity.web.filter.authc.BasicHttpAuthenticationFilter}
+ * #authcBasic.{@link org.jsecurity.web.filter.authc.BasicHttpAuthenticationFilter#setApplicationName(String) applicationName} = application
+ * #
+ * # Roles filter: requires the requesting user to have one or more roles for the request to continue.
+ * # If they do not have the specified roles, they are redirected to the specified URL.
+ * #<a name="roles"></a>roles = {@link org.jsecurity.web.filter.authz.RolesAuthorizationFilter}
+ * #roles.{@link org.jsecurity.web.filter.authz.RolesAuthorizationFilter#setUnauthorizedUrl(String) unauthorizedUrl} =
+ * # (note the above url is null by default, which will cause an HTTP 403 (Access Denied) response instead
+ * # of redirecting to a page. If you want to show a 'nice page' instead, you should specify that url.
+ * #
+ * # Permissions filter: requires the requesting user to have one or more permissions for the request to
+ * # continue, and if they do not, redirects them to the specified URL.
+ * #<a name="perms"></a>perms = {@link org.jsecurity.web.filter.authz.PermissionsAuthorizationFilter}
+ * #perms.{@link org.jsecurity.web.filter.authz.PermissionsAuthorizationFilter#setUnauthorizedUrl(String) unauthorizedUrl} =
+ * # (note the above url is null by default, which will cause an HTTP 403 (Access Denied) response instead
+ * # of redirecting to a page. If you want to show a 'nice page' instead, you should specify that url. Many
+ * # applications like to use the same url specified in roles.unauthorizedUrl above.
+ * #
+ * #
+ * # Define your own filters here. To properly handle url path matching (see the [urls] section below), your
+ * # filter should extend the {@link org.jsecurity.web.filter.PathMatchingFilter PathMatchingFilter} abstract class.
+ *
+ * [urls]
+ * # This section defines url path mappings. Each mapping entry must be on a single line and conform to the
+ * # following representation:
+ * #
+ * # ant_path_expression = path_specific_filter_chain_definition
+ * #
+ * # For any request that matches a specified path, the corresponding value defines a comma-delimited chain of
+ * # filters to execute for that request.
+ * #
+ * # This is incredibly powerful in that you can define arbitrary filter chains for any given request pattern
+ * # to greatly customize the security experience.
+ * #
+ * # The path_specific_filter_chain_definition must match the following format:
+ * #
+ * # filter1[optional_config1], filter2[optional_config2], ..., filterN[optional_configN]
+ * #
+ * # where 'filterN' is the name of an filter defined above in the [filters] section and
+ * # '[optional_configN]' is an optional bracketed string that has meaning for that particular filter for
+ * # _that particular path_. If the filter does not need specific config for that url path, you may
+ * # discard the brackets - that is, filterN[] just becomes filterN.
+ * #
+ * # And because filter tokens define chains, order matters! Define the tokens for each path pattern
+ * # in the order you want them to filter (comma-delimited).
+ * #
+ * # Finally, each filter is free to handle the response however it wants if its necessary
+ * # conditions are not met (redirect, HTTP error code, direct rendering, etc). Otherwise, it is expected to allow
+ * # the request to continue through the chain on to the final destination view.
+ * #
+ * # Examples:
+ * #
+ * # To illustrate chain configuration, look at the /account/** mapping below. This says
+ * # "apply the above 'authcBasic' filter to any request matching the '/account/**' pattern". Since the
+ * # 'authcBasic' filter does not need any path-specific config, it doesn't have any config brackets [].
+ * #
+ * # The /remoting/** definition on the other hand uses the 'roles' and 'perms' filters which do use
+ * # bracket notation. That definition says:
+ * #
+ * # "To access /remoting/** urls, ensure that the user is first authenticated ('authcBasic'), then ensure that user
+ * # has the 'b2bClient' role, and then finally ensure that they have the 'remote:invoke:lan,wan' permission."
+ * #
+ * # (Note that because elements within brackets [ ] are comma-delimited themselves, we needed to escape the permission
+ * # actions of 'lan,wan' with quotes. If we didn't do that, the permission filter would interpret
+ * # the text between the brackets as two permissions: 'remote:invoke:lan' and 'wan' instead of the
+ * # single desired 'remote:invoke:lan,wan' token. So, you can use quotes wherever you need to escape internal
+ * # commas.)
+ *
+ * /account/** = <a href="#authcBasic">authcBasic</a>
+ * /remoting/** = <a href="#authcBasic">authcBasic</a>, <a href="#roles">roles</a>[b2bClient], <a href="#perms">perms</a>[remote:invoke:"lan,wan"]
+ *
+ * </param-value></init-param>
+ * </filter>
+ *
+ *
+ * <filter-mapping>
+ * <filter-name>JSecurityFilter</filter-name>
+ * <url-pattern>/*</url-pattern>
+ * </filter-mapping></pre>
+ *
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public class JSecurityFilter extends OncePerRequestFilter {
+
+ //TODO - complete JavaDoc
+
+ public static final String SECURITY_MANAGER_CONTEXT_KEY = SecurityManager.class.getName() + "_SERVLET_CONTEXT_KEY";
+
+ public static final String CONFIG_CLASS_NAME_INIT_PARAM_NAME = "configClassName";
+ public static final String CONFIG_INIT_PARAM_NAME = "config";
+ public static final String CONFIG_URL_INIT_PARAM_NAME = "configUrl";
+
+ private static final Log log = LogFactory.getLog(JSecurityFilter.class);
+
+ protected String config;
+ protected String configUrl;
+ protected String configClassName;
+ protected WebConfiguration configuration;
+
+ // Reference to the security manager used by this filter
+ protected SecurityManager securityManager;
+
+ public JSecurityFilter() {
+ this.configClassName = IniWebConfiguration.class.getName();
+ }
+
+ public WebConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ public void setConfiguration(WebConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ public SecurityManager getSecurityManager() {
+ return securityManager;
+ }
+
+ protected void setSecurityManager(SecurityManager sm) {
+ this.securityManager = sm;
+ }
+
+ protected void onFilterConfigSet() throws Exception {
+ applyInitParams();
+ WebConfiguration config = configure();
+ setConfiguration(config);
+
+ // Retrieve and store a reference to the security manager
+ SecurityManager sm = ensureSecurityManager(config);
+ setSecurityManager(sm);
+ }
+
+ /**
+ * Retrieves the security manager for the given configuration.
+ *
+ * @param config the configuration for this filter.
+ * @return the security manager that this filter should use.
+ */
+ protected SecurityManager ensureSecurityManager(Configuration config) {
+ SecurityManager sm = config.getSecurityManager();
+
+ // If the config doesn't return a security manager, build one by default.
+ if (sm == null) {
+ if (log.isInfoEnabled()) {
+ log.info("Configuration instance [" + config + "] did not provide a SecurityManager. No config " +
+ "specified? Defaulting to a " + DefaultWebSecurityManager.class.getName() + " instance...");
+ }
+ sm = new DefaultWebSecurityManager();
+ }
+
+ return sm;
+ }
+
+ protected void applyInitParams() {
+ FilterConfig config = getFilterConfig();
+
+ String configCN = clean(config.getInitParameter(CONFIG_CLASS_NAME_INIT_PARAM_NAME));
+ if (configCN != null) {
+ if (ClassUtils.isAvailable(configCN)) {
+ this.configClassName = configCN;
+ } else {
+ String msg = "configClassName fully qualified class name value [" + configCN + "] is not " +
+ "available in the classpath. Please ensure you have typed it correctly and the " +
+ "corresponding class or jar is in the classpath.";
+ throw new ConfigurationException(msg);
+ }
+ }
+
+ this.config = clean(config.getInitParameter(CONFIG_INIT_PARAM_NAME));
+ this.configUrl = clean(config.getInitParameter(CONFIG_URL_INIT_PARAM_NAME));
+ }
+
+ protected WebConfiguration configure() {
+ WebConfiguration conf = (WebConfiguration) ClassUtils.newInstance(this.configClassName);
+ applyFilterConfig(conf);
+ applyUrlConfig(conf);
+ applyEmbeddedConfig(conf);
+ LifecycleUtils.init(conf);
+ return conf;
+ }
+
+ protected void applyFilterConfig(WebConfiguration conf) {
+ if (log.isDebugEnabled()) {
+ String msg = "Attempting to inject the FilterConfig (using 'setFilterConfig' method) into the " +
+ "instantiated WebConfiguration for any wrapped Filter initialization...";
+ log.debug(msg);
+ }
+ try {
+ PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(conf, "filterConfig");
+ if (pd != null) {
+ PropertyUtils.setProperty(conf, "filterConfig", getFilterConfig());
+ }
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ log.debug("Error setting FilterConfig on WebConfiguration instance.", e);
+ }
+ }
+ }
+
+ protected void applyEmbeddedConfig(WebConfiguration conf) {
+ if (this.config != null) {
+ try {
+ PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(conf, "config");
+
+ if (pd != null) {
+ PropertyUtils.setProperty(conf, "config", this.config);
+ } else {
+ String msg = "The 'config' filter param was specified, but there is no " +
+ "'setConfig(String)' method on the Configuration instance [" + conf + "]. If you do " +
+ "not require the 'config' filter param, please comment it out, or if you do need it, " +
+ "please ensure your Configuration instance has a 'setConfig(String)' method to receive it.";
+ throw new ConfigurationException(msg);
+ }
+ } catch (Exception e) {
+ String msg = "There was an error setting the 'config' property of the Configuration object.";
+ throw new ConfigurationException(msg, e);
+ }
+ }
+ }
+
+ protected void applyUrlConfig(WebConfiguration conf) {
+ if (this.configUrl != null) {
+ try {
+ PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(conf, "configUrl");
+
+ if (pd != null) {
+ PropertyUtils.setProperty(conf, "configUrl", this.configUrl);
+ } else {
+ String msg = "The 'configUrl' filter param was specified, but there is no " +
+ "'setConfigUrl(String)' method on the Configuration instance [" + conf + "]. If you do " +
+ "not require the 'configUrl' filter param, please comment it out, or if you do need it, " +
+ "please ensure your Configuration instance has a 'setConfigUrl(String)' method to receive it.";
+ throw new ConfigurationException(msg);
+ }
+ } catch (Exception e) {
+ String msg = "There was an error setting the 'configUrl' property of the Configuration object.";
+ throw new ConfigurationException(msg, e);
+ }
+ }
+ }
+
+ protected boolean isHttpSessions() {
+ SecurityManager secMgr = getSecurityManager();
+ if (secMgr instanceof DefaultWebSecurityManager) {
+ return ((DefaultWebSecurityManager) secMgr).isHttpSessionMode();
+ } else {
+ return true;
+ }
+ }
+
+ protected InetAddress getInetAddress(ServletRequest request) {
+ return WebUtils.getInetAddress(request);
+ }
+
+ protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse,
+ FilterChain origChain) throws ServletException, IOException {
+
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ ThreadContext.bind(getInetAddress(request));
+
+ boolean httpSessions = isHttpSessions();
+ request = new JSecurityHttpServletRequest(request, getServletContext(), httpSessions);
+ if (!httpSessions) {
+ //the JSecurityHttpServletResponse exists to support URL rewriting for session ids. This is only needed if
+ //using JSecurity sessions (i.e. not simple HttpSession based sessions):
+ response = new JSecurityHttpServletResponse(response, getServletContext(), (JSecurityHttpServletRequest) request);
+ }
+
+ WebUtils.bind(request);
+ WebUtils.bind(response);
+ ThreadContext.bind(getSecurityManager());
+ ThreadContext.bind(getSecurityManager().getSubject());
+
+ FilterChain chain = getConfiguration().getChain(request, response, origChain);
+ if (chain == null) {
+ chain = origChain;
+ if (log.isTraceEnabled()) {
+ log.trace("No security filter chain configured for the current request. Using default.");
+ }
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace(" Using configured filter chain for the current request.");
+ }
+ }
+
+ try {
+ chain.doFilter(request, response);
+ } finally {
+ ThreadContext.unbindSubject();
+ ThreadContext.unbindSecurityManager();
+ WebUtils.unbindServletResponse();
+ WebUtils.unbindServletRequest();
+ ThreadContext.unbindInetAddress();
+ }
+ }
+
+ public void destroy() {
+ LifecycleUtils.destroy(getConfiguration());
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/JSecurityHttpServletRequest.java b/web/src/org/jsecurity/web/servlet/JSecurityHttpServletRequest.java
new file mode 100644
index 0000000..0932999
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/JSecurityHttpServletRequest.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import org.jsecurity.SecurityUtils;
+import org.jsecurity.session.Session;
+import org.jsecurity.subject.Subject;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import javax.servlet.http.HttpSession;
+import java.security.Principal;
+
+/**
+ * TODO class JavaDoc
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+@SuppressWarnings({"deprecated", "deprecation"})
+public class JSecurityHttpServletRequest extends HttpServletRequestWrapper {
+
+ //TODO - complete JavaDoc
+
+ //The following 7 constants support the JSecurity's implementation of the Servlet Specification
+ public static final String COOKIE_SESSION_ID_SOURCE = "cookie";
+ public static final String URL_SESSION_ID_SOURCE = "url";
+ public static final String REFERENCED_SESSION_ID = JSecurityHttpServletRequest.class.getName() + "_REQUESTED_SESSION_ID";
+ public static final String REFERENCED_SESSION_ID_IS_VALID = JSecurityHttpServletRequest.class.getName() + "_REQUESTED_SESSION_ID_VALID";
+ public static final String REFERENCED_SESSION_IS_NEW = JSecurityHttpServletRequest.class.getName() + "_REFERENCED_SESSION_IS_NEW";
+ public static final String REFERENCED_SESSION_ID_SOURCE = JSecurityHttpServletRequest.class.getName() + "REFERENCED_SESSION_ID_SOURCE";
+ public static final String SESSION_ID_NAME = JSecurityHttpSession.DEFAULT_SESSION_ID_NAME;
+ /**
+ * Key that may be used to alert that the request's referenced JSecurity Session has expired prior to
+ * request processing.
+ */
+ public static final String EXPIRED_SESSION_KEY = JSecurityHttpServletRequest.class.getName() + "_EXPIRED_SESSION_KEY";
+
+ protected ServletContext servletContext = null;
+
+ protected HttpSession session = null;
+ protected boolean httpSessions = true;
+
+ public JSecurityHttpServletRequest(HttpServletRequest wrapped, ServletContext servletContext,
+ boolean httpSessions) {
+ super(wrapped);
+ this.servletContext = servletContext;
+ this.httpSessions = httpSessions;
+ }
+
+ public boolean isHttpSessions() {
+ return httpSessions;
+ }
+
+ public String getRemoteUser() {
+ String remoteUser;
+ Object scPrincipal = getSubjectPrincipal();
+ if (scPrincipal != null) {
+ if (scPrincipal instanceof String) {
+ return (String) scPrincipal;
+ } else if (scPrincipal instanceof Principal) {
+ remoteUser = ((Principal) scPrincipal).getName();
+ } else {
+ remoteUser = scPrincipal.toString();
+ }
+ } else {
+ remoteUser = super.getRemoteUser();
+ }
+ return remoteUser;
+ }
+
+ protected Subject getSubject() {
+ return SecurityUtils.getSubject();
+ }
+
+ protected Object getSubjectPrincipal() {
+ Object userPrincipal = null;
+ Subject subject = getSubject();
+ if (subject != null) {
+ userPrincipal = subject.getPrincipal();
+ }
+ return userPrincipal;
+ }
+
+ public boolean isUserInRole(String s) {
+ Subject subject = getSubject();
+ boolean inRole = (subject != null && subject.hasRole(s));
+ if (!inRole) {
+ inRole = super.isUserInRole(s);
+ }
+ return inRole;
+ }
+
+ public Principal getUserPrincipal() {
+ Principal userPrincipal;
+ Object scPrincipal = getSubjectPrincipal();
+ if (scPrincipal != null) {
+ if (scPrincipal instanceof Principal) {
+ userPrincipal = (Principal) scPrincipal;
+ } else {
+ userPrincipal = new ObjectPrincipal(scPrincipal);
+ }
+ } else {
+ userPrincipal = super.getUserPrincipal();
+ }
+ return userPrincipal;
+ }
+
+ public String getRequestedSessionId() {
+ String requestedSessionId = null;
+ if (isHttpSessions()) {
+ requestedSessionId = super.getRequestedSessionId();
+ } else {
+ Object sessionId = getAttribute(REFERENCED_SESSION_ID);
+ if (sessionId != null) {
+ requestedSessionId = sessionId.toString();
+ }
+ }
+
+ return requestedSessionId;
+ }
+
+ public HttpSession getSession(boolean create) {
+
+ HttpSession httpSession;
+
+ if (isHttpSessions()) {
+ httpSession = super.getSession(create);
+ } else {
+ if (this.session == null) {
+
+ boolean existing = getSubject().getSession(false) != null;
+
+ Session jsecSession = getSubject().getSession(create);
+ if (jsecSession != null) {
+ this.session = new JSecurityHttpSession(jsecSession, this, this.servletContext);
+ if (!existing) {
+ setAttribute(REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
+ }
+ }
+ }
+ httpSession = this.session;
+ }
+
+ return httpSession;
+ }
+
+
+ public HttpSession getSession() {
+ return getSession(true);
+ }
+
+ public boolean isRequestedSessionIdValid() {
+ if (isHttpSessions()) {
+ return super.isRequestedSessionIdValid();
+ } else {
+ Boolean value = (Boolean) getAttribute(REFERENCED_SESSION_ID_IS_VALID);
+ return (value != null && value.equals(Boolean.TRUE));
+ }
+ }
+
+ public boolean isRequestedSessionIdFromCookie() {
+ if (isHttpSessions()) {
+ return super.isRequestedSessionIdFromCookie();
+ } else {
+ String value = (String) getAttribute(REFERENCED_SESSION_ID_SOURCE);
+ return value != null && value.equals(COOKIE_SESSION_ID_SOURCE);
+ }
+ }
+
+ public boolean isRequestedSessionIdFromURL() {
+ if (isHttpSessions()) {
+ return super.isRequestedSessionIdFromURL();
+ } else {
+ String value = (String) getAttribute(REFERENCED_SESSION_ID_SOURCE);
+ return value != null && value.equals(URL_SESSION_ID_SOURCE);
+ }
+ }
+
+ public boolean isRequestedSessionIdFromUrl() {
+ return isRequestedSessionIdFromURL();
+ }
+
+ private class ObjectPrincipal implements java.security.Principal {
+ private Object object = null;
+
+ public ObjectPrincipal(Object object) {
+ this.object = object;
+ }
+
+ public Object getObject() {
+ return object;
+ }
+
+ public String getName() {
+ return getObject().toString();
+ }
+
+ public int hashCode() {
+ return object.hashCode();
+ }
+
+ public boolean equals(Object o) {
+ if (o instanceof ObjectPrincipal) {
+ ObjectPrincipal op = (ObjectPrincipal) o;
+ return getObject().equals(op.getObject());
+ }
+ return false;
+ }
+
+ public String toString() {
+ return object.toString();
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/JSecurityHttpServletResponse.java b/web/src/org/jsecurity/web/servlet/JSecurityHttpServletResponse.java
new file mode 100644
index 0000000..0995e19
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/JSecurityHttpServletResponse.java
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+
+/**
+ * HttpServletResponse implementation to support URL Encoding of JSecurity Session IDs.
+ *
+ * It is only used when using JSecurity's native Session Management configuration (and not when using the Servlet
+ * Container session configuration, which is JSecurity's default in a web environment). Because the servlet container
+ * already performs url encoding of its own session ids, instances of this class are only needed when using JSecurity
+ * native sessions.
+ *
+ * <p>Note that this implementation relies in part on source code from the Tomcat 6.x distribution for
+ * encoding URLs for session ID URL Rewriting (we didn't want to re-invent the wheel). Since JSecurity is also
+ * Apache 2.0 license, all regular licenses and conditions have remained in tact.
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+@SuppressWarnings({"deprecated", "deprecation"})
+public class JSecurityHttpServletResponse extends HttpServletResponseWrapper {
+
+ //TODO - complete JavaDoc
+
+ private static final String DEFAULT_SESSION_ID_PARAMETER_NAME = JSecurityHttpSession.DEFAULT_SESSION_ID_NAME;
+
+ private ServletContext context = null;
+ //the associated request
+ private JSecurityHttpServletRequest request = null;
+
+ public JSecurityHttpServletResponse(HttpServletResponse wrapped, ServletContext context, JSecurityHttpServletRequest request) {
+ super(wrapped);
+ this.context = context;
+ this.request = request;
+ }
+
+ public ServletContext getContext() {
+ return context;
+ }
+
+ public void setContext(ServletContext context) {
+ this.context = context;
+ }
+
+ public JSecurityHttpServletRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(JSecurityHttpServletRequest request) {
+ this.request = request;
+ }
+
+ /**
+ * Encode the session identifier associated with this response
+ * into the specified redirect URL, if necessary.
+ *
+ * @param url URL to be encoded
+ */
+ public String encodeRedirectURL(String url) {
+ if (isEncodeable(toAbsolute(url))) {
+ return toEncoded(url, request.getSession().getId());
+ } else {
+ return url;
+ }
+ }
+
+
+ public String encodeRedirectUrl(String s) {
+ return encodeRedirectURL(s);
+ }
+
+
+ /**
+ * Encode the session identifier associated with this response
+ * into the specified URL, if necessary.
+ *
+ * @param url URL to be encoded
+ */
+ public String encodeURL(String url) {
+ String absolute = toAbsolute(url);
+ if (isEncodeable(absolute)) {
+ // W3c spec clearly said
+ if (url.equalsIgnoreCase("")) {
+ url = absolute;
+ }
+ return toEncoded(url, request.getSession().getId());
+ } else {
+ return url;
+ }
+ }
+
+ public String encodeUrl(String s) {
+ return encodeURL(s);
+ }
+
+ /**
+ * Return <code>true</code> if the specified URL should be encoded with
+ * a session identifier. This will be true if all of the following
+ * conditions are met:
+ * <ul>
+ * <li>The request we are responding to asked for a valid session
+ * <li>The requested session ID was not received via a cookie
+ * <li>The specified URL points back to somewhere within the web
+ * application that is responding to this request
+ * </ul>
+ *
+ * @param location Absolute URL to be validated
+ */
+ protected boolean isEncodeable(final String location) {
+
+ if (location == null)
+ return (false);
+
+ // Is this an intra-document reference?
+ if (location.startsWith("#"))
+ return (false);
+
+ // Are we in a valid session that is not using cookies?
+ final HttpServletRequest hreq = request;
+ final HttpSession session = hreq.getSession(false);
+ if (session == null)
+ return (false);
+ if (hreq.isRequestedSessionIdFromCookie())
+ return (false);
+
+ return doIsEncodeable(hreq, session, location);
+ }
+
+ private boolean doIsEncodeable(HttpServletRequest hreq, HttpSession session, String location) {
+ // Is this a valid absolute URL?
+ URL url = null;
+ try {
+ url = new URL(location);
+ } catch (MalformedURLException e) {
+ return (false);
+ }
+
+ // Does this URL match down to (and including) the context path?
+ if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol()))
+ return (false);
+ if (!hreq.getServerName().equalsIgnoreCase(url.getHost()))
+ return (false);
+ int serverPort = hreq.getServerPort();
+ if (serverPort == -1) {
+ if ("https".equals(hreq.getScheme()))
+ serverPort = 443;
+ else
+ serverPort = 80;
+ }
+ int urlPort = url.getPort();
+ if (urlPort == -1) {
+ if ("https".equals(url.getProtocol()))
+ urlPort = 443;
+ else
+ urlPort = 80;
+ }
+ if (serverPort != urlPort)
+ return (false);
+
+ String contextPath = getRequest().getContextPath();
+ if (contextPath != null) {
+ String file = url.getFile();
+ if ((file == null) || !file.startsWith(contextPath))
+ return (false);
+ String tok = ";" + DEFAULT_SESSION_ID_PARAMETER_NAME + "=" + session.getId();
+ if (file.indexOf(tok, contextPath.length()) >= 0)
+ return (false);
+ }
+
+ // This URL belongs to our web application, so it is encodeable
+ return (true);
+
+ }
+
+
+ /**
+ * Convert (if necessary) and return the absolute URL that represents the
+ * resource referenced by this possibly relative URL. If this URL is
+ * already absolute, return it unchanged.
+ *
+ * @param location URL to be (possibly) converted and then returned
+ * @throws IllegalArgumentException if a MalformedURLException is
+ * thrown when converting the relative URL to an absolute one
+ */
+ private String toAbsolute(String location) {
+
+ if (location == null)
+ return (location);
+
+ boolean leadingSlash = location.startsWith("/");
+
+ if (leadingSlash || !hasScheme(location)) {
+
+ StringBuffer buf = new StringBuffer();
+
+ String scheme = request.getScheme();
+ String name = request.getServerName();
+ int port = request.getServerPort();
+
+ try {
+ buf.append(scheme).append("://").append(name);
+ if ((scheme.equals("http") && port != 80)
+ || (scheme.equals("https") && port != 443)) {
+ buf.append(':').append(port);
+ }
+ if (!leadingSlash) {
+ String relativePath = request.getRequestURI();
+ int pos = relativePath.lastIndexOf('/');
+ relativePath = relativePath.substring(0, pos);
+
+ String encodedURI = URLEncoder.encode(relativePath, getCharacterEncoding());
+ buf.append(encodedURI).append('/');
+ }
+ buf.append(location);
+ } catch (IOException e) {
+ IllegalArgumentException iae = new IllegalArgumentException(location);
+ iae.initCause(e);
+ throw iae;
+ }
+
+ return buf.toString();
+
+ } else {
+ return location;
+ }
+ }
+
+ /**
+ * Determine if the character is allowed in the scheme of a URI.
+ * See RFC 2396, Section 3.1
+ */
+ public static boolean isSchemeChar(char c) {
+ return Character.isLetterOrDigit(c) ||
+ c == '+' || c == '-' || c == '.';
+ }
+
+
+ /**
+ * Determine if a URI string has a <code>scheme</code> component.
+ */
+ private boolean hasScheme(String uri) {
+ int len = uri.length();
+ for (int i = 0; i < len; i++) {
+ char c = uri.charAt(i);
+ if (c == ':') {
+ return i > 0;
+ } else if (!isSchemeChar(c)) {
+ return false;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return the specified URL with the specified session identifier
+ * suitably encoded.
+ *
+ * @param url URL to be encoded with the session id
+ * @param sessionId Session id to be included in the encoded URL
+ */
+ protected String toEncoded(String url, String sessionId) {
+
+ if ((url == null) || (sessionId == null))
+ return (url);
+
+ String path = url;
+ String query = "";
+ String anchor = "";
+ int question = url.indexOf('?');
+ if (question >= 0) {
+ path = url.substring(0, question);
+ query = url.substring(question);
+ }
+ int pound = path.indexOf('#');
+ if (pound >= 0) {
+ anchor = path.substring(pound);
+ path = path.substring(0, pound);
+ }
+ StringBuffer sb = new StringBuffer(path);
+ if (sb.length() > 0) { // jsessionid can't be first.
+ sb.append(";");
+ sb.append(DEFAULT_SESSION_ID_PARAMETER_NAME);
+ sb.append("=");
+ sb.append(sessionId);
+ }
+ sb.append(anchor);
+ sb.append(query);
+ return (sb.toString());
+
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/JSecurityHttpSession.java b/web/src/org/jsecurity/web/servlet/JSecurityHttpSession.java
new file mode 100644
index 0000000..61e3ba5
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/JSecurityHttpSession.java
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.web.session.WebSession;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.*;
+import java.util.*;
+
+/**
+ * Wrapper class that uses a JSecurity session under the hood for all session operations instead of the
+ * Servlet Container's session mechanism. This is preferred in heterogeneous client environments where the Session
+ * is used on both the business tier as well as in multiple client technologies (web, swing, flash, etc).
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+@SuppressWarnings({"deprecation"})
+public class JSecurityHttpSession implements HttpSession {
+
+ //TODO - complete JavaDoc
+
+ public static final String DEFAULT_SESSION_ID_NAME = "JSESSIONID";
+
+ private static final Enumeration EMPTY_ENUMERATION = new Enumeration() {
+ public boolean hasMoreElements() {
+ return false;
+ }
+
+ public Object nextElement() {
+ return null;
+ }
+ };
+
+ private static final HttpSessionContext HTTP_SESSION_CONTEXT = new HttpSessionContext() {
+ public HttpSession getSession(String s) {
+ return null;
+ }
+
+ public Enumeration getIds() {
+ return EMPTY_ENUMERATION;
+ }
+ };
+
+ protected ServletContext servletContext = null;
+ protected HttpServletRequest currentRequest = null;
+ protected Session session = null; //'real' JSecurity Session
+
+ public JSecurityHttpSession(Session session, HttpServletRequest currentRequest, ServletContext servletContext) {
+ if (session instanceof WebSession) {
+ String msg = "Session constructor argument cannot be an instance of WebSession. This is enforced to " +
+ "prevent circular dependencies and infinite loops.";
+ throw new IllegalArgumentException(msg);
+ }
+ this.session = session;
+ this.currentRequest = currentRequest;
+ this.servletContext = servletContext;
+ }
+
+ public Session getSession() {
+ return this.session;
+ }
+
+ public long getCreationTime() {
+ try {
+ return getSession().getStartTimestamp().getTime();
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public String getId() {
+ return getSession().getId().toString();
+ }
+
+ public long getLastAccessedTime() {
+ return getSession().getLastAccessTime().getTime();
+ }
+
+ public ServletContext getServletContext() {
+ return this.servletContext;
+ }
+
+ public void setMaxInactiveInterval(int i) {
+ try {
+ getSession().setTimeout(i * 1000);
+ } catch (InvalidSessionException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public int getMaxInactiveInterval() {
+ try {
+ return (new Long(getSession().getTimeout() / 1000)).intValue();
+ } catch (InvalidSessionException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public HttpSessionContext getSessionContext() {
+ return HTTP_SESSION_CONTEXT;
+ }
+
+ public Object getAttribute(String s) {
+ try {
+ return getSession().getAttribute(s);
+ } catch (InvalidSessionException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public Object getValue(String s) {
+ return getAttribute(s);
+ }
+
+ @SuppressWarnings({"unchecked"})
+ protected Set<String> getKeyNames() {
+ Collection<Object> keySet;
+ try {
+ keySet = getSession().getAttributeKeys();
+ } catch (InvalidSessionException e) {
+ throw new IllegalStateException(e);
+ }
+ Set<String> keyNames;
+ if (keySet != null && !keySet.isEmpty()) {
+ keyNames = new HashSet<String>(keySet.size());
+ for (Object o : keySet) {
+ keyNames.add(o.toString());
+ }
+ } else {
+ keyNames = Collections.EMPTY_SET;
+ }
+ return keyNames;
+ }
+
+ public Enumeration getAttributeNames() {
+ Set<String> keyNames = getKeyNames();
+ final Iterator iterator = keyNames.iterator();
+ return new Enumeration() {
+ public boolean hasMoreElements() {
+ return iterator.hasNext();
+ }
+
+ public Object nextElement() {
+ return iterator.next();
+ }
+ };
+ }
+
+ public String[] getValueNames() {
+ Set<String> keyNames = getKeyNames();
+ String[] array = new String[keyNames.size()];
+ if (keyNames.size() > 0) {
+ array = keyNames.toArray(array);
+ }
+ return array;
+ }
+
+ protected void afterBound(String s, Object o) {
+ if (o instanceof HttpSessionBindingListener) {
+ HttpSessionBindingListener listener = (HttpSessionBindingListener) o;
+ HttpSessionBindingEvent event = new HttpSessionBindingEvent(this, s, o);
+ listener.valueBound(event);
+ }
+ }
+
+ protected void afterUnbound(String s, Object o) {
+ if (o instanceof HttpSessionBindingListener) {
+ HttpSessionBindingListener listener = (HttpSessionBindingListener) o;
+ HttpSessionBindingEvent event = new HttpSessionBindingEvent(this, s, o);
+ listener.valueUnbound(event);
+ }
+ }
+
+ public void setAttribute(String s, Object o) {
+ try {
+ getSession().setAttribute(s, o);
+ afterBound(s, o);
+ } catch (InvalidSessionException e) {
+ //noinspection finally
+ try {
+ afterUnbound(s, o);
+ } finally {
+ //noinspection ThrowFromFinallyBlock
+ throw new IllegalStateException(e);
+ }
+ }
+ }
+
+ public void putValue(String s, Object o) {
+ setAttribute(s, o);
+ }
+
+ public void removeAttribute(String s) {
+ try {
+ Object attribute = getSession().removeAttribute(s);
+ afterUnbound(s, attribute);
+ } catch (InvalidSessionException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public void removeValue(String s) {
+ removeAttribute(s);
+ }
+
+ public void invalidate() {
+ try {
+ getSession().stop();
+ } catch (InvalidSessionException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public boolean isNew() {
+ Boolean value = (Boolean) currentRequest.getAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_IS_NEW);
+ return value != null && value.equals(Boolean.TRUE);
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/OncePerRequestFilter.java b/web/src/org/jsecurity/web/servlet/OncePerRequestFilter.java
new file mode 100644
index 0000000..a7d8606
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/OncePerRequestFilter.java
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.util.Nameable;
+
+import javax.servlet.*;
+import java.io.IOException;
+
+/**
+ * Filter base class that guarantees to be just executed once per request,
+ * on any servlet container. It provides a {@link #doFilterInternal}
+ * method with HttpServletRequest and HttpServletResponse arguments.
+ *
+ * <p>The {@link #getAlreadyFilteredAttributeName} method determines how
+ * to identify that a request is already filtered. The default implementation
+ * is based on the configured name of the concrete filter instance.
+ *
+ * <p><b>NOTE</b> This class was borrowed from the Spring framework, and as such,
+ * all copyright notices and author names have remained in tact.
+ *
+ * @author Les Hazlewood
+ * @author Juergen Hoeller
+ * @since 0.1
+ */
+public abstract class OncePerRequestFilter extends ServletContextSupport implements Filter, Nameable {
+
+ /** Private internal log instance. */
+ private static final Log log = LogFactory.getLog(OncePerRequestFilter.class);
+
+ /**
+ * Suffix that gets appended to the filter name for the "already filtered" request attribute.
+ *
+ * @see #getAlreadyFilteredAttributeName
+ */
+ public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED";
+
+ /** FilterConfig provided by the Servlet container at startup. */
+ protected FilterConfig filterConfig;
+
+ /** The name of this filter, unique within an application. */
+ private String name;
+
+ /**
+ * Returns the servlet container specified <code>FilterConfig</code> instance provided at
+ * {@link #init(javax.servlet.FilterConfig) startup}.
+ *
+ * @return the servlet container specified <code>FilterConfig</code> instance provided at startup.
+ */
+ public FilterConfig getFilterConfig() {
+ return filterConfig;
+ }
+
+ /**
+ * Sets the FilterConfig <em>and</em> the <code>ServletContext</code> as attributes of this class for use by
+ * subclasses. That is:
+ * <p/>
+ * <code>this.filterConfig = filterConfig;<br/>
+ * setServletContext(filterConfig.getServletContext());</code>
+ *
+ * @param filterConfig the FilterConfig instance provided by the Servlet container at startup.
+ */
+ public void setFilterConfig(FilterConfig filterConfig) {
+ this.filterConfig = filterConfig;
+ setServletContext(filterConfig.getServletContext());
+ }
+
+ /**
+ * Returns the name of this filter.
+ * <p/>
+ * Unless overridden by calling the {@link #setName(String) setName(String)} method, this value defaults to the
+ * filter name as specified by the servlet container at startup:
+ * <p/>
+ * <code>this.name = {@link #getFilterConfig() getFilterConfig()}.{@link FilterConfig#getFilterName() getName()};</code>
+ *
+ * @return the filter name, or <code>null</code> if none available
+ * @see javax.servlet.GenericServlet#getServletName()
+ * @see javax.servlet.FilterConfig#getFilterName()
+ */
+ protected String getName() {
+ if (this.name == null) {
+ FilterConfig config = getFilterConfig();
+ if (config != null) {
+ this.name = config.getFilterName();
+ }
+ }
+
+ return this.name;
+ }
+
+ /**
+ * Sets the filter's name.
+ * <p/>
+ * Unless overridden by calling this method, this value defaults to the filter name as specified by the
+ * servlet container at startup:
+ * <p/>
+ * <code>this.name = {@link #getFilterConfig() getFilterConfig()}.{@link FilterConfig#getFilterName() getName()};</code>
+ *
+ * @param name the name of the filter.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Sets the filter's {@link #setFilterConfig filterConfig} and then immediately calls
+ * {@link #onFilterConfigSet() onFilterConfigSet()} to trigger any processing a subclass might wish to perform.
+ *
+ * @param filterConfig the servlet container supplied FilterConfig instance.
+ * @throws ServletException if {@link #onFilterConfigSet() onFilterConfigSet()} throws an Exception.
+ */
+ public final void init(FilterConfig filterConfig) throws ServletException {
+ setFilterConfig(filterConfig);
+ try {
+ onFilterConfigSet();
+ } catch (Exception e) {
+ if (e instanceof ServletException) {
+ throw (ServletException) e;
+ } else {
+ if (log.isErrorEnabled()) {
+ log.error("Unable to start Filter: [" + e.getMessage() + "].", e);
+ }
+ throw new ServletException(e);
+ }
+ }
+ }
+
+ /**
+ * Template method to be overridden by subclasses to perform initialization logic at startup. The
+ * <code>ServletContext</code> and <code>FilterConfig</code> will be accessible
+ * (and non-<code>null</code>) at the time this method is invoked via the
+ * {@link #getServletContext() getServletContext()} and {@link #getFilterConfig() getFilterConfig()}
+ * methods respectively.
+ *
+ * @throws Exception if the subclass has an error upon initialization.
+ */
+ protected void onFilterConfigSet() throws Exception {
+ }
+
+ /**
+ * This <code>doFilter</code> implementation stores a request attribute for
+ * "already filtered", proceeding without filtering again if the
+ * attribute is already there.
+ *
+ * @see #getAlreadyFilteredAttributeName
+ * @see #shouldNotFilter
+ * @see #doFilterInternal
+ */
+ public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException {
+
+ String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
+ if (request.getAttribute(alreadyFilteredAttributeName) != null || shouldNotFilter(request)) {
+ if (log.isTraceEnabled()) {
+ log.trace("Filter already executed. Proceeding without invoking this filter.");
+ }
+ // Proceed without invoking this filter...
+ filterChain.doFilter(request, response);
+ } else {
+ // Do invoke this filter...
+ if (log.isTraceEnabled()) {
+ log.trace("Filter not yet executed. Executing now.");
+ }
+ request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
+ doFilterInternal(request, response, filterChain);
+ }
+ }
+
+ /**
+ * Return name of the request attribute that identifies that a request has already been filtered.
+ * <p/>
+ * The default implementation takes the configured {@link #getName() name} and appends ".FILTERED".
+ * If the filter is not fully initialized, it falls back to the implementation's class name.
+ *
+ * @return the name of the request attribute that identifies that a request has already been filtered.
+ * @see #getName
+ * @see #ALREADY_FILTERED_SUFFIX
+ */
+ protected String getAlreadyFilteredAttributeName() {
+ String name = getName();
+ if (name == null) {
+ name = getClass().getName();
+ }
+ return name + ALREADY_FILTERED_SUFFIX;
+ }
+
+ /**
+ * Can be overridden in subclasses for custom filtering control,
+ * returning <code>true</code> to avoid filtering of the given request.
+ * <p>The default implementation always returns <code>false</code>.
+ *
+ * @param request current HTTP request
+ * @return whether the given request should <i>not</i> be filtered
+ * @throws ServletException in case of errors
+ */
+ protected boolean shouldNotFilter(ServletRequest request) throws ServletException {
+ return false;
+ }
+
+
+ /**
+ * Same contract as for <code>doFilter</code>, but guaranteed to be
+ * just invoked once per request. Provides HttpServletRequest and
+ * HttpServletResponse arguments instead of the default ServletRequest
+ * and ServletResponse ones.
+ */
+ protected abstract void doFilterInternal(
+ ServletRequest request, ServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException;
+
+ /**
+ * Default no-op implementation that can be overridden by subclasses for custom cleanup behavior.
+ */
+ public void destroy() {
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/ProxiedFilterChain.java b/web/src/org/jsecurity/web/servlet/ProxiedFilterChain.java
new file mode 100644
index 0000000..e6f8306
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/ProxiedFilterChain.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.*;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class ProxiedFilterChain implements FilterChain {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(ProxiedFilterChain.class);
+
+ private FilterChain orig;
+ private List<Filter> filters;
+ private int index = 0;
+
+ public ProxiedFilterChain(FilterChain orig, List<Filter> filters) {
+ this.orig = orig;
+ this.filters = filters;
+ this.index = 0;
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
+ if (this.filters == null || this.filters.size() == this.index) {
+ //we've reached the end of the wrapped chain, so invoke the original one:
+ if (log.isTraceEnabled()) {
+ log.trace("Invoking original filter chain.");
+ }
+ this.orig.doFilter(request, response);
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Invoking wrapped filter at index [" + this.index + "]");
+ }
+ this.filters.get(this.index++).doFilter(request, response, this);
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/servlet/ServletContextSupport.java b/web/src/org/jsecurity/web/servlet/ServletContextSupport.java
new file mode 100644
index 0000000..9d2f76b
--- /dev/null
+++ b/web/src/org/jsecurity/web/servlet/ServletContextSupport.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.servlet;
+
+import javax.servlet.ServletContext;
+
+/**
+ * TODO - class javadoc
+ *
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class ServletContextSupport {
+
+ //TODO - complete JavaDoc
+ private ServletContext servletContext = null;
+
+ public ServletContext getServletContext() {
+ return servletContext;
+ }
+
+ public void setServletContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
+ protected String getContextInitParam(String paramName) {
+ return getServletContext().getInitParameter(paramName);
+ }
+
+ private ServletContext getServletContextNullCheck() {
+ ServletContext servletContext = getServletContext();
+ if (servletContext == null) {
+ String msg = "ServletContext property must be set via the setServletContext method.";
+ throw new IllegalStateException(msg);
+ }
+ return servletContext;
+ }
+
+ protected void setAttribute(String key, Object value) {
+ getServletContextNullCheck().setAttribute(key, value);
+ }
+
+ protected Object getAttribute(String key) {
+ return getServletContextNullCheck().getAttribute(key);
+ }
+
+ protected void removeAttribute(String key) {
+ getServletContextNullCheck().removeAttribute(key);
+ }
+
+ protected void bind(String name, String key, Object value) {
+ if (value == null) {
+ throw new IllegalArgumentException(name + " argument cannot be null.");
+ }
+ if (getAttribute(key) != null) {
+ String msg = name + " already bound to ServletContext. Please check your configuration to ensure " +
+ "you don't have mutliple SecurityManager Loaders configured (listener, servlet, etc).";
+ throw new IllegalStateException(msg);
+ }
+ setAttribute(key, value);
+ }
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/servlet/package-info.java
similarity index 77%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/servlet/package-info.java
index 8e597f2..60dd3f3 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/servlet/package-info.java
@@ -1,23 +1,23 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Support implementations that depend heavily on the <tt>javax.servlet.*</tt> API and are meant to be
+ * directly used in web.xml (Servlet Filters, Servlet Context Listeners, Servlets, etc)
+ */
+package org.jsecurity.web.servlet;
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/session/DefaultWebSessionManager.java b/web/src/org/jsecurity/web/session/DefaultWebSessionManager.java
new file mode 100644
index 0000000..8cb9cf2
--- /dev/null
+++ b/web/src/org/jsecurity/web/session/DefaultWebSessionManager.java
@@ -0,0 +1,316 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.session;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.HostUnauthorizedException;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.mgt.DefaultSessionManager;
+import org.jsecurity.web.WebUtils;
+import org.jsecurity.web.attr.CookieAttribute;
+import org.jsecurity.web.attr.RequestParamAttribute;
+import org.jsecurity.web.attr.WebAttribute;
+import org.jsecurity.web.servlet.JSecurityHttpServletRequest;
+import org.jsecurity.web.servlet.JSecurityHttpSession;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.Serializable;
+import java.net.InetAddress;
+
+/**
+ * Web-application capable <tt>SessionManager</tt> implementation.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class DefaultWebSessionManager extends DefaultSessionManager implements WebSessionManager {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(DefaultWebSessionManager.class);
+
+ /**
+ * Property specifying if, after a session object is acquired from the request, if that session should be
+ * validated to ensure the starting origin of the session is the same as the incoming request.
+ */
+ private boolean validateRequestOrigin = false; //default
+
+ protected CookieAttribute<Serializable> sessionIdCookieAttribute = null;
+ protected RequestParamAttribute<Serializable> sessionIdRequestParamAttribute = null;
+
+ public DefaultWebSessionManager() {
+ ensureCookieSessionIdStore();
+ ensureRequestParamSessionIdStore();
+ }
+
+ public CookieAttribute<Serializable> getSessionIdCookieAttribute() {
+ return sessionIdCookieAttribute;
+ }
+
+ public void setSessionIdCookieAttribute(CookieAttribute<Serializable> sessionIdCookieAttribute) {
+ this.sessionIdCookieAttribute = sessionIdCookieAttribute;
+ }
+
+ public RequestParamAttribute<Serializable> getSessionIdRequestParamAttribute() {
+ return sessionIdRequestParamAttribute;
+ }
+
+ public void setSessionIdRequestParamAttribute(RequestParamAttribute<Serializable> sessionIdRequestParamAttribute) {
+ this.sessionIdRequestParamAttribute = sessionIdRequestParamAttribute;
+ }
+
+ /**
+ * If set to <tt>true</tt>, this implementation will ensure that any
+ * <tt>HttpRequest</tt> attempting
+ * to join a session (i.e. via {@link #getSession getSession} must have the same
+ * IP Address of the <tt>HttpRequest</tt> that started the session.
+ *
+ * <p> If set to <tt>false</tt>, any <tt>HttpRequest</tt> with a reference to a valid
+ * session id may acquire that <tt>Session</tt>.
+ *
+ * <p>Although convenient, this should only be enabled in environments where the
+ * system can <em>guarantee</em> that each IP address represents one and only one
+ * machine accessing the system.
+ *
+ * <p>Public websites are not good candidates for enabling this
+ * feature since many browser clients often sit behind NAT routers (in
+ * which case many machines are viewed to come from the same IP, thereby making this
+ * validation check useless). Also, some internet service providers (e.g. AOL) may change a
+ * client's IP in mid-session, making subsequent requests appear to come from a different
+ * location. Again, this feature should only be enabled where IP Addresses can be guaranteed a
+ * 1-to-1 relationship with a user's session.
+ *
+ * <p>For the reasons specified above, this property is <tt>false</tt> by default.
+ *
+ * @return true if this factory will verify each HttpRequest joining a session
+ */
+ public boolean isValidateRequestOrigin() {
+ return validateRequestOrigin;
+ }
+
+ /**
+ * Sets whether or not a request's origin will be validated when accessing a session. See
+ * the {@link #isValidateRequestOrigin} JavaDoc for an in-depth explanation of this property.
+ *
+ * @param validateRequestOrigin whether or not to validate the request's origin when accessing
+ * a session.
+ * @see #isValidateRequestOrigin
+ */
+ public void setValidateRequestOrigin(boolean validateRequestOrigin) {
+ this.validateRequestOrigin = validateRequestOrigin;
+ }
+
+ public void setSessionIdCookieName(String name) {
+ getSessionIdCookieAttribute().setName(name);
+ }
+
+ public void setSessionIdCookiePath(String path) {
+ getSessionIdCookieAttribute().setPath(path);
+ }
+
+ public void setSessionIdCookieMaxAge(int maxAge) {
+ getSessionIdCookieAttribute().setMaxAge(maxAge);
+ }
+
+ public void setSessionIdCookieSecure(boolean secure) {
+ getSessionIdCookieAttribute().setSecure(secure);
+ }
+
+ protected void ensureCookieSessionIdStore() {
+ CookieAttribute<Serializable> cookieStore = getSessionIdCookieAttribute();
+ if (cookieStore == null) {
+ cookieStore = new CookieAttribute<Serializable>(JSecurityHttpSession.DEFAULT_SESSION_ID_NAME);
+ cookieStore.setCheckRequestParams(false);
+ setSessionIdCookieAttribute(cookieStore);
+ }
+ }
+
+ protected void ensureRequestParamSessionIdStore() {
+ RequestParamAttribute<Serializable> reqParamStore = getSessionIdRequestParamAttribute();
+ if (reqParamStore == null) {
+ reqParamStore = new RequestParamAttribute<Serializable>(JSecurityHttpSession.DEFAULT_SESSION_ID_NAME);
+ setSessionIdRequestParamAttribute(reqParamStore);
+ }
+ }
+
+ protected void validateSessionOrigin(ServletRequest request, Session session)
+ throws HostUnauthorizedException {
+ InetAddress requestIp = WebUtils.getInetAddress(request);
+ InetAddress originIp = session.getHostAddress();
+ Serializable sessionId = session.getId();
+
+ if (originIp == null) {
+ if (requestIp != null) {
+ String msg = "No IP Address was specified when creating session with id [" +
+ sessionId + "]. Attempting to access session from " +
+ "IP [" + requestIp + "]. Origin IP and request IP must match.";
+ throw new HostUnauthorizedException(msg);
+ }
+ } else {
+ if (requestIp != null) {
+ if (!requestIp.equals(originIp)) {
+ String msg = "Session with id [" + sessionId + "] originated from [" +
+ originIp + "], but the current HttpServletRequest originated " +
+ "from [" + requestIp + "]. Disallowing session access: " +
+ "session origin and request origin must match to allow access.";
+ throw new HostUnauthorizedException(msg);
+ }
+
+ } else {
+ String msg = "No IP Address associated with the current HttpServletRequest. " +
+ "Session with id [" + sessionId + "] originated from " +
+ "[" + originIp + "]. Request IP must match the session's origin " +
+ "IP in order to gain access to that session.";
+ throw new HostUnauthorizedException(msg);
+ }
+ }
+ }
+
+ protected void storeSessionId(Serializable currentId, ServletRequest request, ServletResponse response) {
+ if (currentId == null) {
+ String msg = "sessionId cannot be null when persisting for subsequent requests.";
+ throw new IllegalArgumentException(msg);
+ }
+ //ensure that the id has been set in the idStore, or if it already has, that it is not different than the
+ //'real' session value:
+ Serializable existingId = retrieveSessionId(request, response);
+ if (existingId == null || !currentId.equals(existingId)) {
+ getSessionIdCookieAttribute().storeValue(currentId, request, response);
+ }
+ }
+
+ protected Serializable retrieveSessionId(ServletRequest request, ServletResponse response) {
+ WebAttribute<Serializable> cookieSessionIdAttribute = getSessionIdCookieAttribute();
+ Serializable id = cookieSessionIdAttribute.retrieveValue(request, response);
+ if (id != null) {
+ request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
+ JSecurityHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
+ } else {
+ id = getSessionIdRequestParamAttribute().retrieveValue(request, response);
+ if (id != null) {
+ request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
+ JSecurityHttpServletRequest.URL_SESSION_ID_SOURCE);
+ }
+ }
+ return id;
+ }
+
+ public Serializable start(InetAddress hostAddress) throws HostUnauthorizedException, IllegalArgumentException {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ return start(request, response, hostAddress);
+ }
+
+ protected Serializable start(ServletRequest request, ServletResponse response, InetAddress inetAddress) {
+ Serializable sessionId = super.start(inetAddress);
+ storeSessionId(sessionId, request, response);
+ request.removeAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
+ request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
+ return sessionId;
+ }
+
+ public Session retrieveSession(Serializable sessionId) throws InvalidSessionException, AuthorizationException {
+ if (sessionId != null) {
+ return super.retrieveSession(sessionId);
+ } else {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ return getSession(request, response);
+ }
+ }
+
+ /**
+ * Returns the Session associated with the specified request if it is valid or <tt>null</tt> if a Session doesn't
+ * exist or it was invalid.
+ *
+ * @param request incoming servlet request
+ * @param response outgoing servlet response
+ * @return the Session associated with the incoming request or <tt>null</tt> if one does not exist.
+ * @throws org.jsecurity.session.InvalidSessionException
+ * if the associated Session has expired prior to invoking this method.
+ * @throws org.jsecurity.authz.AuthorizationException
+ * if the caller is not authorized to access the session associated with the request.
+ */
+ public final Session getSession(ServletRequest request, ServletResponse response)
+ throws InvalidSessionException, AuthorizationException {
+
+ Session session;
+ try {
+ session = doGetSession(request, response);
+ } catch (InvalidSessionException ise) {
+ if (log.isTraceEnabled()) {
+ log.trace("Request Session is invalid, message: [" + ise.getMessage() + "]. Removing any " +
+ "associated session cookie...");
+ }
+ getSessionIdCookieAttribute().removeValue(request, response);
+
+ //give subclass a chance to do something additional if necessary. Otherwise returning null is just fine:
+ session = handleInvalidSession(request, response, ise);
+ }
+
+ return session;
+ }
+
+ protected Session doGetSession(ServletRequest request, ServletResponse response) {
+
+ Session session = null;
+ Serializable sessionId = retrieveSessionId(request, response);
+
+ if (sessionId != null) {
+ request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
+ session = super.retrieveSession(sessionId);
+ if (isValidateRequestOrigin()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Validating request origin against session origin");
+ }
+ validateSessionOrigin(request, session);
+ }
+ if (session != null) {
+ request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
+ }
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("No JSecurity session id associated with the given " +
+ "HttpServletRequest. A Session will not be returned.");
+ }
+ }
+
+ return session;
+ }
+
+ protected Session handleInvalidSession(ServletRequest request,
+ ServletResponse response,
+ InvalidSessionException ise) {
+ if (log.isTraceEnabled()) {
+ log.trace("Sesssion associated with the current request is nonexistent or invalid. Returning null.");
+ }
+ return null;
+ }
+
+ protected void onStop(Session session) {
+ super.onStop(session);
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ getSessionIdCookieAttribute().removeValue(request, response);
+ }
+}
diff --git a/web/src/org/jsecurity/web/session/ServletContainerSessionManager.java b/web/src/org/jsecurity/web/session/ServletContainerSessionManager.java
new file mode 100644
index 0000000..7d18ac8
--- /dev/null
+++ b/web/src/org/jsecurity/web/session/ServletContainerSessionManager.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.session;
+
+import org.jsecurity.authz.AuthorizationException;
+import org.jsecurity.authz.HostUnauthorizedException;
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.session.mgt.AbstractSessionManager;
+import org.jsecurity.web.WebUtils;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import java.io.Serializable;
+import java.net.InetAddress;
+
+/**
+ * SessionManager implementation providing Session implementations that are merely wrappers for the
+ * Servlet container's HttpSession.
+ *
+ * <p>Despite its name, this implementation <em>does not</em> itself manage Sessions since the Servlet container
+ * provides the actual management support. This class mainly exists to 'impersonate' a regular JSecurity
+ * <tt>SessionManager</tt> so it can be pluggable into a normal JSecurity configuration in a pure web application.
+ *
+ * <p>Note that because this implementation relies on the <tt>HttpSession</tt>, it is only functional in a servlet
+ * container. I.e. it is <em>NOT</em> capable of supporting Sessions any clients other than HttpRequest/HttpResponse
+ * based clients.
+ *
+ * <p>Therefore, if you need heterogenous Session support across multiple client mediums (e.g. web pages,
+ * Flash applets, Java Web Start applications, etc.), use the {@link DefaultWebSessionManager WebSessionManager} instead. The
+ * <tt>WebSessionManager</tt> supports both traditional web-based access as well as non web-based clients.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class ServletContainerSessionManager extends AbstractSessionManager implements WebSessionManager {
+
+ //TODO - complete JavaDoc
+
+ public ServletContainerSessionManager() {
+ }
+
+ protected Session doGetSession(Serializable sessionId) throws InvalidSessionException {
+ //Ignore session id since there is no way to acquire a session based on an id in a servlet container
+ //(that is implementation agnostic)
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ ServletResponse response = WebUtils.getRequiredServletResponse();
+ return getSession(request, response);
+ }
+
+ public Session getSession(ServletRequest request, ServletResponse response) throws AuthorizationException {
+ Session session = null;
+ HttpSession httpSession = ((HttpServletRequest) request).getSession(false);
+ if (httpSession != null) {
+ session = createSession(httpSession, WebUtils.getInetAddress(request));
+ }
+ return session;
+ }
+
+ protected Session createSession(InetAddress originatingHost) throws HostUnauthorizedException, IllegalArgumentException {
+ ServletRequest request = WebUtils.getRequiredServletRequest();
+ HttpSession httpSession = ((HttpServletRequest) request).getSession();
+ return createSession(httpSession, originatingHost);
+ }
+
+ protected Session createSession(HttpSession httpSession, InetAddress inet) {
+ return new WebSession(httpSession, inet);
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/session/WebSession.java b/web/src/org/jsecurity/web/session/WebSession.java
new file mode 100644
index 0000000..4b4df61
--- /dev/null
+++ b/web/src/org/jsecurity/web/session/WebSession.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.session;
+
+import org.jsecurity.session.InvalidSessionException;
+import org.jsecurity.session.Session;
+import org.jsecurity.web.servlet.JSecurityHttpSession;
+
+import javax.servlet.http.HttpSession;
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Enumeration;
+
+/**
+ * TODO class JavaDoc
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class WebSession implements Session {
+
+ //TODO - complete JavaDoc
+
+ private static final String INET_ADDRESS_SESSION_KEY = WebSession.class.getName() + "_INET_ADDRESS_SESSION_KEY";
+ private static final String TOUCH_OBJECT_SESSION_KEY = WebSession.class.getName() + "_TOUCH_OBJECT_SESSION_KEY";
+
+ private HttpSession httpSession = null;
+
+ public WebSession(HttpSession httpSession, InetAddress inetAddress) {
+ if (httpSession == null) {
+ String msg = "HttpSession constructor argument cannot be null.";
+ throw new IllegalArgumentException(msg);
+ }
+ if (httpSession instanceof JSecurityHttpSession) {
+ String msg = "HttpSession constructor argument cannot be an instance of JSecurityHttpSession. This " +
+ "is enforced to prevent circular dependencies and infinite loops.";
+ throw new IllegalArgumentException(msg);
+ }
+ this.httpSession = httpSession;
+ if (inetAddress != null) {
+ setHostAddress(inetAddress);
+ }
+ }
+
+ public Serializable getId() {
+ return httpSession.getId();
+ }
+
+ public Date getStartTimestamp() {
+ return new Date(httpSession.getCreationTime());
+ }
+
+ public Date getLastAccessTime() {
+ return new Date(httpSession.getLastAccessedTime());
+ }
+
+ public long getTimeout() throws InvalidSessionException {
+ try {
+ return httpSession.getMaxInactiveInterval() * 1000;
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ public void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException {
+ try {
+ int timeout = Long.valueOf(maxIdleTimeInMillis / 1000).intValue();
+ httpSession.setMaxInactiveInterval(timeout);
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ protected void setHostAddress(InetAddress hostAddress) {
+ setAttribute(INET_ADDRESS_SESSION_KEY, hostAddress);
+ }
+
+ public InetAddress getHostAddress() {
+ return (InetAddress) getAttribute(INET_ADDRESS_SESSION_KEY);
+ }
+
+ public void touch() throws InvalidSessionException {
+ //just manipulate the session to update the access time:
+ try {
+ httpSession.setAttribute(TOUCH_OBJECT_SESSION_KEY, TOUCH_OBJECT_SESSION_KEY);
+ httpSession.removeAttribute(TOUCH_OBJECT_SESSION_KEY);
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ public void stop() throws InvalidSessionException {
+ try {
+ httpSession.invalidate();
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ public Collection<Object> getAttributeKeys() throws InvalidSessionException {
+ try {
+ Enumeration namesEnum = httpSession.getAttributeNames();
+ Collection<Object> keys = null;
+ if (namesEnum != null) {
+ keys = new ArrayList<Object>();
+ while (namesEnum.hasMoreElements()) {
+ keys.add(namesEnum.nextElement());
+ }
+ }
+ return keys;
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ private static String assertString(Object key) {
+ if (!(key instanceof String)) {
+ String msg = "HttpSession based implementations of the JSecurity Session interface requires attribute keys " +
+ "to be String objects. The HttpSession class does not support anything other than String keys.";
+ throw new IllegalArgumentException(msg);
+ }
+ return (String) key;
+ }
+
+ public Object getAttribute(Object key) throws InvalidSessionException {
+ try {
+ return httpSession.getAttribute(assertString(key));
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ public void setAttribute(Object key, Object value) throws InvalidSessionException {
+ try {
+ httpSession.setAttribute(assertString(key), value);
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+
+ public Object removeAttribute(Object key) throws InvalidSessionException {
+ try {
+ String sKey = assertString(key);
+ Object removed = httpSession.getAttribute(sKey);
+ httpSession.removeAttribute(sKey);
+ return removed;
+ } catch (Exception e) {
+ throw new InvalidSessionException(e);
+ }
+ }
+}
diff --git a/web/src/org/jsecurity/web/session/WebSessionManager.java b/web/src/org/jsecurity/web/session/WebSessionManager.java
new file mode 100644
index 0000000..b2f1fa0
--- /dev/null
+++ b/web/src/org/jsecurity/web/session/WebSessionManager.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.session;
+
+import org.jsecurity.session.Session;
+import org.jsecurity.session.mgt.SessionManager;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * A <code>WebSessionManager</code> is a <code>SessionManager</code> that has the ability to obtain
+ * {@link Session Session}s based on a {@link ServletRequest ServletRequest}/{@link ServletResponse ServletResponse}
+ * pair.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public interface WebSessionManager extends SessionManager {
+
+ /**
+ * Returns the current {@link Session Session} associated with the specified request pair, or
+ * <code>null</code> if there is no session associated with the request.
+ *
+ * @param request the incoming <code>ServletRequest</code>
+ * @param response the outgoing <code>ServletResponse</code>
+ * @return the current {@link Session Session} associated with the specified request pair, or
+ * <code>null</code> if there is no session associated with the request.
+ */
+ Session getSession(ServletRequest request, ServletResponse response);
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/session/package-info.java
similarity index 77%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/session/package-info.java
index 8e597f2..8f59c05 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/session/package-info.java
@@ -1,23 +1,22 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Components supporting Session management in web-enabled applications.
+ */
+package org.jsecurity.web.session;
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/tags/AuthenticatedTag.java b/web/src/org/jsecurity/web/tags/AuthenticatedTag.java
new file mode 100644
index 0000000..9e146b7
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/AuthenticatedTag.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * JSP tag that renders the tag body only if the current user has executed a <b>successful</b> authentication attempt
+ * <em>during their current session</em>.
+ *
+ * <p>This is more restrictive than the {@link UserTag}, which only
+ * ensures the current user is known to the system, either via a current login or from Remember Me services,
+ * which only makes the assumption that the current user is who they say they are, and does not guarantee it like
+ * this tag does.
+ *
+ * <p>The logically opposite tag of this one is the {@link NotAuthenticatedTag}
+ *
+ * @author Jeremy Haile
+ * @author Les Hazlewood
+ * @since 0.2
+ */
+public class AuthenticatedTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(AuthenticatedTag.class);
+
+ public int onDoStartTag() throws JspException {
+ if (getSubject() != null && getSubject().isAuthenticated()) {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject exists and is authenticated. Tag body will be evaluated.");
+ }
+ return TagSupport.EVAL_BODY_INCLUDE;
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject does not exist or is not authenticated. Tag body will not be evaluated.");
+ }
+ return TagSupport.SKIP_BODY;
+ }
+ }
+}
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/tags/GuestTag.java b/web/src/org/jsecurity/web/tags/GuestTag.java
new file mode 100644
index 0000000..a272a1b
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/GuestTag.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * JSP tag that renders the tag body if the current user <em>is not</em> known to the system, either because they
+ * haven't logged in yet, or because they have no 'RememberMe' identity.
+ *
+ * <p>The logically opposite tag of this one is the {@link UserTag}. Please read that class's JavaDoc as it explains
+ * more about the differences between Authenticated/Unauthenticated and User/Guest semantic differences.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class GuestTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(GuestTag.class);
+
+ public int onDoStartTag() throws JspException {
+ if (getSubject() == null || getSubject().getPrincipal() == null) {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject does not exist or does not have a known identity (aka 'principal'). " +
+ "Tag body will be evaluated.");
+ }
+ return TagSupport.EVAL_BODY_INCLUDE;
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject exists or has a known identity (aka 'principal'). " +
+ "Tag body will not be evaluated.");
+ }
+ return TagSupport.SKIP_BODY;
+ }
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/tags/HasAnyRolesTag.java b/web/src/org/jsecurity/web/tags/HasAnyRolesTag.java
new file mode 100644
index 0000000..1b54ab2
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/HasAnyRolesTag.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.jsecurity.subject.Subject;
+
+/**
+ * Displays body content if the current user has any of the roles specified.
+ *
+ * @author Jeremy Haile
+ * @since 0.2
+ */
+public class HasAnyRolesTag extends RoleTag {
+
+ //TODO - complete JavaDoc
+
+ // Delimeter that separates role names in tag attribute
+ private static final String ROLE_NAMES_DELIMETER = ",";
+
+ public HasAnyRolesTag() {
+ }
+
+ protected boolean showTagBody(String roleNames) {
+ boolean hasAnyRole = false;
+
+ Subject subject = getSubject();
+
+ if (subject != null) {
+
+ // Iterate through roles and check to see if the user has one of the roles
+ for (String role : roleNames.split(ROLE_NAMES_DELIMETER)) {
+
+ if (subject.hasRole(role.trim())) {
+ hasAnyRole = true;
+ break;
+ }
+
+ }
+
+ }
+
+ return hasAnyRole;
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/tags/HasPermissionTag.java
similarity index 72%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/tags/HasPermissionTag.java
index 8e597f2..4929d33 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/tags/HasPermissionTag.java
@@ -16,8 +16,22 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.web.tags;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public class HasPermissionTag extends PermissionTag {
+
+ //TODO - complete JavaDoc
+
+ public HasPermissionTag() {
+ }
+
+ protected boolean showTagBody(String p) {
+ return isPermitted(p);
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/tags/HasRoleTag.java
similarity index 71%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/tags/HasRoleTag.java
index 8e597f2..84a33cb 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/tags/HasRoleTag.java
@@ -16,8 +16,21 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.web.tags;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * @author Les Hazlewood
+ * @since 0.1
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public class HasRoleTag extends RoleTag {
+
+ //TODO - complete JavaDoc
+
+ public HasRoleTag() {
+ }
+
+ protected boolean showTagBody(String roleName) {
+ return getSubject() != null && getSubject().hasRole(roleName);
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/tags/LacksPermissionTag.java
similarity index 71%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/tags/LacksPermissionTag.java
index 8e597f2..6456827 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/tags/LacksPermissionTag.java
@@ -16,8 +16,22 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.web.tags;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public class LacksPermissionTag extends PermissionTag {
+
+ //TODO - complete JavaDoc
+
+ public LacksPermissionTag() {
+ }
+
+ protected boolean showTagBody(String p) {
+ return !isPermitted(p);
+ }
+
+}
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/tags/LacksRoleTag.java
similarity index 69%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/tags/LacksRoleTag.java
index 8e597f2..b267777 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/tags/LacksRoleTag.java
@@ -16,8 +16,22 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.jsecurity.web.tags;
+
/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
+ * @author Les Hazlewood
+ * @since 0.1
*/
-package org.jsecurity.mgt;
\ No newline at end of file
+public class LacksRoleTag extends RoleTag {
+
+ //TODO - complete JavaDoc
+
+ public LacksRoleTag() {
+ }
+
+ protected boolean showTagBody(String roleName) {
+ boolean hasRole = getSubject() != null && getSubject().hasRole(roleName);
+ return !hasRole;
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/tags/NotAuthenticatedTag.java b/web/src/org/jsecurity/web/tags/NotAuthenticatedTag.java
new file mode 100644
index 0000000..fa26519
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/NotAuthenticatedTag.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * JSP tag that renders the tag body only if the current user has <em>not</em> executed a successful authentication
+ * attempt <em>during their current session</em>.
+ *
+ * <p>The logically opposite tag of this one is the {@link AuthenticatedTag}.
+ *
+ * @author Jeremy Haile
+ * @since 0.2
+ */
+public class NotAuthenticatedTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(NotAuthenticatedTag.class);
+
+ public int onDoStartTag() throws JspException {
+ if (getSubject() == null || !getSubject().isAuthenticated()) {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject does not exist or is not authenticated. Tag body will be evaluated.");
+ }
+ return TagSupport.EVAL_BODY_INCLUDE;
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject exists and is authenticated. Tag body will not be evaluated.");
+ }
+ return TagSupport.SKIP_BODY;
+ }
+ }
+}
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/tags/PermissionTag.java b/web/src/org/jsecurity/web/tags/PermissionTag.java
new file mode 100644
index 0000000..b7a8aee
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/PermissionTag.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * @author Les Hazlewood
+ * @author Jeremy Haile
+ * @since 0.1
+ */
+public abstract class PermissionTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ private String name = null;
+
+ public PermissionTag() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ protected void verifyAttributes() throws JspException {
+ String permission = getName();
+
+ if (permission == null || permission.length() == 0) {
+ String msg = "The 'name' tag attribute must be set.";
+ throw new JspException(msg);
+ }
+ }
+
+ public int onDoStartTag() throws JspException {
+
+ String p = getName();
+
+ boolean show = showTagBody(p);
+ if (show) {
+ return TagSupport.EVAL_BODY_INCLUDE;
+ } else {
+ return TagSupport.SKIP_BODY;
+ }
+ }
+
+ protected boolean isPermitted(String p) {
+ return getSubject() != null && getSubject().isPermitted(p);
+ }
+
+ protected abstract boolean showTagBody(String p);
+
+}
diff --git a/web/src/org/jsecurity/web/tags/PrincipalTag.java b/web/src/org/jsecurity/web/tags/PrincipalTag.java
new file mode 100644
index 0000000..416b97a
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/PrincipalTag.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.JspTagException;
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.io.IOException;
+
+/**
+ * <p>Tag used to print out the String value of a user's default principal,
+ * or a specific principal as specified by the tag's attributes.</p>
+ *
+ * <p> If no attributes are specified, the tag prints out the <tt>toString()</tt>
+ * value of the user's default principal. If the <tt>type</tt> attribute
+ * is specified, the tag looks for a principal with the given type. If the
+ * <tt>property</tt> attribute is specified, the tag prints the string value of
+ * the specified property of the principal. If no principal is found or the user
+ * is not authenticated, the tag displays nothing unless a <tt>defaultValue</tt>
+ * is specified.</p>
+ *
+ * @author Jeremy Haile
+ * @since 0.2
+ */
+public class PrincipalTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ /*--------------------------------------------
+ | C O N S T A N T S |
+ ============================================*/
+
+ /*--------------------------------------------
+ | I N S T A N C E V A R I A B L E S |
+ ============================================*/
+ private static final Log log = LogFactory.getLog(PrincipalTag.class);
+
+ /**
+ * The type of principal to be retrieved, or null if the default principal should be used.
+ */
+ private String type;
+
+ /**
+ * The property name to retrieve of the principal, or null if the <tt>toString()</tt> value should be used.
+ */
+ private String property;
+
+ /**
+ * The default value that should be displayed if the user is not authenticated, or no principal is found.
+ */
+ private String defaultValue;
+
+ /*--------------------------------------------
+ | C O N S T R U C T O R S |
+ ============================================*/
+
+ /*--------------------------------------------
+ | A C C E S S O R S / M O D I F I E R S |
+ ============================================*/
+
+
+ public String getType() {
+ return type;
+ }
+
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+
+ public String getProperty() {
+ return property;
+ }
+
+
+ public void setProperty(String property) {
+ this.property = property;
+ }
+
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+
+ /*--------------------------------------------
+ | M E T H O D S |
+ ============================================*/
+
+
+ @SuppressWarnings({"unchecked"})
+ public int onDoStartTag() throws JspException {
+ String strValue = null;
+
+ if (getSubject() != null) {
+
+ // Get the principal to print out
+ Object principal;
+
+ if (type == null) {
+ principal = getSubject().getPrincipal();
+ } else {
+ principal = getPrincipalFromClassName();
+ }
+
+ // Get the string value of the principal
+ if (principal != null) {
+ if (property == null) {
+ strValue = principal.toString();
+ } else {
+ strValue = getPrincipalProperty(principal, property);
+ }
+ }
+
+ }
+
+ // Print out the principal value if not null
+ if (strValue != null) {
+ try {
+ pageContext.getOut().write(strValue);
+ } catch (IOException e) {
+ throw new JspTagException("Error writing [" + strValue + "] to JSP.", e);
+ }
+ }
+
+ return SKIP_BODY;
+ }
+
+ @SuppressWarnings({"unchecked"})
+ private Object getPrincipalFromClassName() {
+ Object principal = null;
+
+ try {
+ Class cls = Class.forName(type);
+ principal = getSubject().getPrincipals().oneByType(cls);
+ } catch (ClassNotFoundException e) {
+ if (log.isErrorEnabled()) {
+ log.error("Unable to find class for name [" + type + "]");
+ }
+ }
+ return principal;
+ }
+
+
+ private String getPrincipalProperty(Object principal, String property) throws JspTagException {
+ String strValue = null;
+
+ try {
+ BeanInfo bi = Introspector.getBeanInfo(principal.getClass());
+
+ // Loop through the properties to get the string value of the specified property
+ boolean foundProperty = false;
+ for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
+ if (pd.getName().equals(property)) {
+ Object value = pd.getReadMethod().invoke(principal, (Object[]) null);
+ strValue = String.valueOf(value);
+ foundProperty = true;
+ break;
+ }
+ }
+
+ if (!foundProperty) {
+ final String message = "Property [" + property + "] not found in principal of type [" + principal.getClass().getName() + "]";
+ if (log.isErrorEnabled()) {
+ log.error(message);
+ }
+ throw new JspTagException(message);
+ }
+
+ } catch (Exception e) {
+ final String message = "Error reading property [" + property + "] from principal of type [" + principal.getClass().getName() + "]";
+ if (log.isErrorEnabled()) {
+ log.error(message, e);
+ }
+ throw new JspTagException(message, e);
+ }
+
+ return strValue;
+ }
+}
\ No newline at end of file
diff --git a/web/src/org/jsecurity/web/tags/RoleTag.java b/web/src/org/jsecurity/web/tags/RoleTag.java
new file mode 100644
index 0000000..1b4bbda
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/RoleTag.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public abstract class RoleTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ private String name = null;
+
+ public RoleTag() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int onDoStartTag() throws JspException {
+ boolean show = showTagBody(getName());
+ if (show) {
+ return TagSupport.EVAL_BODY_INCLUDE;
+ } else {
+ return TagSupport.SKIP_BODY;
+ }
+ }
+
+ protected abstract boolean showTagBody(String roleName);
+
+}
diff --git a/web/src/org/jsecurity/web/tags/SecureTag.java b/web/src/org/jsecurity/web/tags/SecureTag.java
new file mode 100644
index 0000000..2d8d8ba
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/SecureTag.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jsecurity.SecurityUtils;
+import org.jsecurity.subject.Subject;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * @author Les Hazlewood
+ * @since 0.1
+ */
+public abstract class SecureTag extends TagSupport {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(SecureTag.class);
+
+ public SecureTag() {
+ }
+
+ protected Subject getSubject() {
+ return SecurityUtils.getSubject();
+ }
+
+ protected void verifyAttributes() throws JspException {
+ }
+
+ public int doStartTag() throws JspException {
+
+ verifyAttributes();
+
+ return onDoStartTag();
+ }
+
+ public abstract int onDoStartTag() throws JspException;
+}
diff --git a/web/src/org/jsecurity/web/tags/UserTag.java b/web/src/org/jsecurity/web/tags/UserTag.java
new file mode 100644
index 0000000..428a46e
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/UserTag.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jsecurity.web.tags;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.tagext.TagSupport;
+
+/**
+ * JSP tag that renders the tag body if the current user known to the system, either from a successful login attempt
+ * (not necessarily during the current session) or from 'RememberMe' services.
+ *
+ * <p><b>Note:</b> This is <em>less</em> restrictive than the <code>AuthenticatedTag</code> since it only assumes
+ * the user is who they say they are, either via a current session login <em>or</em> via Remember Me services, which
+ * makes no guarantee the user is who they say they are. The <code>AuthenticatedTag</code> however
+ * guarantees that the current user has logged in <em>during their current session</em>, proving they really are
+ * who they say they are.
+ *
+ * <p>The logically opposite tag of this one is the {@link GuestTag}.
+ *
+ * @author Les Hazlewood
+ * @since 0.9
+ */
+public class UserTag extends SecureTag {
+
+ //TODO - complete JavaDoc
+
+ private static final Log log = LogFactory.getLog(UserTag.class);
+
+ public int onDoStartTag() throws JspException {
+ if (getSubject() != null && getSubject().getPrincipal() != null) {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject has known identity (aka 'principal'). " +
+ "Tag body will be evaluated.");
+ }
+ return TagSupport.EVAL_BODY_INCLUDE;
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Subject does not exist or have a known identity (aka 'principal'). " +
+ "Tag body will not be evaluated.");
+ }
+ return TagSupport.SKIP_BODY;
+ }
+ }
+
+}
diff --git a/web/src/org/jsecurity/web/tags/jsecurity.tld b/web/src/org/jsecurity/web/tags/jsecurity.tld
new file mode 100644
index 0000000..9f539b6
--- /dev/null
+++ b/web/src/org/jsecurity/web/tags/jsecurity.tld
@@ -0,0 +1,166 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied. See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
+ "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
+
+<taglib>
+
+ <tlib-version>1.1.2</tlib-version>
+
+ <jsp-version>1.2</jsp-version>
+
+ <short-name>JSecurity</short-name>
+
+ <uri>http://www.jsecurity.org/tags</uri>
+
+ <description>JSecurity JSP Tag Library. Authors: Les Hazlewood, Jeremy Haile</description>
+
+ <tag>
+ <name>hasPermission</name>
+ <tag-class>org.jsecurity.web.tags.HasPermissionTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current Subject (user)
+ 'has' (implies) the specified permission (i.e the user has the specified ability).
+ </description>
+ <attribute>
+ <name>name</name>
+ <required>true</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ </tag>
+
+ <tag>
+ <name>lacksPermission</name>
+ <tag-class>org.jsecurity.web.tags.LacksPermissionTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current Subject (user) does
+ NOT have (not imply) the specified permission (i.e. the user lacks the specified ability)
+ </description>
+ <attribute>
+ <name>name</name>
+ <required>true</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ </tag>
+
+ <tag>
+ <name>hasRole</name>
+ <tag-class>org.jsecurity.web.tags.HasRoleTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current user has the specified role.</description>
+ <attribute>
+ <name>name</name>
+ <required>true</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ </tag>
+
+
+ <tag>
+ <name>hasAnyRoles</name>
+ <tag-class>org.jsecurity.web.tags.HasAnyRolesTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current user has one of the specified roles from a
+ comma-separated list of role names.
+ </description>
+ <attribute>
+ <name>name</name>
+ <required>true</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ </tag>
+
+ <tag>
+ <name>lacksRole</name>
+ <tag-class>org.jsecurity.web.tags.LacksRoleTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current user does NOT have the specified role
+ (i.e. they explicitly lack the specified role)
+ </description>
+ <attribute>
+ <name>name</name>
+ <required>true</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ </tag>
+
+ <tag>
+ <name>authenticated</name>
+ <tag-class>org.jsecurity.web.tags.AuthenticatedTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current user has successfully authenticated
+ _during their current session_. It is more restrictive than the 'user' tag.
+ It is logically opposite to the 'notAuthenticated' tag.
+ </description>
+ </tag>
+
+ <tag>
+ <name>notAuthenticated</name>
+ <tag-class>org.jsecurity.web.tags.NotAuthenticatedTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current user has NOT succesfully authenticated
+ _during their current session_. It is logically opposite to the 'authenticated' tag.
+ </description>
+ </tag>
+
+ <tag>
+ <name>user</name>
+ <tag-class>org.jsecurity.web.tags.UserTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current Subject has a known identity, either
+ from a previous login or from 'RememberMe' services. Note that this is semantically different
+ from the 'authenticated' tag, which is more restrictive. It is logically
+ opposite to the 'guest' tag.
+ </description>
+ </tag>
+
+ <tag>
+ <name>guest</name>
+ <tag-class>org.jsecurity.web.tags.GuestTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays body content only if the current Subject IS NOT known to the system, either
+ because they have not logged in or they have no corresponding 'RememberMe' identity. It is logically
+ opposite to the 'user' tag.
+ </description>
+ </tag>
+
+ <tag>
+ <name>principal</name>
+ <tag-class>org.jsecurity.web.tags.PrincipalTag</tag-class>
+ <body-content>JSP</body-content>
+ <description>Displays the user's principal or a property of the user's principal.</description>
+ <attribute>
+ <name>type</name>
+ <required>false</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ <attribute>
+ <name>property</name>
+ <required>false</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ <attribute>
+ <name>defaultValue</name>
+ <required>false</required>
+ <rtexprvalue>true</rtexprvalue>
+ </attribute>
+ </tag>
+
+</taglib>
\ No newline at end of file
diff --git a/src/org/jsecurity/mgt/package-info.java b/web/src/org/jsecurity/web/tags/package-info.java
similarity index 72%
copy from src/org/jsecurity/mgt/package-info.java
copy to web/src/org/jsecurity/web/tags/package-info.java
index 8e597f2..a89c19f 100644
--- a/src/org/jsecurity/mgt/package-info.java
+++ b/web/src/org/jsecurity/web/tags/package-info.java
@@ -1,23 +1,25 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Provides the master {@link org.jsecurity.mgt.SecurityManager SecurityManager} interface and a default implementation
- * hierarchy for managing all aspects of JSecurity's functionality in an application.
- */
-package org.jsecurity.mgt;
\ No newline at end of file
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/**
+ * Provides the JSecurity JSP Tag Library implementations.
+ * <p/>
+ * JSecurity JSP Tags can be used to evalute or not evaluate (show or not show) parts of a JSP page based on the
+ * current user's authentication status and/or authorization (access control) abilities.
+ */
+package org.jsecurity.web.tags;
\ No newline at end of file