Jivespace Community Blog

4 Posts tagged with the acegi tag

This post is the sixth in a series of blog posts about customizing for Clearspace 2.x. The previous posts covered:

  1. Customizations in Clearspace 2.x

  2. Upgrading Themes and FTL Files.

  3. Widgets in Clearspace 2.x

  4. Macros for Clearspace 2.0

  5. Web Services

 

As in the Clearspace 1.x series, in Clearspace 2.x versions you can write your own components to manage user information and provide custom authentication.

 

Upgrading a User Data Provider

In version 1 you created a custom user provider by implementing the com.jivesoftware.spi.user.UserProvider interface to interact with your user data source and implementing the com.jivesoftware.base.User interface to represent a user. In version 2, you implement UserProvider and User, but the interfaces have changed a bit. The version 2 model is more streamlined, removing the need to implement the lifecycle methods that the SPI framework requires. Here's a summary of the changes:

 

  • Because you no longer implement the ServiceProvider interface, you don't implement support for its life cycle methods. Clearspace handles provider life cycle through Spring.

  • The com.jivesoftware.base.User interface is read-only (lacks setters) in version 2. Your implementation now provides the interface and logic for updating user information and returning it to Clearspace.

  • The User.authenticate method has been removed. Use an authentication provider to authenticate a user.

  • The User interface includes several new methods for retrieving information about the user.

  • You now connect your custom provider to Clearspace using Spring conventions rather than by setting a Jive property.

 

Here's a high level view of the upgrade steps you'll need to consider.

 

  • Implement the User interface to support whatever setters it needs. You'll also want to implement the is*Supported methods that indicate to Clearspace which user data is supported for setting.

  • For UserProvider methods in which your code receives and returns a User instance, you'll need to rewrite a bit to return your own User implementation. In version 1 the UserProvider instance received a UserTemplate with setters. Because you can no longer simply call setters on the User instance you receive (it might not have any), you'll instead copy data from the received instance into an instance of your own implementation and return your own (such as by constructing your instance from the User your code receives). The methods you'll need to change include create(User) and getUser(User).

  • Implement UserProvider.supportsUpdate to return true if your data store supports creating or updating users from Clearspace. If you return false from this method, be sure to also throw an UnsupportedOperationException from the create and update methods.

 

Upgrading an Authentication Provider

Authentication is substantially changed in version 2. For example, you no longer need to pass an AuthToken instance with method calls. Every request is guaranteed to have an authentication context. In version 2, Clearspace uses Acegi security, which is designed to fit well with the Spring framework. If you're implementing your own authentication provider, your components are based on Acegi; in some cases you might be able to use the classes included with Acegi, such as Authentication implementations.

 

Be sure to read the Acegi documentation, which includes information you'll find useful.

 

What Your Implementation Should Include

 

  • Implement org.acegisecurity.AuthenticationProvider to provide the service that authenticates users for Clearspace. This interface includes two methods: authenticate(Authentication) and supports(Class). Your supports method is called by Clearspace to determine whether the Authentication approach is supported by your provider. You should return true if the Authentication class it receives is one your authenticate method supports.

public boolean supports(Class authentication) {
    return authentication == UsernamePasswordAuthenticationToken.class;
}


The authenticate method receives an Authentication instance containing information identifying the user. Your implementation knows how to authenticate the user and should return an Authentication instance that indicates whether the user is authenticated. Here's a simple authenticate method example in which the checkAuth method (not shown) communicates with the data source and returns true if the user is authentic:

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String username = String.valueOf(auth.getPrincipal());
    String password = String.valueOf(auth.getCredentials());
    if(!checkAuth(username, password)){
        throw new BadCredentialsException("Username:" + username + " was not authenticated");
    }
    return new UsernamePasswordAuthenticationToken(username, password, new GrantedAuthority[]{});
}


  • Implement org.acegisecurity.Authentication to contain details of the authentication request (you can also use an existing class that implements Authentication ). An Authentication class represents the user in the context of a particular authentication approach -- such as basic authentication, LDAP, X.509 certificate, and so on. An instance includes details such as principal (something identifying the user, such as a username) and credentials (such as a password). Your isAuthenticated method should return true if the user is authentic.
     
    The Authentication class includes a getAuthorities method that is not currently supported by Clearspace. Your implementation should return an empty array:

public GrantedAuthority[] getAuthorities() {
    return new GrantedAuthority[0];
}]


  • Connect your authentication provider to Clearspace by adding a Spring configuration XML file to the jiveHome/etc directory.

 

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /upgrade/**=httpSessionContextIntegrationFilter, upgradeAuthenticationFilter, upgradeExceptionTranslationFilter
    /post-upgrade/**=httpSessionContextIntegrationFilter, postUpgradeAuthenticationFilter, postUpgradeExceptionTranslationFilter
    /admin/**=httpSessionContextIntegrationFilter, adminAuthenticationFilter, adminExceptionTranslationFilter
    /rpc/xmlrpc=httpSessionContextIntegrationFilter, basicAuthenticationFilter, wsExceptionTranslator
    /rpc/rest/**=httpSessionContextIntegrationFilter, basicAuthenticationFilter, wsExceptionTranslator
    /**=httpSessionContextIntegrationFilter, formAuthenticationFilter, rememberMeProcessingFilter, anonymousProcessingFilter, exceptionTranslationFilter
    .... add your implementation ...
</value>
</property>
</bean>

The following stanza lists the authentication providers that Clearspace tries to use. When trying to authenticate a user, Clearspace tries with each in turn, top to bottom. Each of the beans listed here

 

<!-- A list of authentication sources that will be consulted when attempting to
    authenticate the user. Each is consulted in order until a provider does
    *not* return null. This chains multiple providers together
    until one decides it can handle the user. -->
<bean id="authenticationManager" 
    class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
    <list>
        <ref bean="jiveLdapAuthenticationProvider"></ref>
        <ref bean="jiveLegacyAuthenticationProvider"></ref>
        <ref bean="daoAuthenticationProvider" ></ref>
        <ref bean="rememberMeAuthenticationProvider"></ref>
        <ref bean="anonymousAuthenticationProvider"></ref>
    </list>
    </property>
</bean>

 

The information above along with more details can be found in the Upgrading Extensions to 2.0 documentation.

 

If you are working on authentication for SSO, you might also be interested in reading Fred's post about Quick SSO on Clearspace 2.0

 

 

1 Comments Permalink

Quick SSO on Clearspace 2.0

Posted by brockf Jul 1, 2008

Below is a small filter that I co-authored recently to integrate with Oracle Access Manager (formerly called Oblix). With the release of CS 2.0 we have totally revamped the authentication process and it is now built on spring-security (formerly acegi). Doing this makes it super easy for most of the typical SSO use-cases to be implemented in a reasonable amount of time.

 

Here was the use case:

1. User Makes initiial request and is not authenticated yet.

2. Webgate routes user to the corporate login page

3. User supplies auth credentials

4. Webgate authenticates the user

5. Webgate sets an Authentication Cookie that identifies this user to Webgate

6. Webgate adds custom HTTP Headers to a new request to the originally requested resource, in this case clearspace.

7. Clearspace ACEGI Filter chain executes for /*** path, this is where I inserted the OblixSSOFilter right before the form authentication.

8. The Filter executes, grabs the HTTP Header "jwt-dn" and extracts the users DN (the user name).

9. The Filter retrieves the User and creates an Authentication and allows the rest of the filters to execute.

 

The User is now authenticated. The Default authoprovider ultimatly loads the Users permission etc downstream using the default AuthProvider.

 

Here is the code for the filter. The filter is pretty straight forward. It looks at the incoming HttpServletRequest and attempts to retrieve a HTTP Header that was sent along from the webgate authentication form previously visited by the user, as stated above, in this particular scenario I was able to assume authentication would always be done prior to accessing clearspace.

 

 

 package com.jivesoftware.clearspace.sso.oblix;
 
 
import com.jivesoftware.community.aaa.AnonymousAuthentication;
import com.jivesoftware.community.aaa.JiveUserAuthentication;
import com.jivesoftware.base.*;
 
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;
 
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.Authentication;
import org.apache.commons.lang.StringUtils;
 
/**
 * Created by IntelliJ IDEA.
 * User: fred
 * Date: Jun 11, 2008
 * Time: 12:36:14 PM
 */
public class OblixSSOFilter implements Filter {
 
 
    private static String OAMHEADER = "jwt-unique";
    private static String HEADER_NAME = "jwt-dn";
    private UserManager userManager;
    //possible to use system properties to enable and change the header, for
    //now just keep it simple.
    private String oamHeaderName = HEADER_NAME;
    private boolean enabled = true;
 
    public OblixSSOFilter(){
        super();
    }
 
  
 
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Authentication authentication;
 
        if(!enabled){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            try {
                Log.debug("executing oblix filter");
                HttpServletRequest request = (HttpServletRequest)servletRequest;
                String oamHeader = request.getHeader(getOamHeaderName());
                if(oamHeader != null){
                    Log.debug("got OAM header: " + oamHeader);
                    String userDN = extractUserDN(oamHeader);
 
                    User authenticationTarget = null;
                    try{
                        authenticationTarget = userManager.getUser(StringUtils.chomp(userDN));
                    }catch(UserNotFoundException e){
                        Log.error("no user found with username: " + userDN);
                    }
                    //Found an a
                    authentication = new JiveUserAuthentication(authenticationTarget);
                    authentication.setAuthenticated(true);
                }else{
                    Log.debug("no OAM Header");
                    authentication = new AnonymousAuthentication();
                }
                    SecurityContextHolder.getContext().setAuthentication(authentication);
               }catch (Exception e) {
                    Log.error("Exception occured while trying to authenticate OAM response: " + e.getMessage());
               }
           
               
          filterChain.doFilter(servletRequest,servletResponse);
       }
    }
 
 
    private String extractUserDN(String header){
        String userName = null;
        String[] elements = StringUtils.split(header,',');
        for(String element: elements){
            Log.debug("processing header: " + element);
            if(element.startsWith(OAMHEADER)){
                String[] uniqueID = StringUtils.split(element,'=');
                userName = uniqueID[1];
            }
        }
        return(userName);
    }
 
    public void destroy(){
    }
 
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
 
    public AuthenticationProvider getAuthenticationProvider() {
        return authenticationProvider;
    }
 
    public void setAuthenticationProvider(AuthenticationProvider authenticationProvider) {
        this.authenticationProvider = authenticationProvider;
    }
 
    public String getOamHeaderName() {
        return oamHeaderName;
    }
 
    public void setOamHeaderName(String oamHeaderName) {
        this.oamHeaderName = oamHeaderName;
    }
 
    public boolean isEnabled() {
        return enabled;
    }
 
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

 

I simply created a jar containing this one class that I deployed to the WEB-INF\lib directory of a expanded clearspace war file. You can use any IDE or VI and Ant to create the jar, nothing special about it or clearspace specific.

 

After I had the jar. I needed to tell clearspace about the filter. Since 2.0 there is a back door that can be utilized to override the default implementation of clearspace managers,DAOs and other spring managed beans, this back door is your jiveHome\etc directoy. Within the jiveHome\etc directory you can copy and modify the various spring context files packaged in the clearspace.jar file found in \WEB\lib. This is done by extracting the appropriate spring context file from the clearspace.jar file found in WEB-INF\lib, make your edits to it and copy it into \jiveHome\etc. In my case the authentication filter stack is configured in spring-securityContext.xml so I extracted that and made the changes listed below:

 


<!-- NOTICE THE ADDITION OF oblixSS0Filter -->
<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
        <property name="filterInvocationDefinitionSource">
            <value>
                CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                PATTERN_TYPE_APACHE_ANT
                /upgrade/**=httpSessionContextIntegrationFilter, upgradeAuthenticationFilter, upgradeExceptionTranslationFilter,jiveAuthenticationTranslationFilter
                /post-upgrade/**=httpSessionContextIntegrationFilter, postUpgradeAuthenticationFilter, postUpgradeExceptionTranslationFilter,jiveAuthenticationTranslationFilter
                /admin/**=httpSessionContextIntegrationFilter, adminAuthenticationFilter, adminExceptionTranslationFilter,jiveAuthenticationTranslationFilter
                /rpc/xmlrpc=wsRequireSSLFilter, httpSessionContextIntegrationFilter, basicAuthenticationFilter, wsExceptionTranslator, jiveAuthenticationTranslationFilter, wsAccessTypeCheckFilter
                /rpc/rest/**=wsRequireSSLFilter, httpSessionContextIntegrationFilter, basicAuthenticationFilter, wsExceptionTranslator, jiveAuthenticationTranslationFilter, wsAccessTypeCheckFilter
                /rpc/soap/**=wsRequireSSLFilter, httpSessionContextIntegrationFilter, jiveAuthenticationTranslationFilter 
                /**=httpSessionContextIntegrationFilter, oblixSSoFilter formAuthenticationFilter, rememberMeProcessingFilter, feedBasicAuthenticationFilter, jiveAuthenticationTranslationFilter
            </value>
        </property>
    </bean>

<!-- DECLARE THE NEW FILTER -->
<bean id="oblixSSoFilter" class="com.jivesoftware.clearspace.sso.oblix.OblixSSOFilter">
        <property name="userManager" ref="userManager" ></property>
    </bean>

 

 

As you can see the stack is configured to protect various resources within clearspace, you can add to this stack as required for your particular case, in my case it was simply a matter of declaring my filter, this allows spring to handle the creation of the object and changing the filter stack for the root path of the application to ensure the oblixSSOFilter fired off prior to formAuthentication. If the oblix filter is able to vouch for the user making the request (via the headers) the filter sets the Authentication on the SecurityContext and life moves forward with an authenticated user, if not, I allow it to fall to the next filter in the stack and the process repeats, with this new framework in place it makes it easy to support multiple authentication sources while still staying on the peripheral edges of the product which will help when it comes time to upgrade.

 

 

After you have made the changes, restart your clearspace instance and you should be up and running with your new filter.

 

Enjoy!.  

 

 

 

 

 

 

 

 

 

 

11 Comments Permalink

Clearspace 2.0 made several improvements to the internal security mechanisms within the product that serve to streamline and standardize the way authentication, authorization and auditing occur within the application. Following on Dolan's blog about Spring in Clearspace 2.0, this post will cover the Acegi-related changes for 2.0 security.

 

Motivation

There were several motivations for using Acegi Security in Clearspace 2.0:

  • Reuse of standard, community reviewed code - At the time of writing, Acegi is planned to be incorporated into Spring proper in the near future. Particularly with security-related code, community review is essential to producing a more robust end result.

  • Removal of unnecessary, Jive-specific code - There really wasn't a need for us to manage our own authentication framework, authorization framework, X509 handling, etc. when Acegi has already made available a solid implementation. Additionally, Acegi gives us out of the box AuthenticationProvider and Filter implementations for things that previously we had to roll from scratch such as SiteMinder integration or X509 authentication. Acegi's implementations will still require some customization, largely due to the way we perform authorization, but the jive-managed code can be substantially reduced.

  • Community - As with Spring, Acegi has a healthy community that we can leverage, both through shared code as well as by contributing back to the project.

  • Flexibility - Acegi is well written and tends to give us extension points where we need them. For example, we needed to support existing LDAP configurations from Clearspace 1.x installations. This required us to inject custom LDAP search properties into the Acegi BindAuthenticator which was easily done through the setUserSearch method on the authenticator.

  • Leverage Existing Enterprise Competencies - Acegi and Spring are fairly well known in Java enterprise development. Existing skill sets around Acegi will translate to SSO implementations with Clearspace 2.0 as opposed to the 1.x model which required a customer's developers to learn an entirely new security model.

 

Implementation

Authentication

The Clearspace 2.0 authentication model follows standard Acegi authentication, defining a Spring-managed FilterChainProxy bean in web.xml which then delegates to URL-mapped filter chains. These chains manage various security-related concerns including Session expiration, authentication cookie management, password encoding, user profile loading and federated identity features of Clearspace. One notable change is the move to a stronger password hash using a SHA-256 hash of a salted password. Additionally, the amount of Jive-specific LDAP code has been dramatically reduced instead delegating to Acegi's LDAP lookup and bind implementation.

 

Authorization

Clearspace 2.0 authorization has not changed substantially from 1.x with the exception that contextual information about a user is now accessed via the Acegi SecurityContext rather than explicitly passed through the application as AuthToken objects. This change focused the APIs on business concerns and moved security concerns to more of a cross-cutting realm, a change we're leveraging in 2.1 to make authorization driven by annotation rather than proxied objects. The hope for 2.1 is that this will greatly reduce the amount of authoirzation code while improving security.

 

Auditing

Acegi fundamentally feeds into the new auditing features of Clearspace 2.0. Based on contextual authentication information accessed by Acegi's SecurityContext, the auditing functionality logs operations performed by the effective user performing an action in the system.

 

Customization

 

Customization of authentication and authorization have several extension mechanisms in Clearspace 2.0 and the required APIs have been simplified. The older AuthFactory class has been removed and implementing jive-specific interfaces is no-longer required to customize the authentication mechanism. The goal for 2.0 authentication customization has shifted focus to a more modular, composition and inversion of control-driven approach. This better aligns with the Spring-standard Acegi approach and focuses customization on Spring-managed filters and/or AuthenticationProvider implementations. The Clearspace 2.0 documentation has more information on creating new authentication customizations or migrating 1.x authentication customizations.

 

 

 

 

The hope for these changes is that they will improve, standardize and simplify security as it exists in Clearspace. Let us know your feedback!

 

 

0 Comments Permalink

Spring Is Coming

Posted by Dolan Halbrook Jan 17, 2008

Among the changes being made to Clearspace during 2008 is the adoption of the Spring framework in many parts of the application.  The first and most obvious feature of Spring of which we are taking advantage is the well-known and robust configuration and dependency injection service.  Much of what was formerly done using the JiveContext is now delegated to a Spring ApplicationContext, and this trend will continue.  This enables easier integration with existing libraries, more pluggability and testablility, and greater familiarity to the developer world.  What is more, with our upgrade to Struts2 (from WebWork2) all Struts objects are created using Spring as the object factory.  The immediate benefit to the developer is that any Spring-managed dependencies in a Struts object (actions, interceptors, etc) will automagically be set using Spring autowiring.

 

JDBC and Transactional support are other areas where we have attempted to make use of the facilities provided by the Spring framework.  Indeed anyone who has used the code provided by the framework for those two areas will be clear as to why we have chosen to do so.  Because of the improved ease of layering transactions declaratively, much more of the codebase will be transactional than before, leading to improved data integrity across the system.  We have also taken advantage of Spring LDAP support, DWR integration, CXF integration, and OSWorkflow integration.  Last but not least, we have worked to integrate the Acegi framework for authentication, and are working to use it for authorization as well.

 

The inclusion of the Spring framework into our project lays the groundwork for many benefits in upcoming versions of Clearspace.  We hope that you're as excited as we are to explore the possibilities and reap the benefits of its arrival.

0 Comments Permalink