Fix formatting.

This commit is contained in:
Ben Alex 2004-08-04 06:40:06 +00:00
parent be37d8292e
commit e006f521f4
14 changed files with 665 additions and 286 deletions

View File

@ -1,25 +1,51 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import java.security.Principal;
/**
* The AuthorityGranter interface is used to map a given principal to a role name.
* If a Windows NT login module were to be used from JAAS, an AuthrityGranter implementation could be created
* to map a NT Group Principal to a ROLE_USER role for instance.
* <br>
* The AuthorityGranter interface is used to map a given principal to a role
* name.
*
* <P>
* If a Windows NT login module were to be used from JAAS, an AuthrityGranter
* implementation could be created to map a NT Group Principal to a ROLE_USER
* role for instance. <br>
* </p>
*
* @author Ray Krueger
* @version $Id$
*/
public interface AuthorityGranter {
//~ Methods ================================================================
/**
* The grant method is called for each principal returned from the LoginContext subject.
* If the AuthorityGranter wishes to grant authority, it should return the role name, such as ROLE_USER.
* If the AuthrityGranter does not wish to grant any authority it should return null.
* The grant method is called for each principal returned from the
* LoginContext subject. If the AuthorityGranter wishes to grant
* authority, it should return the role name, such as ROLE_USER. If the
* AuthrityGranter does not wish to grant any authority it should return
* null.
*
* @param principal One of the principal from the LoginContext.getSubect().getPrincipals() method.
* @return The name of a role to grant, or null meaning no role should be granted.
* @param principal One of the principal from the
* LoginContext.getSubect().getPrincipals() method.
*
* @return The name of a role to grant, or null meaning no role should be
* granted.
*/
public String grant(Principal principal);
}

View File

@ -1,47 +1,78 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.Authentication;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* The JaasAuthenticationCallbackHandler is similar to the javax.security.auth.callback.CallbackHandler interface
* in that it defines a handle method. The JaasAuthenticationCallbackHandler is only asked to handle one Callback instance at at time
* rather than an array of all Callbacks, as the javax... CallbackHandler defines.
* <p/>
* Before a JaasAuthenticationCallbackHandler is asked to 'handle' any callbacks, it is first passed the Authentication
* object that the login attempt is for. NOTE: The Authentication object has not been 'authenticated' yet.
* The JaasAuthenticationCallbackHandler is similar to the
* javax.security.auth.callback.CallbackHandler interface in that it defines a
* handle method. The JaasAuthenticationCallbackHandler is only asked to
* handle one Callback instance at at time rather than an array of all
* Callbacks, as the javax... CallbackHandler defines.
*
* <p>
* Before a JaasAuthenticationCallbackHandler is asked to 'handle' any
* callbacks, it is first passed the Authentication object that the login
* attempt is for. NOTE: The Authentication object has not been
* 'authenticated' yet.
* </p>
* <br>
*
* @author Ray Krueger
* @version $Id$
*
* @see JaasNameCallbackHandler
* @see JaasPasswordCallbackHandler
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/CallbackHandler.html">CallbackHandler</a>
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/CallbackHandler.html">CallbackHandler</a>
*/
public interface JaasAuthenticationCallbackHandler {
//~ Methods ================================================================
/**
* Called by the JaasAuthenticationProvider before calling the handle method for any Callbacks.
* Called by the JaasAuthenticationProvider before calling the handle
* method for any Callbacks.
*
* @param auth The Authentication object currently being authenticated.
*/
void setAuthentication(Authentication auth);
/**
* Handle the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>.
* The handle method will be called for every callback instance sent from the LoginContext. Meaning that The handle
* method may be called multiple times for a given JaasAuthenticationCallbackHandler, after a single call
* to the {@link #setAuthentication(net.sf.acegisecurity.Authentication) setAuthentication} method.
* Handle the <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>.
* The handle method will be called for every callback instance sent from
* the LoginContext. Meaning that The handle method may be called multiple
* times for a given JaasAuthenticationCallbackHandler, after a single
* call to the {@link
* #setAuthentication(net.sf.acegisecurity.Authentication)
* setAuthentication} method.
*
* @param callback
*
* @throws IOException
* @throws UnsupportedCallbackException
*/
void handle(Callback callback) throws IOException, UnsupportedCallbackException;
void handle(Callback callback)
throws IOException, UnsupportedCallbackException;
}

View File

@ -1,3 +1,18 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.Authentication;
@ -8,76 +23,100 @@ import net.sf.acegisecurity.providers.AuthenticationProvider;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.jaas.event.JaasAuthenticationFailedEvent;
import net.sf.acegisecurity.providers.jaas.event.JaasAuthenticationSuccessEvent;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.security.Principal;
import java.security.Security;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.security.Principal;
import java.security.Security;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* An {@link AuthenticationProvider} implementation that retrieves user details
* from a JAAS login configuration.
* <p/>
*
* <p>
* This <code>AuthenticationProvider</code> is capable of validating {@link
* net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken} requests contain the correct username and password.
* net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken}
* requests contain the correct username and password.
* </p>
* This implementation is backed by a <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuide.html">JAAS</a> configuration.
* The loginConfig property must be set to a given JAAS configuration file. This setter accepts a Spring
* {@link org.springframework.core.io.Resource} instance. It should point to a JAAS configuration file
* containing an index matching the {@link #setLoginContextName(java.lang.String) loginContextName} property.
* <p/>
* For example:
* If this JaasAuthenticationProvider were configured in a Spring WebApplicationContext the xml to set the loginConfiguration
* could be as follows...
*
* <p>
* This implementation is backed by a <a
* href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuide.html">JAAS</a>
* configuration. The loginConfig property must be set to a given JAAS
* configuration file. This setter accepts a Spring {@link
* org.springframework.core.io.Resource} instance. It should point to a JAAS
* configuration file containing an index matching the {@link
* #setLoginContextName(java.lang.String) loginContextName} property.
* </p>
*
* <p>
* For example: If this JaasAuthenticationProvider were configured in a Spring
* WebApplicationContext the xml to set the loginConfiguration could be as
* follows...
* <pre>
* &lt;property name="loginConfig"&gt;
* &lt;value&gt;/WEB-INF/login.conf&lt;/value&gt;
* &lt;/property&gt;
* </pre>
* </p>
* <p/>
* <p/>
* The loginContextName should coincide with a given index in the loginConfig specifed.
* The loginConfig file used in the JUnit tests appears as the following...
*
* <p>
* The loginContextName should coincide with a given index in the loginConfig
* specifed. The loginConfig file used in the JUnit tests appears as the
* following...
* <pre>
* JAASTest {
* net.sf.acegisecurity.providers.jaas.TestLoginModule required;
* };
* </pre>
* Using the example login configuration above, the loginContextName property would be set as <i>JAASTest</i>...
* Using the example login configuration above, the loginContextName property
* would be set as <i>JAASTest</i>...
* <pre>
* &lt;property name="loginContextName"&gt;
* &lt;value&gt;JAASTest&lt;/value&gt;
* &lt;/property&gt;
* </pre>
* </p>
* <p/>
* <p/>
* When using JAAS login modules as the authentication source, sometimes the
* <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/login/LoginContext.html">LoginContext</a>
* will require <i>CallbackHandler</i>s.
* The JaasAuthenticationProvider uses an internal <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/CallbackHandler.html">CallbackHandler</a> to
* wrap the {@link JaasAuthenticationCallbackHandler}s configured in the ApplicationContext. When the LoginContext calls
* the internal CallbackHandler, control is passed to each {@link JaasAuthenticationCallbackHandler} for each Callback passed.
*
* <p>
* When using JAAS login modules as the authentication source, sometimes the <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/login/LoginContext.html">LoginContext</a>
* will require <i>CallbackHandler</i>s. The JaasAuthenticationProvider uses
* an internal <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/CallbackHandler.html">CallbackHandler</a>
* to wrap the {@link JaasAuthenticationCallbackHandler}s configured in the
* ApplicationContext. When the LoginContext calls the internal
* CallbackHandler, control is passed to each {@link
* JaasAuthenticationCallbackHandler} for each Callback passed.
* </p>
* <p/>
* {@link JaasAuthenticationCallbackHandler}s are passed to the JaasAuthenticationProvider through the
* {@link #setCallbackHandlers(net.sf.acegisecurity.providers.jaas.JaasAuthenticationCallbackHandler[]) callbackHandlers} property.
* <pre>
*
* <p>
{ * {@link JaasAuthenticationCallbackHandler}s are passed to the
* JaasAuthenticationProvider through the {@link
* #setCallbackHandlers(net.sf.acegisecurity.providers.jaas.JaasAuthenticationCallbackHandler[])
* callbackHandlers} property.
} * <pre>
* &lt;property name="callbackHandlers"&gt;
* &lt;list&gt;
* &lt;bean class="net.sf.acegisecurity.providers.jaas.TestCallbackHandler"/&gt;
@ -87,13 +126,20 @@ import java.util.Set;
* &lt;/property&gt;
* </pre>
* </p>
* <p/>
* <p/>
* After calling LoginContext.login(), the JaasAuthenticationProvider will retrieve the returned Principals from the Subject (LoginContext.getSubject().getPrincipals).
* Each returned principal is then passed to the configured {@link AuthorityGranter}s. An AuthorityGranter is a mapping between a returned Principal, and a role name.
* If an AuthorityGranter wishes to grant an Authorization a role, it returns that role name from it's {@link AuthorityGranter#grant(java.security.Principal)} method.
* The returned role will be applied to the Authorization object as a {@link GrantedAuthority}.
* <p/>
*
* <p>
* After calling LoginContext.login(), the JaasAuthenticationProvider will
* retrieve the returned Principals from the Subject
* (LoginContext.getSubject().getPrincipals). Each returned principal is then
* passed to the configured {@link AuthorityGranter}s. An AuthorityGranter is
* a mapping between a returned Principal, and a role name. If an
* AuthorityGranter wishes to grant an Authorization a role, it returns that
* role name from it's {@link AuthorityGranter#grant(java.security.Principal)}
* method. The returned role will be applied to the Authorization object as a
* {@link GrantedAuthority}.
* </p>
*
* <p>
* AuthorityGranters are configured in spring xml as follows...
* <pre>
* &lt;property name="authorityGranters"&gt;
@ -108,36 +154,151 @@ import java.util.Set;
* @author Ray Krueger
* @version $Id$
*/
public class JaasAuthenticationProvider implements AuthenticationProvider, InitializingBean, ApplicationContextAware {
public class JaasAuthenticationProvider implements AuthenticationProvider,
InitializingBean, ApplicationContextAware {
//~ Instance fields ========================================================
private ApplicationContext context;
private String loginContextName = "ACEGI";
private Resource loginConfig;
private JaasAuthenticationCallbackHandler[] callbackHandlers;
private String loginContextName = "ACEGI";
private AuthorityGranter[] authorityGranters;
private JaasAuthenticationCallbackHandler[] callbackHandlers;
//~ Methods ================================================================
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
/**
* Attempts to login the user given the Authentication objects principal and credential
* Set the AuthorityGranters that should be consulted for role names to be
* granted to the Authentication.
*
* @param authorityGranters AuthorityGranter array
*
* @see JaasAuthenticationProvider
*/
public void setAuthorityGranters(AuthorityGranter[] authorityGranters) {
this.authorityGranters = authorityGranters;
}
/**
* DOCUMENT ME!
*
* @return The AuthorityGranter array
*
* @see #setAuthorityGranters(net.sf.acegisecurity.providers.jaas.AuthorityGranter[])
*/
public AuthorityGranter[] getAuthorityGranters() {
return authorityGranters;
}
/**
* Set the JAASAuthentcationCallbackHandler array to handle callback
* objects generated by the LoginContext.login method.
*
* @param callbackHandlers Array of JAASAuthenticationCallbackHandlers
*/
public void setCallbackHandlers(
JaasAuthenticationCallbackHandler[] callbackHandlers) {
this.callbackHandlers = callbackHandlers;
}
/**
* DOCUMENT ME!
*
* @return the JAASAuthenticationCallbackHandlers.
*
* @see #setCallbackHandlers(net.sf.acegisecurity.providers.jaas.JaasAuthenticationCallbackHandler[])
*/
public JaasAuthenticationCallbackHandler[] getCallbackHandlers() {
return callbackHandlers;
}
/**
* Set the JAAS login configuration file.
*
* @param loginConfig <a
* href="http://www.springframework.org/docs/api/org/springframework/core/io/Resource.html">Spring
* Resource</a>
*
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuide.html">JAAS
* Reference</a>
*/
public void setLoginConfig(Resource loginConfig) {
this.loginConfig = loginConfig;
}
public Resource getLoginConfig() {
return loginConfig;
}
/**
* Set the loginContextName, this name is used as the index to the
* configuration specified in the loginConfig property.
*
* @param loginContextName
*/
public void setLoginContextName(String loginContextName) {
this.loginContextName = loginContextName;
}
public String getLoginContextName() {
return loginContextName;
}
public void afterPropertiesSet() throws Exception {
if (loginConfig == null) {
throw new ApplicationContextException("loginConfig must be set on "
+ getClass());
}
if (loginContextName == null) {
throw new ApplicationContextException(
"loginContextName must be set on " + getClass());
}
int n = 1;
while (Security.getProperty("login.config.url." + n) != null) {
n++;
}
Security.setProperty("login.config.url." + n,
loginConfig.getURL().toString());
}
/**
* Attempts to login the user given the Authentication objects principal
* and credential
*
* @param auth The Authentication object to be authenticated.
* @return The authenticated Authentication object, with it's grantedAuthorities set.
* @throws AuthenticationException This implementation does not handle 'locked' or 'disabled' accounts.
* This method only throws a AuthenticationServiceException, with the message of the LoginException that will be thrown,
* should the loginContext.login() method fail.
*
* @return The authenticated Authentication object, with it's
* grantedAuthorities set.
*
* @throws AuthenticationException This implementation does not handle
* 'locked' or 'disabled' accounts. This method only throws a
* AuthenticationServiceException, with the message of the
* LoginException that will be thrown, should the
* loginContext.login() method fail.
* @throws AuthenticationServiceException DOCUMENT ME!
*/
public Authentication authenticate(Authentication auth) throws AuthenticationException {
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
if (auth instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) auth;
try {
//Create the LoginContext object, and pass our InternallCallbackHandler
LoginContext lc = new LoginContext(loginContextName, new InternalCallbackHandler(auth));
LoginContext lc = new LoginContext(loginContextName,
new InternalCallbackHandler(auth));
//Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
lc.login();
//create a set to hold the authorities, and add any that have already been applied.
Set authorities = new HashSet();
@ -147,34 +308,41 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Initi
//get the subject principals and pass them to each of the AuthorityGranters
Set principals = lc.getSubject().getPrincipals();
for (Iterator iterator = principals.iterator(); iterator.hasNext();) {
for (Iterator iterator = principals.iterator();
iterator.hasNext();) {
Principal principal = (Principal) iterator.next();
for (int i = 0; i < authorityGranters.length; i++) {
AuthorityGranter granter = authorityGranters[i];
String role = granter.grant(principal);
//If the granter doesn't wish to grant any authority, it should return null.
if (role != null) {
authorities.add(new JaasGrantedAuthority(role, principal));
authorities.add(new JaasGrantedAuthority(role,
principal));
}
}
}
//Convert the authorities set back to an array and apply it to the token.
token.setAuthorities((GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]));
token.setAuthorities((GrantedAuthority[]) authorities.toArray(
new GrantedAuthority[authorities.size()]));
//Publish the success event
context.publishEvent(new JaasAuthenticationSuccessEvent(token));
//we're done, return the token.
return token;
} catch (LoginException e) {
context.publishEvent(new JaasAuthenticationFailedEvent(auth, e));
//We have no way of knowing what caused the exception, so we cannot throw BadCredentialsException, DisabledException, or LockedException.
//So we'll just throw an AuthenticationServiceException
throw new AuthenticationServiceException(e.toString());
}
}
return null;
}
@ -182,104 +350,24 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Initi
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
public String getLoginContextName() {
return loginContextName;
}
/**
* Set the loginContextName, this name is used as the index to the configuration specified in the loginConfig property.
*
* @param loginContextName
*/
public void setLoginContextName(String loginContextName) {
this.loginContextName = loginContextName;
}
public Resource getLoginConfig() {
return loginConfig;
}
/**
* Set the JAAS login configuration file.
*
* @param loginConfig <a href="http://www.springframework.org/docs/api/org/springframework/core/io/Resource.html">Spring Resource</a>
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASRefGuide.html">JAAS Reference</a>
*/
public void setLoginConfig(Resource loginConfig) {
this.loginConfig = loginConfig;
}
public void afterPropertiesSet() throws Exception {
if (loginConfig == null)
throw new ApplicationContextException("loginConfig must be set on " + getClass());
if (loginContextName == null)
throw new ApplicationContextException("loginContextName must be set on " + getClass());
int n = 1;
while (Security.getProperty("login.config.url." + n) != null) n++;
Security.setProperty("login.config.url." + n, loginConfig.getURL().toString());
}
/**
* @return the JAASAuthenticationCallbackHandlers.
* @see #setCallbackHandlers(net.sf.acegisecurity.providers.jaas.JaasAuthenticationCallbackHandler[])
*/
public JaasAuthenticationCallbackHandler[] getCallbackHandlers() {
return callbackHandlers;
}
/**
* Set the JAASAuthentcationCallbackHandler array to handle callback objects generated by the
* LoginContext.login method.
*
* @param callbackHandlers Array of JAASAuthenticationCallbackHandlers
*/
public void setCallbackHandlers(JaasAuthenticationCallbackHandler[] callbackHandlers) {
this.callbackHandlers = callbackHandlers;
}
/**
* @return The AuthorityGranter array
* @see #setAuthorityGranters(net.sf.acegisecurity.providers.jaas.AuthorityGranter[])
*/
public AuthorityGranter[] getAuthorityGranters() {
return authorityGranters;
}
/**
* Set the AuthorityGranters that should be consulted for role names to be granted to the Authentication.
*
* @param authorityGranters AuthorityGranter array
* @see JaasAuthenticationProvider
*/
public void setAuthorityGranters(AuthorityGranter[] authorityGranters) {
this.authorityGranters = authorityGranters;
}
//~ Inner Classes ==========================================================
/**
* Wrapper class for JAASAuthenticationCallbackHandlers
*/
private class InternalCallbackHandler implements CallbackHandler {
private Authentication authentication;
public InternalCallbackHandler(Authentication authentication) {
this.authentication = authentication;
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbackHandlers.length; i++) {
JaasAuthenticationCallbackHandler handler = callbackHandlers[i];
handler.setAuthentication(authentication);
for (int j = 0; j < callbacks.length; j++) {
Callback callback = callbacks[j];
handler.handle(callback);

View File

@ -1,26 +1,48 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import java.security.Principal;
/**
* Extends GrantedAuthorityImpl to hold the principal that an AuthorityGranter justified as a reason to grant this Authority.
* <br>
* Extends GrantedAuthorityImpl to hold the principal that an AuthorityGranter
* justified as a reason to grant this Authority. <br>
*
* @author Ray Krueger
* @version $Id$
*
* @see AuthorityGranter
*/
public class JaasGrantedAuthority extends GrantedAuthorityImpl {
//~ Instance fields ========================================================
private Principal principal;
//~ Constructors ===========================================================
public JaasGrantedAuthority(String role, Principal principal) {
super(role);
this.principal = principal;
}
//~ Methods ================================================================
public Principal getPrincipal() {
return principal;
}

View File

@ -1,40 +1,70 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.Authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
/**
* The most basic Callbacks to be handled when using a LoginContext from JAAS, are the NameCallback and PasswordCallback.
* The acegi security framework provides the JaasNameCallbackHandler specifically tailored to handling the NameCallback.
* <br>
* The most basic Callbacks to be handled when using a LoginContext from JAAS,
* are the NameCallback and PasswordCallback. The acegi security framework
* provides the JaasNameCallbackHandler specifically tailored to handling the
* NameCallback. <br>
*
* @author Ray Krueger
* @version $Id$
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/NameCallback.html">NameCallback</a>
*
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/NameCallback.html">NameCallback</a>
*/
public class JaasNameCallbackHandler implements JaasAuthenticationCallbackHandler {
public class JaasNameCallbackHandler
implements JaasAuthenticationCallbackHandler {
//~ Instance fields ========================================================
private Authentication authentication;
//~ Methods ================================================================
public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
/**
* If the callback passed to the 'handle' method is an instance of NameCallback, the JaasNameCallbackHandler will call,
* callback.setName(authentication.getPrincipal().toString()). Where 'authentication' is the {@link Authentication}
* object used in the {@link #setAuthentication(net.sf.acegisecurity.Authentication) setAuthentication} method.
* If the callback passed to the 'handle' method is an instance of
* NameCallback, the JaasNameCallbackHandler will call,
* callback.setName(authentication.getPrincipal().toString()). Where
* 'authentication' is the {@link Authentication} object used in the
* {@link #setAuthentication(net.sf.acegisecurity.Authentication)
* setAuthentication} method.
*
* @param callback
*
* @throws IOException
* @throws UnsupportedCallbackException
*/
public void handle(Callback callback) throws IOException, UnsupportedCallbackException {
public void handle(Callback callback)
throws IOException, UnsupportedCallbackException {
if (callback instanceof NameCallback) {
NameCallback ncb = (NameCallback) callback;
ncb.setName(authentication.getPrincipal().toString());

View File

@ -1,40 +1,71 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.Authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
/**
* The most basic Callbacks to be handled when using a LoginContext from JAAS, are the NameCallback and PasswordCallback.
* The acegi security framework provides the JaasPasswordCallbackHandler specifically tailored to handling the PasswordCallback.
* <br>
* The most basic Callbacks to be handled when using a LoginContext from JAAS,
* are the NameCallback and PasswordCallback. The acegi security framework
* provides the JaasPasswordCallbackHandler specifically tailored to handling
* the PasswordCallback. <br>
*
* @author Ray Krueger
* @version $Id$
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/PasswordCallback.html">PasswordCallback</a>
*
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/Callback.html">Callback</a>
* @see <a
* href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/callback/PasswordCallback.html">PasswordCallback</a>
*/
public class JaasPasswordCallbackHandler implements JaasAuthenticationCallbackHandler {
public class JaasPasswordCallbackHandler
implements JaasAuthenticationCallbackHandler {
//~ Instance fields ========================================================
private Authentication auth;
//~ Methods ================================================================
public void setAuthentication(Authentication auth) {
this.auth = auth;
}
/**
* If the callback passed to the 'handle' method is an instance of PasswordCallback, the JaasPasswordCallbackHandler will call,
* callback.setPassword(authentication.getCredentials().toString()). Where 'authentication' is the {@link Authentication}
* object used in the {@link JaasAuthenticationCallbackHandler#setAuthentication(net.sf.acegisecurity.Authentication) setAuthentication} method.
* If the callback passed to the 'handle' method is an instance of
* PasswordCallback, the JaasPasswordCallbackHandler will call,
* callback.setPassword(authentication.getCredentials().toString()). Where
* 'authentication' is the {@link Authentication} object used in the
* {@link
* JaasAuthenticationCallbackHandler#setAuthentication(net.sf.acegisecurity.Authentication)
* setAuthentication} method.
*
* @param callback
*
* @throws IOException
* @throws UnsupportedCallbackException
*/
public void handle(Callback callback) throws IOException, UnsupportedCallbackException {
public void handle(Callback callback)
throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callback;
pc.setPassword(auth.getCredentials().toString().toCharArray());

View File

@ -1,25 +1,46 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas.event;
import net.sf.acegisecurity.Authentication;
/**
* Fired when LoginContext.login throws a LoginException, or if any other exception is thrown during that time.
* <br>
* Fired when LoginContext.login throws a LoginException, or if any other
* exception is thrown during that time.
*
* @author Ray Krueger
* @version $Id$
*/
public class JaasAuthenticationFailedEvent extends JaasAuthenticationEvent {
//~ Instance fields ========================================================
private Exception exception;
public JaasAuthenticationFailedEvent(Authentication auth, Exception exception) {
//~ Constructors ===========================================================
public JaasAuthenticationFailedEvent(Authentication auth,
Exception exception) {
super(auth);
this.exception = exception;
}
//~ Methods ================================================================
public Exception getException() {
return exception;
}
}

View File

@ -1,19 +1,36 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas.event;
import net.sf.acegisecurity.Authentication;
/**
* Fired by the {@link net.sf.acegisecurity.providers.jaas.JaasAuthenticationProvider JaasAuthenticationProvider} after
* successfully logging the user into the LoginContext, handling all callbacks, and calling all AuthorityGranters.
* <br>
* Fired by the {@link
* net.sf.acegisecurity.providers.jaas.JaasAuthenticationProvider
* JaasAuthenticationProvider} after successfully logging the user into the
* LoginContext, handling all callbacks, and calling all AuthorityGranters.
*
* @author Ray Krueger
* @version $Id$
*/
public class JaasAuthenticationSuccessEvent extends JaasAuthenticationEvent {
//~ Constructors ===========================================================
public JaasAuthenticationSuccessEvent(Authentication auth) {
super(auth);
}
}

View File

@ -1,50 +1,87 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import junit.framework.TestCase;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.GrantedAuthority;
import net.sf.acegisecurity.GrantedAuthorityImpl;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Arrays;
import java.util.List;
/**
* Insert comments here...
* <br>
* DOCUMENT ME!
*
* @author Ray Krueger
* @version $Id$
*/
public class JaasAuthenticationProviderTests extends TestCase {
//~ Instance fields ========================================================
private JaasAuthenticationProvider jaasProvider;
private ApplicationContext context;
private JaasAuthenticationProvider jaasProvider;
private JaasEventCheck eventCheck;
protected void setUp() throws Exception {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
context = new ClassPathXmlApplicationContext(resName);
eventCheck = (JaasEventCheck) context.getBean("eventCheck");
jaasProvider = (JaasAuthenticationProvider) context.getBean("jaasAuthenticationProvider");
//~ Methods ================================================================
public void testBadPassword() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken(
"user", "asdf"));
fail("LoginException should have been thrown for the bad password");
} catch (AuthenticationException e) {}
assertNotNull("Failure event not fired", eventCheck.failedEvent);
assertNotNull("Failure event exception was null",
eventCheck.failedEvent.getException());
assertNull("Success event was fired", eventCheck.successEvent);
}
public void testBadUser() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken(
"asdf", "password"));
fail("LoginException should have been thrown for the bad user");
} catch (AuthenticationException e) {}
assertNotNull("Failure event not fired", eventCheck.failedEvent);
assertNotNull("Failure event exception was null",
eventCheck.failedEvent.getException());
assertNull("Success event was fired", eventCheck.successEvent);
}
public void testFull() throws Exception {
GrantedAuthorityImpl role1 = new GrantedAuthorityImpl("ROLE_1");
GrantedAuthorityImpl role2 = new GrantedAuthorityImpl("ROLE_2");
GrantedAuthority[] defaultAuths = new GrantedAuthority[]{
role1,
role2,
};
GrantedAuthority[] defaultAuths = new GrantedAuthority[] {role1, role2,};
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", defaultAuths);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user",
"password", defaultAuths);
assertTrue(jaasProvider.supports(UsernamePasswordAuthenticationToken.class));
assertTrue(jaasProvider.supports(
UsernamePasswordAuthenticationToken.class));
Authentication auth = jaasProvider.authenticate(token);
@ -56,51 +93,41 @@ public class JaasAuthenticationProviderTests extends TestCase {
List list = Arrays.asList(auth.getAuthorities());
assertTrue("GrantedAuthorities does not contain ROLE_TEST",
list.contains(new GrantedAuthorityImpl("ROLE_TEST")));
list.contains(new GrantedAuthorityImpl("ROLE_TEST")));
assertTrue("GrantedAuthorities does not contain ROLE_1", list.contains(role1));
assertTrue("GrantedAuthorities does not contain ROLE_1",
list.contains(role1));
assertTrue("GrantedAuthorities does not contain ROLE_2", list.contains(role2));
assertTrue("GrantedAuthorities does not contain ROLE_2",
list.contains(role2));
boolean foundit = false;
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
if (obj instanceof JaasGrantedAuthority) {
JaasGrantedAuthority grant = (JaasGrantedAuthority) obj;
assertNotNull("Principal was null on JaasGrantedAuthority", grant.getPrincipal());
assertNotNull("Principal was null on JaasGrantedAuthority",
grant.getPrincipal());
foundit = true;
}
}
assertTrue("Could not find a JaasGrantedAuthority", foundit);
assertNotNull("Success event not fired", eventCheck.successEvent);
assertEquals("Auth objects are not equal", auth, eventCheck.successEvent.getAuthentication());
assertEquals("Auth objects are not equal", auth,
eventCheck.successEvent.getAuthentication());
assertNull("Failure event was fired", eventCheck.failedEvent);
}
public void testBadUser() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
} catch (AuthenticationException e) {
}
assertNotNull("Failure event not fired", eventCheck.failedEvent);
assertNotNull("Failure event exception was null", eventCheck.failedEvent.getException());
assertNull("Success event was fired", eventCheck.successEvent);
protected void setUp() throws Exception {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
context = new ClassPathXmlApplicationContext(resName);
eventCheck = (JaasEventCheck) context.getBean("eventCheck");
jaasProvider = (JaasAuthenticationProvider) context.getBean(
"jaasAuthenticationProvider");
}
public void testBadPassword() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
fail("LoginException should have been thrown for the bad password");
} catch (AuthenticationException e) {
}
assertNotNull("Failure event not fired", eventCheck.failedEvent);
assertNotNull("Failure event exception was null", eventCheck.failedEvent.getException());
assertNull("Success event was fired", eventCheck.successEvent);
}
}

View File

@ -1,6 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!-- $Id$ -->
<beans>
<bean id="eventCheck" class="net.sf.acegisecurity.providers.jaas.JaasEventCheck"/>

View File

@ -1,25 +1,48 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.providers.jaas.event.JaasAuthenticationFailedEvent;
import net.sf.acegisecurity.providers.jaas.event.JaasAuthenticationSuccessEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
* DOCUMENT ME!
*
* @author Ray Krueger
* @version $Id$
*/
public class JaasEventCheck implements ApplicationListener {
//~ Instance fields ========================================================
JaasAuthenticationFailedEvent failedEvent;
JaasAuthenticationSuccessEvent successEvent;
//~ Methods ================================================================
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof JaasAuthenticationFailedEvent)
if (event instanceof JaasAuthenticationFailedEvent) {
failedEvent = (JaasAuthenticationFailedEvent) event;
}
if (event instanceof JaasAuthenticationSuccessEvent)
if (event instanceof JaasAuthenticationSuccessEvent) {
successEvent = (JaasAuthenticationSuccessEvent) event;
}
}
}

View File

@ -1,19 +1,39 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import java.security.Principal;
/**
* Insert comments here...
* <br>
* DOCUMENT ME!
*
* @author Ray Krueger
* @version $Id$
*/
public class TestAuthorityGranter implements AuthorityGranter {
//~ Methods ================================================================
public String grant(Principal principal) {
String role = null;
if (principal.getName().equals("TEST_PRINCIPAL"))
if (principal.getName().equals("TEST_PRINCIPAL")) {
role = "ROLE_TEST";
}
return role;
}
}

View File

@ -1,28 +1,48 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import net.sf.acegisecurity.Authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.TextInputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
/**
* Insert comments here...
* <br>
* DOCUMENT ME!
*
* @author Ray Krueger
* @version $Id$
*/
public class TestCallbackHandler implements JaasAuthenticationCallbackHandler {
//~ Instance fields ========================================================
Authentication auth;
//~ Methods ================================================================
public void setAuthentication(Authentication auth) {
this.auth = auth;
}
public void handle(Callback callback) throws IOException, UnsupportedCallbackException {
public void handle(Callback callback)
throws IOException, UnsupportedCallbackException {
if (callback instanceof TextInputCallback) {
TextInputCallback tic = (TextInputCallback) callback;
tic.setText(auth.getPrincipal().toString());

View File

@ -1,24 +1,44 @@
/* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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 net.sf.acegisecurity.providers.jaas;
import java.security.Principal;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import java.security.Principal;
import java.util.Map;
/**
* Insert comments here...
* <br>
* DOCUMENT ME!
*
* @author Ray Krueger
* @version $Id$
*/
public class TestLoginModule implements LoginModule {
//~ Instance fields ========================================================
private Subject subject;
private String user;
private String password;
private String user;
private Subject subject;
//~ Methods ================================================================
public boolean abort() throws LoginException {
return true;
@ -28,8 +48,26 @@ public class TestLoginModule implements LoginModule {
return true;
}
public boolean login() throws LoginException {
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options) {
this.subject = subject;
try {
TextInputCallback textCallback = new TextInputCallback("prompt");
NameCallback nameCallback = new NameCallback("prompt");
PasswordCallback passwordCallback = new PasswordCallback("prompt",
false);
callbackHandler.handle(new Callback[] {textCallback, nameCallback, passwordCallback});
password = new String(passwordCallback.getPassword());
user = nameCallback.getName();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public boolean login() throws LoginException {
if (!user.equals("user")) {
throw new LoginException("Bad User");
}
@ -39,38 +77,21 @@ public class TestLoginModule implements LoginModule {
}
subject.getPrincipals().add(new Principal() {
public String getName() {
return "TEST_PRINCIPAL";
}
});
public String getName() {
return "TEST_PRINCIPAL";
}
});
subject.getPrincipals().add(new Principal() {
public String getName() {
return "NULL_PRINCIPAL";
}
});
public String getName() {
return "NULL_PRINCIPAL";
}
});
return true;
}
public boolean logout() throws LoginException {
return true;
}
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
this.subject = subject;
try {
TextInputCallback textCallback = new TextInputCallback("prompt");
NameCallback nameCallback = new NameCallback("prompt");
PasswordCallback passwordCallback = new PasswordCallback("prompt", false);
callbackHandler.handle(new Callback[]{textCallback, nameCallback, passwordCallback});
password = new String(passwordCallback.getPassword());
user = nameCallback.getName();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}