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 Check if a Given Graph Contain Hamiltonian Cycle or Not
How to Read a File in Java
Converting a Stack Trace to a String in Java
A Guide to JUnit 5 Extensions
Hướng dẫn Java Design Pattern – Intercepting Filter
Java Program to Implement the Bin Packing Algorithm
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Converting String to Stream of chars
Lập trình đa luồng với Callable và Future trong Java
Using a List of Values in a JdbcTemplate IN Clause
Java Program to Use rand and srand Functions
Java Program to Implement VList
Guide to java.util.concurrent.BlockingQueue
How to Add a Single Element to a Stream
Java Program to Implement LinkedList API
Java Program to Solve any Linear Equations
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Hướng dẫn Java Design Pattern – Observer
Phương thức tham chiếu trong Java 8 – Method References
Java Program to Implement Queue
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java 14 Record Keyword
Java Program to Decode a Message Encoded Using Playfair Cipher
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Java Program to Perform Matrix Multiplication
Automatic Property Expansion with Spring Boot
Java Program to Implement Bubble Sort
Java Program to Implement Hash Tables with Double Hashing
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Java Program to Implement Fermat Primality Test Algorithm
Java Program to Emulate N Dice Roller