Authentification d’application avec JAX-WS

L’un des moyens courants de gérer l’authentification dans JAX-WS consiste à fournir au client «nom d’utilisateur» et «mot de passe», en le joignant à l’en-tête de la requête SOAP et à l’envoyer au serveur. partir de l’en-tête de demande et valider à partir de la base de données, ou quelle que soit la méthode préférée.

Dans cet article, nous vous montrons comment implémenter l’authentification «au niveau de l’application» ci-dessus dans JAX-WS ** «.

Idées …​

Sur le site client de service Web , il suffit de mettre votre "nom d’utilisateur" et votre "mot de passe" dans l’en-tête de la requête.

    Map<String, Object> req__ctx = ((BindingProvider)port).getRequestContext();
    req__ctx.put(BindingProvider.ENDPOINT__ADDRESS__PROPERTY, WS__URL);

    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put("Username", Collections.singletonList("mkyong"));
    headers.put("Password", Collections.singletonList("password"));
    req__ctx.put(MessageContext.HTTP__REQUEST__HEADERS, headers);

Sur le site serveur de service Web , obtenez les paramètres d’en-tête de requête via WebServiceContext .

    @Resource
    WebServiceContext wsctx;

    @Override
    public String method() {

        MessageContext mctx = wsctx.getMessageContext();

   //get detail from request headers
        Map http__headers = (Map) mctx.get(MessageContext.HTTP__REQUEST__HEADERS);
        List userList = (List) http__headers.get("Username");
        List passList = (List) http__headers.get("Password");

   //...

C’est tout, votre JAX-WS déployée est désormais prise en charge par l’authentification au niveau de l’application.

Exemple d’authentification avec JAX-WS

Voir un exemple complet.

1. Serveur WebService

Créez un exemple simple de monde JAX-WS hello pour gérer l’authentification au niveau de l’application.

File: HelloWorld.java

package com.mkyong.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{

    @WebMethod String getHelloWorldAsString();

}

HelloWorldImpl.java

package com.mkyong.ws;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
//Service Implementation Bean
@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

    @Resource
    WebServiceContext wsctx;

    @Override
    public String getHelloWorldAsString() {

    MessageContext mctx = wsctx.getMessageContext();

   //get detail from request headers
        Map http__headers = (Map) mctx.get(MessageContext.HTTP__REQUEST__HEADERS);
        List userList = (List) http__headers.get("Username");
        List passList = (List) http__headers.get("Password");

        String username = "";
        String password = "";

        if(userList!=null){
           //get username
            username = userList.get(0).toString();
        }

        if(passList!=null){
           //get password
            password = passList.get(0).toString();
        }

       //Should validate username and password with database
        if (username.equals("mkyong") && password.equals("password")){
            return "Hello World JAX-WS - Valid User!";
        }else{
            return "Unknown User!";
        }

    }
}

2. EndPoint Publisher

Créez un éditeur de point de terminaison pour déployer le service Web ci-dessus à cette URL:

Http://localhost: 9999/ws/hello

File: HelloWorldPublisher.java

package com.mkyong.endpoint;

import javax.xml.ws.Endpoint;
import com.mkyong.ws.HelloWorldImpl;
 //Endpoint publisher
public class HelloWorldPublisher{

    public static void main(String[]args) {
       Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }

}

3. Client WebService

Créez un client de service Web pour envoyer «nom d’utilisateur» et «mot de passe» pour l’authentification.

File: HelloWorldClient.java

package com.mkyong.client;

import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;

import com.mkyong.ws.HelloWorld;

public class HelloWorldClient{

    private static final String WS__URL = "http://localhost:9999/ws/hello?wsdl";

    public static void main(String[]args) throws Exception {

    URL url = new URL(WS__URL);
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");

        Service service = Service.create(url, qname);
        HelloWorld hello = service.getPort(HelloWorld.class);

       /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** UserName & Password ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** /        Map<String, Object> req__ctx = ((BindingProvider)hello).getRequestContext();
        req__ctx.put(BindingProvider.ENDPOINT__ADDRESS__PROPERTY, WS__URL);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList("mkyong"));
        headers.put("Password", Collections.singletonList("password"));
        req__ctx.put(MessageContext.HTTP__REQUEST__HEADERS, headers);
       /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** /
        System.out.println(hello.getHelloWorldAsString());

    }
}

Sortie

Hello World JAX-WS - Valid User!

4. Traçage du trafic SOAP

De haut en bas, montrant comment l’enveloppe SOAP circule entre le client et le serveur.

{vide} 1. La demande d’envoi du client, le nom d’utilisateur « mkyong » et le mot de passe « password » sont inclus dans l’enveloppe SOAP.

POST/ws/hello?wsdl HTTP/1.1
Password: password
Username: mkyong
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, ** ; q=.2, ** /** ; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0__13
Host: localhost:8888
Connection: keep-alive
Content-Length: 178

<?xml version="1.0" ?>
    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
        <S:Body>
            <ns2:getHelloWorldAsString xmlns:ns2="http://ws.mkyong.com/"/>
        </S:Body>
    </S:Envelope>

{vide} 2. Le serveur renvoie une réponse normale.

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8

<?xml version="1.0" ?>
    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
        <S:Body>
            <ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.mkyong.com/">
                <return>Hello World JAX-WS - Valid User!</return>
            </ns2:getHelloWorldAsStringResponse>
        </S:Body>
    </S:Envelope>

Terminé.

Télécharger le code source

Téléchargez-le - lien://wp-content/uploads/2010/12/JAX-WS-Application-Authentication-Example.zip[JAX-WS-Application-Authentication-Example.zip](10 Ko)

lien://étiquette/authentification/[authentification]lien://étiquette/jax-ws/[jax-ws] security web services