SOAP Web service: Authentication trong JAX-WS

Một trong những cách được sử dụng để chứng thực (Authentication) người dùng trong JAX-WS là Client sẽ cung cấp username/ password trong SOAP request header và gửi lên server. Server sẽ parse SOAP document và lấy thông tin username/ password từ request header và sau đó thực hiện truy xuất database để validate hoặc làm bất kỳ cái gì nếu muốn.

Trong bài này, chúng ta sẽ cùng tìm hiểu cách chứng thực Client trong JAX-WS.

1. Tạo WebService Server

WelcomeService.java

package com.maixuanviet.ws.authentication;
 
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
@WebService
@SOAPBinding(style = Style.RPC)
public interface WelcomeService {
 
    @WebMethod
    String getWelcomeMsg(String name);
}

Chúng ta sử dụng WebServiceContext để truy xuất thông tin được Client gửi lên trong header.

WelcomeServiceImpl.java

package com.maixuanviet.ws.authentication;
 
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;
 
@WebService(endpointInterface = "com.maixuanviet.ws.authentication.WelcomeService")
public class WelcomeServiceImpl implements WelcomeService {
 
    @Resource
    private WebServiceContext wsctx;
 
    @Override
    public String getWelcomeMsg(String name) {
        MessageContext mctx = wsctx.getMessageContext();
 
        // get detail from request headers
        Map<String, Object> headers = (Map<String, Object>) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
        List<String> users = (List<String>) headers.get("username");
        List<String> pwds = (List<String>) headers.get("password");
 
        if (users != null && pwds != null) {
            if ("maixuanviet".equals(users.get(0)) && "jax-ws-by-maixuanviet".equals(pwds.get(0))) {
                return "Welcome " + name;
            } else {
                return "Authentication failed!";
            }
        }
 
        return "Username and password are not provided!";
    }
}

WelcomePublisher.java

package com.maixuanviet.ws.authentication;
 
import javax.xml.ws.Endpoint;
 
public class WelcomePublisher {
     
    public static final String WS_URL = "http://localhost:8080/ws/welcome";
 
    public static void main(String[] args) {
        Endpoint.publish(WS_URL, new WelcomeServiceImpl());
    }
}

2. Tạo Client truy cập WS

Chúng ta sử dụng RequestContext để gửi thông tin username và password lên Server. Lưu ý: giá trị trong header là kiểu Map<String, List<Object>>.

WelcomeClient.java

package com.maixuanviet.ws.authentication;
 
import java.net.MalformedURLException;
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;
 
public class WelcomeClient {
 
    private static final String WS_URL = WelcomePublisher.WS_URL + "?wsdl";
 
    public static void main(String[] args) throws MalformedURLException {
        // Create URL of .wsdl file
        URL wsdlURL = new URL(WS_URL);
 
        // Create a QName using targetNamespace and name
        QName qname = new QName("http://authentication.ws.maixuanviet.com/", "WelcomeServiceImplService");
 
        // Creates a Service instance with the specified WSDL document location and
        // service qualified name
        Service service = Service.create(wsdlURL, qname);
 
        // We need to pass interface and model beans to client
        WelcomeService userService = service.getPort(WelcomeService.class);
 
        // Prepare username & password
        Map<String, List<String>> headers = new HashMap<>();
        headers.put("username", Collections.singletonList("maixuanviet"));
        headers.put("password", Collections.singletonList("jax-ws-by-maixuanviet"));
 
        // Set request to header
        Map<String, Object> requestContext = ((BindingProvider) userService).getRequestContext();
        requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
 
        // Send request and receive response
        System.out.println("Result: " + userService.getWelcomeMsg("maixuanviet.com"));
    }
}

Chạy file WelcomePublisher.java trước, sau đó chạy file WelcomeClient.java chúng ta có kết quả như sau:

Result: Welcome maixuanviet.com

Related posts:

Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
The HttpMediaTypeNotAcceptableException in Spring MVC
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Perform the Shaker Sort
Removing all duplicates from a List in Java
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Implement Interpolation Search Algorithm
Quick Guide on Loading Initial Data with Spring Boot
Kết hợp Java Reflection và Java Annotations
Java Program to Implement the MD5 Algorithm
Spring WebClient Requests with Parameters
Create a Custom Exception in Java
Java Program to Implement Bubble Sort
Guide to @ConfigurationProperties in Spring Boot
Using the Not Operator in If Conditions in Java
Java Program to Perform Sorting Using B-Tree
Setting Up Swagger 2 with a Spring REST API
Spring MVC Content Negotiation
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Compare Binary and Sequential Search
Hướng dẫn Java Design Pattern – Decorator
Guide to ThreadLocalRandom in Java
How to Add a Single Element to a Stream
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Java Program to Implement Sorted Doubly Linked List
Java Program to Implement HashSet API
Spring Boot: Customize the Jackson ObjectMapper
Lập trình đa luồng với CompletableFuture trong Java 8
Hướng dẫn Java Design Pattern – Builder
An Intro to Spring Cloud Vault
MyBatis with Spring
Convert Character Array to String in Java