webservice添加用户密码验证

时间:2024-03-13 14:41:25

一、增加maven 依赖

         <dependency>
		    <groupId>org.apache.cxf</groupId>
		    <artifactId>cxf-rt-ws-security</artifactId>
		    <version>3.1.8</version>
		 </dependency>

二、spring-context配置拦截器

<jaxws:endpoint >
    	<jaxws:inInterceptors>
            <bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
                <constructor-arg>
                    <map>
                        <entry key="action" value="UsernameToken" />
                        <entry key="passwordType" value="PasswordDigest" />
                        <entry key="passwordCallbackRef">
                            <bean class="com.interceptor.PasswordCallback"></bean>
                        </entry>
                    </map>
                </constructor-arg>
            </bean>
        </jaxws:inInterceptors>
</jaxws:endpoint>

三、编写PasswordCallback

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.wss4j.common.ext.WSPasswordCallback;

import java.io.IOException;
 
 
public class PasswordCallback implements CallbackHandler {
    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
        String idf = pc.getIdentifier();//ws传过来的用户名
        String pwd = null;//需查数据库获得密码
        String cfgUser = "aaa";
        if(cfgUser!=null && cfgUser.equals(idf)) {
        	pwd = "123456";
        }else {
        	pwd = "error";
        }
        pc.setPassword(pwd);
    }

}

四、soapUI 调用时设置用户名密码

右键,show Interface view

webservice添加用户密码验证