Jivespace Community Blog

2 Posts tagged with the sso 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