alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Glassfish example source code file (CommonServerSecurityTube.java)

This example Glassfish source code file (CommonServerSecurityTube.java) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Glassfish tags/keywords

authstatus, commonserversecuritytube, exception, exception, log, logging, nextaction, object, override, packet, packet, security, subject, subject, throwable, util, webserviceexception, webserviceexception, xml

The Glassfish CommonServerSecurityTube.java source code

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License.  You can
 * obtain a copy of the License at
 * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
 * or packager/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at packager/legal/LICENSE.txt.
 *
 * GPL Classpath Exception:
 * Oracle designates this particular file as subject to the "Classpath"
 * exception as provided by Oracle in the GPL Version 2 section of the License
 * file that accompanied this code.
 *
 * Modifications:
 * If applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyright [year] [name of copyright owner]"
 *
 * Contributor(s):
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package com.sun.enterprise.security.webservices;

import com.sun.xml.ws.api.pipe.TubeCloner;
import com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;

import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import javax.security.auth.Subject;
import javax.security.auth.message.config.*;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;

import javax.xml.ws.WebServiceException;

import com.sun.enterprise.security.jmac.provider.PacketMapMessageInfo;
import com.sun.enterprise.security.jmac.provider.PacketMessageInfo;
import com.sun.enterprise.security.jmac.provider.config.PipeHelper;
import com.sun.enterprise.util.LocalStringManagerImpl;
import com.sun.logging.LogDomains;

import com.sun.xml.ws.api.message.Packet;
import com.sun.xml.ws.api.pipe.NextAction;
import com.sun.xml.ws.api.pipe.Tube;
import com.sun.xml.ws.api.pipe.helper.AbstractFilterTubeImpl;


/**
 * This pipe is used to do 196 security
 */
public class CommonServerSecurityTube extends AbstractFilterTubeImpl {

    protected static final Logger _logger = LogDomains.getLogger(CommonServerSecurityTube.class,
        LogDomains.SECURITY_LOGGER);
    protected static final LocalStringManagerImpl localStrings = 
        new LocalStringManagerImpl(CommonServerSecurityTube.class);
    private final boolean isHttpBinding;
    private PipeHelper helper;
    
    // Introduced during Pipe to Tube conversion
    private ServerAuthContext sAC = null;
    private PacketMessageInfo info = null;
    private Subject serverSubject = null;
    
    public CommonServerSecurityTube(Map props, final Tube next, 
			     boolean isHttpBinding) {
        super(next);
	props.put(PipeConstants.SECURITY_PIPE, this);
	this.helper = new PipeHelper(PipeConstants.SOAP_LAYER,props,null);
        this.isHttpBinding = isHttpBinding;
       
    }    
    
    protected CommonServerSecurityTube(CommonServerSecurityTube that,
            TubeCloner cloner) {

        super(that, cloner);
        // we can share the helper for all pipes so that the remove 
        // registration (in server side) can be done properly
        this.helper = that.helper;
        this.isHttpBinding = that.isHttpBinding;
    }

    /**
     * This method is called once in server side and at most one in client side.
     */
    public void preDestroy() {
	helper.disable();
        /**
         Fix for bug 3932/4052
         */
        next.preDestroy(); 
    }    
    
    
    @Override
    public NextAction processRequest(Packet request) {
        try {
            if (isHttpBinding) {
                return doInvoke(super.next, request);
            }

            AuthStatus status = AuthStatus.SUCCESS;
            info = new PacketMapMessageInfo(request, new Packet());
            // XXX at this time, we expect the server subject to be null
            serverSubject = (Subject) request.invocationProperties.get(PipeConstants.SERVER_SUBJECT);

            //could change the request packet
            sAC = helper.getServerAuthContext(info, serverSubject);
            Subject clientSubject = getClientSubject(request);
            final Packet validatedRequest;
            try {
                if (sAC != null) {
                    // client subject must not be null
                    // and when return status is SUCCESS, module
                    // must have called handler.handle(CallerPrincipalCallback)
                    status = sAC.validateRequest(info, clientSubject, serverSubject);
                }
            } catch (Exception e) {
                _logger.log(Level.SEVERE, "ws.error_validate_request", e);
                WebServiceException wse = new WebServiceException(localStrings.getLocalString("enterprise.webservice.cantValidateRequest",
                        "Cannot validate request for {0}",
                        new Object[]{helper.getModelName()}), e);

                //set status for audit
                status = AuthStatus.SEND_FAILURE;
                // if unable to determine if two-way will return empty response
                Packet ret = helper.getFaultResponse(info.getRequestPacket(), info.getResponsePacket(), wse);
                return doReturnWith(ret);

            } finally {
                validatedRequest = info.getRequestPacket();
                helper.auditInvocation(validatedRequest, status);
            }

            Packet response = null;
            if (status == AuthStatus.SUCCESS) {
                boolean authorized = false;
                try {
                    helper.authorize(validatedRequest);
                    authorized = true;

                } catch (Exception e) {
                    // not authorized, construct fault and proceded
                    response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), e);
                    return doReturnWith(response);
                }
                if (authorized) {

                    // only do doAdPriv if SecurityManager is in effect
                    if (System.getSecurityManager() == null) {
                        try {
                            // proceed to invoke the endpoint
                            return doInvoke(super.next, validatedRequest);
                        } catch (Exception e) {
                            _logger.log(Level.SEVERE, "ws.error_next_pipe", e);
                            response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), e);
                            return doReturnWith(response);
                        }
                    } else {
                        try {
                            final Tube next = super.next;
                            NextAction action = (NextAction) Subject.doAsPrivileged(clientSubject, new PrivilegedExceptionAction() {

                                public Object run() throws Exception {
                                    // proceed to invoke the endpoint
                                    return doInvoke(next, validatedRequest);
                                }
                            }, null);
                            return action;
                        } catch (PrivilegedActionException pae) {
                            Throwable cause = pae.getCause();
                            _logger.log(Level.SEVERE, "ws.error_next_pipe", cause);                           
                            response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), cause);
                            return doReturnWith(response);
                        }
                    }
                } else { //if not authorized
                    // not authorized, construct fault and proceded
		    response = helper.getFaultResponse(
                            validatedRequest,info.getResponsePacket(), new Exception("Client Not Authorized"));
                    return doReturnWith(response);
                }

            } else {
                // validateRequest did not return success
                if (_logger.isLoggable(Level.FINE)) {
                    _logger.log(Level.FINE, "ws.status_validate_request", status);
                }
                // even for one-way mep, may return response with non-empty message
                response = info.getResponsePacket();
                return doReturnWith(response);
            }

        } catch (Throwable t) {
            if (!(t instanceof WebServiceException)) {
                t = new WebServiceException(t);
            }
            return doThrow(t);
        }
    }
 
    @Override
    public NextAction processResponse(Packet response) {
        try{
            //could be oneway
            if((response == null) || (response.getMessage() == null)){
                return doReturnWith(response);
            }
            Packet resp = response;
	    // secure response, including if it is a fault
	    if (sAC != null && response.getMessage() != null) {
		info.setResponsePacket(response);
		resp = processResponse(info, sAC, serverSubject);
	    }
            return doReturnWith(resp);
        }catch(Throwable t){
            if (!(t instanceof WebServiceException)) {
                t = new WebServiceException(t);
            }
            return doThrow(t);
        }
         
    }
    
    
    // called when secureResponse is to be called 
    private Packet processResponse(PacketMessageInfo info,
				   ServerAuthContext sAC,
				   Subject serverSubject) throws Exception {
        
        AuthStatus status;

	try {
	    status = sAC.secureResponse(info, serverSubject);
	} catch (Exception e) {
	    if (e instanceof AuthException) {
		if (_logger.isLoggable(Level.INFO)) {
		    _logger.log(Level.INFO, "ws.error_secure_response", e);
		}
	    } else {
		_logger.log(Level.SEVERE, "ws.error_secure_response", e);
	    }
    
	    return helper.makeFaultResponse(info.getResponsePacket(),e);
	}
	if (_logger.isLoggable(Level.FINE)) {
	    _logger.log(Level.FINE,"ws.status_secure_response", status);
	}
	return info.getResponsePacket();

    }

    private static Subject getClientSubject(Packet p) {
	
	Subject s = null;
	
	if (p != null) {
	    s =(Subject) 
		p.invocationProperties.get(PipeConstants.CLIENT_SUBJECT);
	}
	if (s == null) {	    
	    s = PipeHelper.getClientSubject();	    
	    if (p != null) {
		p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT,s);
	    }
	}
	return s;
    }

    @Override
    public AbstractTubeImpl copy(TubeCloner cloner) {
         return new CommonServerSecurityTube(this, cloner);
    }

    
}







Other Glassfish examples (source code examples)

Here is a short list of links related to this Glassfish CommonServerSecurityTube.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.