IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Services Web Java Discussion :

Authentification Web Service Java 6 - Header SOAP


Sujet :

Services Web Java

  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Novembre 2008
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2008
    Messages : 5
    Points : 3
    Points
    3
    Par défaut Authentification Web Service Java 6 - Header SOAP
    Bonjour

    Suite a des jours de recherche j'ai pu ajouté la notion d'authentification a mon WebService. Vous trouvez en détaille les démarche a suivre pour faire la même chose:

    1 -Explication
    D'abord La communication entre le client et WebService est assurée par le protocole SOAP. Le message SOAP est écrit en XML, les principales balises sont les suivantes
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     <soap:Message>
            <soap:Part>
                     <soap:Envelope>
                            <soap:Header>
                            <soap:Header>
                            <soap:Body>
                            <soap:Body>
                     </soap:Envelope>
            </soap:Part>
       </soap:Message>
    Une des méthodes d'authentification consiste a ajouté un NomUtilisateur et MotPasse dans le Header Soap en respectent les spécification de sécurités (WSS http://www.oasis-open.org/committees...?wg_abbrev=wss, WSE 3.0http://www.microsoft.com/download/en....aspx?id=14089, ....) pour c# http://stackoverflow.com/questions/2...d-with-wse-3-0

    Dans notre exemple on va ajouter le Login et le Passoward dans le Header de SOAP on respectant WSS de l'organisme OASIS (Mode Jeton)

    2-Coté Client
    Coté client en récupere le service et on l'ajoute un Handle qui nous permettre d'ajouer un Soap Heder avec les spécification attendu, Le code de Client, Handle sont le suivants :
    Client
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import javax.xml.ws.handler.Handler;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.BindingProvider;
     
     
     
    public class Main {
     
    	public static void main(String[] args) {
     
    		CalculatriceService service = new CalculatriceService();
     
    		HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
    		service.setHandlerResolver(handlerResolver);
     
    		InterfaceCalculatrice port = service.getCalculatricePort();
     
    		System.out.println("------------------------------------------");
    		System.out.println("Service Addition");
    		System.out.println("------------------------------------------");
    		String reponse = port.add(5,6);
     
            System.out.println("------------------------------------------");
    		System.out.println("Resultats= \n" + reponse);
    	}
    }
    HandleResolver
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    import java.util.ArrayList;
     
    import java.util.List;
    import javax.xml.ws.handler.Handler;
    import javax.xml.ws.handler.HandlerResolver;
    import javax.xml.ws.handler.PortInfo;
     
    /**
     *
     * 
     */
    public class HeaderHandlerResolver implements HandlerResolver {
     
    public List<Handler> getHandlerChain(PortInfo portInfo) {
          List<Handler> handlerChain = new ArrayList<Handler>();
     
          HeaderHandler hh = new HeaderHandler();
     
          handlerChain.add(hh);
     
          return handlerChain;
       }
    }
    Handle
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
     
    import java.util.Set;
     
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPElement;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.soap.SOAPMessage;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
     
    /**
     *
     * 
     */
    public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {
     
        public boolean handleMessage(SOAPMessageContext smc) {
     
            Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
     
            if (outboundProperty.booleanValue()) {
     
                SOAPMessage message = smc.getMessage();
     
                try {
     
                    SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
                    SOAPHeader header = envelope.addHeader();
     
                    SOAPElement security =
                            header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
     
                    SOAPElement usernameToken =
                            security.addChildElement("UsernameToken", "wsse");
                    usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
     
                    SOAPElement username =
                            usernameToken.addChildElement("Username", "wsse");
                    username.addTextNode("nomUtilisateur");
     
                    SOAPElement password =
                            usernameToken.addChildElement("Password", "wsse");
                    password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
                   password.addTextNode("motpass");
     
                    //Print out the outbound SOAP message to System.out
                    message.writeTo(System.out);
                    System.out.println("");
     
                } catch (Exception e) {
                    e.printStackTrace();
                }
     
            } else {
                try {
     
                    //This handler does nothing with the response from the Web Service so
                    //we just print out the SOAP message.
                    SOAPMessage message = smc.getMessage();
                    message.writeTo(System.out);
                    System.out.println("");
     
                } catch (Exception ex) {
                    ex.printStackTrace();
                } 
            }
     
     
            return outboundProperty;
     
        }
     
        public Set<QName> getHeaders() {
            //throw new UnsupportedOperationException("Not supported yet.");
            return null;
        }
     
        public boolean handleFault(SOAPMessageContext context) {
            //throw new UnsupportedOperationException("Not supported yet.");
            return true;
        }
     
        public void close(MessageContext context) {
        //throw new UnsupportedOperationException("Not supported yet.");
        }
    }
    3- Coté Serveur

    Depuis la version JDK6 on peut lancer un WebService sans serveur. Voila les trois class a utiliser pour pour deployer un Web service avec authentification

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    package webServices;
     
    import javax.annotation.Resource;
    import javax.jws.HandlerChain;
    import javax.jws.WebService;
    import javax.xml.ws.WebServiceContext;
     
    @WebService(endpointInterface = "webServices.InterfaceDS")
    @HandlerChain(file = "handlers.xml")
    public class ServiceWSDS implements InterfaceWSDS {
     
     
    	@Resource
    	WebServiceContext context;	
     
    	/*******************************************************************************************************/
    	public String add(int a, int b) {
     
    		User user= null;
     
    		if(this.authentification(context)){
    			return a + b;
    		}else
    			return null; 
     
    	}
     
    	/*******************************************************************************************************/
    	private boolean authentification(WebServiceContext ctx){
     
    		String userName=null;
    		String passward=null;
     
    		try {
     
    			HeaderList headers =  (HeaderList)context.getMessageContext().get("com.sun.xml.ws.api.message.HeaderList");
    			Header hd = headers.get(0); 
     
    			XMLStreamReader xmlread  = hd.readHeader();
    			int nn = 1;
     
    			do{
    				if(xmlread.hasName()&&nn==1&&xmlread.hasNext()){
     
    					if(xmlread.getLocalName().equals("Username")){
    						xmlread.next();
    						if(xmlread.isCharacters())
    							userName=xmlread.getText();
    					}else	
    					if(xmlread.getLocalName().equals("Password")&&nn==1&&xmlread.hasNext()){
    						xmlread.next();
    						if(xmlread.isCharacters())
    							passward=xmlread.getText();
    					}
    				}
     
    				if(userName!=null &&passward!=null)
    					break;
     
    				nn = xmlread.next();
     
    			}while(xmlread.hasNext());
     
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
     
    		if(userName=="nomAttendu" && passward=="MotPasseAttendu")
    			return true;
    		else
    			return false;
     
    	}
    }
    dans mon exemple j'ai utilisé un Handle coté serveur pour intercepter et afficher le message Soap entrent et sortant, Pour faire ça vous devez ajouter un fichier xml de config "handlers.xml" et la class SOAPLoggingHandler
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <?xml version="1.0" encoding="UTF-8"?>
    <handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
    	<handler-chain>
    		<handler>
    			<handler-name>webServices.SOAPLoggingHandler</handler-name>
    			<handler-class>webServices.SOAPLoggingHandler</handler-class>
    		</handler>
    	</handler-chain>
    </handler-chains>
    SOAPLoggingHandler

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    package webServices;
     
    import java.io.PrintStream;
    import java.util.Date;
    import java.util.Set;
     
    import javax.xml.soap.SOAPMessage;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
     
     
    public class SOAPLoggingHandler<QName> implements SOAPHandler<SOAPMessageContext> {
     
    	private static PrintStream out = System.out;
     
    	public Set<javax.xml.namespace.QName> getHeaders() { return null; }
     
    	public void close(MessageContext context) { }
     
    	public boolean handleMessage(SOAPMessageContext smc) {
    		logToSystemOut(smc);
    		return true;
    	}
     
    	public boolean handleFault(SOAPMessageContext smc) {
    		logToSystemOut(smc);
    		return true;
    	}
     
    	private void logToSystemOut(SOAPMessageContext smc) {
     
    		Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
     
    		out.println(new Date().toString()+" : Appel au Web Service ");
    		out.println(" \n-------------------  Message SOAP : Debut ---------------------\n" );
     
    		if (outboundProperty.booleanValue()) {
    			out.println("\nOutgoing message from web service provider:");
    		} else {
    			out.println("\nIncoming message to web service provider:");
    		}
     
    		SOAPMessage message = smc.getMessage();
     
    		try {
     
    			message.writeTo(out);
    			out.println("");
    		} catch (Exception e) {
    			out.println("Exception in handler: " + e);
    		}
     
    		out.println(" \n-------------------  Message SOAP : Fin   ---------------------\n" );
     
    	}
    }
    -----------------------------------------------------------------------
    Une remarque: il faut ajouter les jar de jaxws coté serveur, sont téléchargeable sur ce lien http://jax-ws.java.net/2.2.5/

    Bon courage

    Pardon pour les fautes d'orthographe

    Bonne courage

  2. #2
    Membre confirmé
    Profil pro
    Inscrit en
    Décembre 2003
    Messages
    476
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2003
    Messages : 476
    Points : 595
    Points
    595
    Par défaut
    Salut,

    merci de partager ton retour
    Le nom du sujet ne fait pas penser à un tuto par contre.
    Ils flottent tous en bas

  3. #3
    Candidat au Club
    Profil pro
    Inscrit en
    Novembre 2008
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2008
    Messages : 5
    Points : 3
    Points
    3
    Par défaut
    Une remarque: il faut ajouter jar de jaxws coté serveur, sont téléchargeable sur ce lien http://jax-ws.java.net/2.2.5/

    Bon courage

  4. #4
    Candidat au Club
    Profil pro
    Inscrit en
    Novembre 2008
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2008
    Messages : 5
    Points : 3
    Points
    3
    Par défaut
    Citation Envoyé par thebloodyman Voir le message
    Salut,

    merci de partager ton retour
    Le nom du sujet ne fait pas penser à un tuto par contre.
    une partie de code Oui mais pas la totalité

    Cordialement

Discussions similaires

  1. Authentification Web Service Java 6 - Header SOAP
    Par ameur1 dans le forum Services Web
    Réponses: 0
    Dernier message: 06/10/2011, 18h10
  2. authentification web service
    Par dimahoo dans le forum Sécurité
    Réponses: 4
    Dernier message: 29/10/2010, 10h29
  3. web services Java/C++
    Par tet.dum dans le forum Services Web
    Réponses: 7
    Dernier message: 24/11/2006, 15h28
  4. Deploiment web service + java
    Par dimahoo dans le forum Services Web
    Réponses: 3
    Dernier message: 16/04/2006, 00h04
  5. [Web Services] [JAVA] cree un client
    Par yannick24 dans le forum XML/XSL et SOAP
    Réponses: 1
    Dernier message: 10/12/2005, 01h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo