怎么在springBoot中利用CXF實現(xiàn)用戶名密碼校驗

今天就跟大家聊聊有關(guān)怎么在springBoot中利用CXF實現(xiàn)用戶名密碼校驗,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

目前成都創(chuàng)新互聯(lián)已為近1000家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間綿陽服務(wù)器托管、企業(yè)網(wǎng)站設(shè)計、競秀網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

準備工作:

創(chuàng)建springBoot項目webservice_server

創(chuàng)建springBoot項目webservice_client

分別添加CXF的依賴:

<!-- CXF webservice -->
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
  <version>3.1.11</version>
</dependency>
<!-- CXF webservice -->

一.定義要發(fā)布的接口和實現(xiàn)類

接口:

@WebService
public interface AppService {


  @WebMethod
  String getUserName(@WebParam(name = "id") String id) throws UnsupportedEncodingException;
  @WebMethod
  public User getUser(String id) throws UnsupportedEncodingException;
}

實現(xiàn)類:

//name暴露的服務(wù)名稱, targetNamespace:命名空間,設(shè)置為接口的包名倒寫(默認是本類包名倒寫). endpointInterface接口地址
@WebService(name = "test" ,targetNamespace ="http://cxf.wolfcode.cn/" ,endpointInterface = "cn.wolfcode.cxf.AppService")
public class AppServiceImpl implements AppService {
  JSONResult jsonResult = JSONResult.getJsonResult();
  @Override
  public String getUserName(String id) throws UnsupportedEncodingException {
    System.out.println("==========================="+id);
    JSONResult result= JSONResult.getJsonResult();
    result.setSuccess(true);
    result.setMessage("明哥");
    return result.toJsonObject();
  }
  @Override
  public User getUser(String id)throws UnsupportedEncodingException {
    System.out.println("==========================="+id);
    return new User(1L,"明哥");
  }
}

二.發(fā)布服務(wù)

1.定義配置類

@Configuration
public class CxfConfig {
  //默認servlet路徑/*,如果覆寫則按照自己定義的來
  @Bean
  public ServletRegistrationBean dispatcherServlet() {
    return new ServletRegistrationBean(new CXFServlet(), "/services/*");
  }

  @Bean(name = Bus.DEFAULT_BUS_ID)
  public SpringBus springBus() {
    return new SpringBus();
  }

  //把實現(xiàn)類交給spring管理
  @Bean
  public AppService appService() {
    return new AppServiceImpl();
  }

  //終端路徑
  @Bean
  public Endpoint endpoint() {
    EndpointImpl endpoint = new EndpointImpl(springBus(), appService());
    endpoint.getInInterceptors().add(new AuthInterceptor());//添加校驗攔截器
    endpoint.publish("/user");
    return endpoint;
  }
}

2.發(fā)布服務(wù)

@SpringBootApplication
public class WebserviceApplication {

  public static void main(String[] args) {
    SpringApplication.run(WebserviceApplication.class, args);
  }
}

因為我添加了用戶名和密碼校驗所以在發(fā)布之前還需要定義自己校驗用戶名和密碼的Interceptor

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
  Logger logger = LoggerFactory.getLogger(this.getClass());
  private static final String USERNAME="root";
  private static final String PASSWORD="admin";

  public AuthInterceptor() {
    //定義在哪個階段進行攔截
    super(Phase.PRE_PROTOCOL);
  }

  @Override
  public void handleMessage(SoapMessage soapMessage) throws Fault {
    List<Header> headers = null;
    String username=null;
    String password=null;
    try {
      headers = soapMessage.getHeaders();
    } catch (Exception e) {
      logger.error("getSOAPHeader error: {}",e.getMessage(),e);
    }

    if (headers == null) {
      throw new Fault(new IllegalArgumentException("找不到Header,無法驗證用戶信息"));
    }
    //獲取用戶名,密碼
    for (Header header : headers) {
      SoapHeader soapHeader = (SoapHeader) header;
      Element e = (Element) soapHeader.getObject();
      NodeList usernameNode = e.getElementsByTagName("username");
      NodeList pwdNode = e.getElementsByTagName("password");
       username=usernameNode.item(0).getTextContent();
       password=pwdNode.item(0).getTextContent();
      if( StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
        throw new Fault(new IllegalArgumentException("用戶信息為空"));
      }
    }
    //校驗用戶名密碼
    if(!(username.equals(USERNAME) && password.equals(PASSWORD))){
      SOAPException soapExc = new SOAPException("認證失敗");
      logger.debug("用戶認證信息錯誤");
      throw new Fault(soapExc);
    }
  }
}

現(xiàn)在可以發(fā)布服務(wù)了.....

發(fā)布完成后訪問http://localhost:8888/services/user?wsdl

能夠出現(xiàn)以下界面就是發(fā)布OK

怎么在springBoot中利用CXF實現(xiàn)用戶名密碼校驗

三.調(diào)用服務(wù)

1.新建調(diào)用端項目,添加依賴

2.因為示例演示了兩種調(diào)用方式,其中一種需要用到接口,所以先把服務(wù)接口拷貝一份到調(diào)用端項目中(代碼就是上面接口的代碼)

3.因為服務(wù)端添加了用戶名密碼校驗,所以調(diào)用的時候需要添加用戶名密碼信息, 所以需要使用下面的Interceptor完成添加用戶名密碼信息

/**
 * Created by sky on 2018/2/27.
 */
public class LoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
  private String username="root";
  private String password="admin";
  public LoginInterceptor(String username, String password) {
    //設(shè)置在發(fā)送請求前階段進行攔截
    super(Phase.PREPARE_SEND);
    this.username=username;
    this.password=password;
  }

  @Override
  public void handleMessage(SoapMessage soapMessage) throws Fault {
    List<Header> headers = soapMessage.getHeaders();
    Document doc = DOMUtils.createDocument();
    Element auth = doc.createElementNS("http://cxf.wolfcode.cn/","SecurityHeader");
    Element UserName = doc.createElement("username");
    Element UserPass = doc.createElement("password");

    UserName.setTextContent(username);
    UserPass.setTextContent(password);

    auth.appendChild(UserName);
    auth.appendChild(UserPass);

    headers.add(0, new Header(new QName("SecurityHeader"),auth));
  }
}

4.調(diào)用接口

/**
 * Created by sky on 2018/2/27.
 */
public class Cxfclient {
  //webservice接口地址
  private static String address = "http://localhost:8888/services/user?wsdl";

  //測試
  public static void main(String[] args) {
    test1();
    test2();
  }

  /**
   * 方式1:使用代理類工廠,需要拿到對方的接口
   */
  public static void test1() {
    try {
      // 代理工廠
      JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
      // 設(shè)置代理地址
      jaxWsProxyFactoryBean.setAddress(address);
      //添加用戶名密碼攔截器
      jaxWsProxyFactoryBean.getOutInterceptors().add(new LoginInterceptor("root","admin"));;
      // 設(shè)置接口類型
      jaxWsProxyFactoryBean.setServiceClass(AppService.class);
      // 創(chuàng)建一個代理接口實現(xiàn)
      AppService cs = (AppService) jaxWsProxyFactoryBean.create();
      // 數(shù)據(jù)準備
      String LineId = "1";
      // 調(diào)用代理接口的方法調(diào)用并返回結(jié)果
      User result = (User)cs.getUser(LineId);
      System.out.println("==============返回結(jié)果:" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 動態(tài)調(diào)用方式
   */
  public static void test2() {
    // 創(chuàng)建動態(tài)客戶端
    JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    Client client = dcf.createClient(address);
    // 需要密碼的情況需要加上用戶名和密碼
     client.getOutInterceptors().add(new LoginInterceptor("root","admin"));
    Object[] objects = new Object[0];
    try {
      // invoke("方法名",參數(shù)1,參數(shù)2,參數(shù)3....);
      System.out.println("======client"+client);
      objects = client.invoke("getUserName", "1");
      System.out.println("返回數(shù)據(jù):" + objects[0]);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

看完上述內(nèi)容,你們對怎么在springBoot中利用CXF實現(xiàn)用戶名密碼校驗有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

網(wǎng)站欄目:怎么在springBoot中利用CXF實現(xiàn)用戶名密碼校驗
網(wǎng)址分享:http://bm7419.com/article22/ijpgcc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站App設(shè)計、網(wǎng)站策劃網(wǎng)頁設(shè)計公司、靜態(tài)網(wǎng)站、域名注冊

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護公司