您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)怎么在springBoot中利用CXF實(shí)現(xiàn)用戶名密碼校驗(yàn),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
準(zhǔn)備工作:
創(chuàng)建springBoot項(xiàng)目webservice_server
創(chuàng)建springBoot項(xiàng)目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ā)布的接口和實(shí)現(xiàn)類
接口:
@WebService public interface AppService { @WebMethod String getUserName(@WebParam(name = "id") String id) throws UnsupportedEncodingException; @WebMethod public User getUser(String id) throws UnsupportedEncodingException; }
實(shí)現(xiàn)類:
//name暴露的服務(wù)名稱, targetNamespace:命名空間,設(shè)置為接口的包名倒寫(xiě)(默認(rèn)是本類包名倒寫(xiě)). 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 { //默認(rèn)servlet路徑/*,如果覆寫(xiě)則按照自己定義的來(lái) @Bean public ServletRegistrationBean dispatcherServlet() { return new ServletRegistrationBean(new CXFServlet(), "/services/*"); } @Bean(name = Bus.DEFAULT_BUS_ID) public SpringBus springBus() { return new SpringBus(); } //把實(shí)現(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());//添加校驗(yàn)攔截器 endpoint.publish("/user"); return endpoint; } }
2.發(fā)布服務(wù)
@SpringBootApplication public class WebserviceApplication { public static void main(String[] args) { SpringApplication.run(WebserviceApplication.class, args); } }
因?yàn)槲姨砑恿擞脩裘兔艽a校驗(yàn)所以在發(fā)布之前還需要定義自己校驗(yàn)用戶名和密碼的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() { //定義在哪個(gè)階段進(jìn)行攔截 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,無(wú)法驗(yàn)證用戶信息")); } //獲取用戶名,密碼 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("用戶信息為空")); } } //校驗(yàn)用戶名密碼 if(!(username.equals(USERNAME) && password.equals(PASSWORD))){ SOAPException soapExc = new SOAPException("認(rèn)證失敗"); logger.debug("用戶認(rèn)證信息錯(cuò)誤"); throw new Fault(soapExc); } } }
現(xiàn)在可以發(fā)布服務(wù)了.....
發(fā)布完成后訪問(wèn)http://localhost:8888/services/user?wsdl
能夠出現(xiàn)以下界面就是發(fā)布OK
三.調(diào)用服務(wù)
1.新建調(diào)用端項(xiàng)目,添加依賴
2.因?yàn)槭纠菔玖藘煞N調(diào)用方式,其中一種需要用到接口,所以先把服務(wù)接口拷貝一份到調(diào)用端項(xiàng)目中(代碼就是上面接口的代碼)
3.因?yàn)榉?wù)端添加了用戶名密碼校驗(yàn),所以調(diào)用的時(shí)候需要添加用戶名密碼信息, 所以需要使用下面的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ā)送請(qǐng)求前階段進(jìn)行攔截 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"; //測(cè)試 public static void main(String[] args) { test1(); test2(); } /** * 方式1:使用代理類工廠,需要拿到對(duì)方的接口 */ 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)建一個(gè)代理接口實(shí)現(xiàn) AppService cs = (AppService) jaxWsProxyFactoryBean.create(); // 數(shù)據(jù)準(zhǔn)備 String LineId = "1"; // 調(diào)用代理接口的方法調(diào)用并返回結(jié)果 User result = (User)cs.getUser(LineId); System.out.println("==============返回結(jié)果:" + result); } catch (Exception e) { e.printStackTrace(); } } /** * 動(dòng)態(tài)調(diào)用方式 */ public static void test2() { // 創(chuàng)建動(dò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("返回?cái)?shù)據(jù):" + objects[0]); } catch (Exception e) { e.printStackTrace(); } } }
springboot一種全新的編程規(guī)范,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程,SpringBoot也是一個(gè)服務(wù)于框架的框架,服務(wù)范圍是簡(jiǎn)化配置文件。
看完上述內(nèi)容,你們對(duì)怎么在springBoot中利用CXF實(shí)現(xiàn)用戶名密碼校驗(yàn)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。