Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package hudson.plugins.collabnet.auth;
Class for filtering CollabNet auth information for SSO.
 public class CNFilter implements Filter {
     private static Logger log = Logger.getLogger("CNFilter");
     public void init(FilterConfig filterConfig) {

Filter for the CollabNet plugin. Handles 2 separate tasks: 1. Attempts to use CollabNet tokens to login (if they are present and we're not currently authed.). 2. If we have not yet logged into the CollabNet server, redirect to the CollabNet server and login.

request the servlet request
response the servlet response
chain remaining filters to handle.
     public void doFilter(ServletRequest requestServletResponse response,
                          FilterChain chainthrows IOExceptionServletException {
         if (Hudson.getInstance().isUseSecurity()) {
             // check if we're in the CollabNetSecurity Realm
             SecurityRealm securityRealm = Hudson.getInstance().getSecurityRealm();
             if (securityRealm instanceof CollabNetSecurityRealm) {
                 CollabNetSecurityRealm cnRealm = (CollabNetSecurityRealmsecurityRealm;
                 boolean enableSSOFromCTF = cnRealm.getEnableSSOAuthFromCTF();
                 boolean enableSSOToCTF = cnRealm.getEnableSSOAuthToCTF();
                 Authentication auth = Hudson.getAuthentication();
                 if (enableSSOFromCTF) {
                     HttpServletRequest httpRequest = (HttpServletRequestrequest;
                     // first detect if we are accessing hudson through CTF
                     String username = request.getParameter("sfUsername");
                     if (username != null) {
                         // 'sfUsername' is used for CTF linked apps. if present make sure match the authenticated user
                         if (!username.equals(auth.getName())) {
                     if (!auth.isAuthenticated() || auth.getPrincipal().equals("anonymous")) {
                 if (enableSSOToCTF && auth instanceof CNAuthentication) {
                     CNAuthentication cnauth = (CNAuthenticationauth;
                     if (!cnauth.isCNAuthed()) {
                         loginToCTF(cnauth, (CollabNetSecurityRealm)securityRealm,
                             (HttpServletRequestrequest, (HttpServletResponseresponse);

Catch SSO data from CollabNet if data is present, and automatically login. Used when the Hudson server is setup as a linked application in the CollabNet server. The CollabNet server will sent 2 parameters: sfUsername and sfLoginToken. The token is a one-time token that can be used to initiate a SOAP session and set authentication.

securityRealm the security realm
request the huttp servlet reuqest
    private void loginHudsonUsingCTFSSO(CollabNetSecurityRealm securityRealmHttpServletRequest request) {
        String url = securityRealm.getCollabNetUrl();
        String username = request.getParameter("sfUsername");
        String token = request.getParameter("sfLoginToken");
        Authentication auth = null;
        boolean logoff = false;
        if (username != null && token != null) {
            CollabNetApp ca = new CollabNetApp(urlusername);
            try {
                auth = new CNAuthentication(usernameca);
            } catch (RemoteException re) {
                // login failed, but continue
                .severe("Login failed with RemoteException: " + 
                logoff = true
        } else {
            logoff = true;
        if (logoff) {
            auth = new AnonymousAuthenticationToken("anonymous","anonymous",
                new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
        // ensure that a session exists before we set context in it
        // see artf42298
Redirect to the CollabNet Server to login there, and then redirect back to our original location.

cnauth the CNAuthentication object
securityRealm the security realm
request the http request
response the http response
    private void loginToCTF(CNAuthentication cnauthCollabNetSecurityRealm securityRealm,
                          HttpServletRequest requestHttpServletResponse response)
        throws IOExceptionServletException {
        String reqUrl = getCurrentUrl(request);
        String collabNetUrl = securityRealm.getCollabNetUrl();
        String username = (String)cnauth.getPrincipal();
        String id = cnauth.getSessionId();
        String cnauthUrl = collabNetUrl + "/sf/sfmain/do/soapredirect?id=" 
            + URLEncoder.encode(id"UTF-8") + "&user=" + 
        if (securityRealm.getEnableSSORedirect()) {
            // append redirect only if enabled
            cnauthUrl = cnauthUrl + "&redirectUrl=" + URLEncoder.encode(reqUrl,"UTF-8");
        // prepare a redirect


req the servlet request to pull data from, if root url is unset.
the best guess for the current base URL (i.e. just the scheme, server, port) plus the contextPath.
    public static String getCurrentBaseUrl(HttpServletRequest req) {
        StringBuilder url = new StringBuilder();
        // Use the user configured url, if available.
        String rootUrl = Hudson.getInstance().getRootUrl();
        if (rootUrl != null) {
        }else {
            // otherwise, use the request
            if (req.getServerPort() != 80) {
        return url.toString();

the best guess for the current full URL. It will use the "referer" field from the request to determine the url, if it is present.
    public static String getCurrentUrl(HttpServletRequest req) {
        String curBaseUrl = getCurrentBaseUrl(req);
        // remove the contextPath from the url, since it will also
        // be present in the requestURI.
        curBaseUrl = CommonUtil.stripSlashes(curBaseUrl);
        curBaseUrl = StringUtils.removeEnd(curBaseUrlreq.getContextPath());
        StringBuilder url = new StringBuilder(curBaseUrl);
        if (req.getRequestURI() != null) {
        if (req.getQueryString() != null) {
            url.append("?" + req.getQueryString());
        return url.toString();
    // destroy is currently a no-op
    public void destroy() {
New to GrepCode? Check out our FAQ X