iServer 扩展-短信验证码登录

📅 2026/7/3 7:39:11
iServer 扩展-短信验证码登录
iServer 扩展-短信验证码登录一、开发环境配置二、具体实现2.1 扩展“短信验证码”方式实现类UserCaptchaResource 编写2.2 iServer登录页面修改三、部署3.1 后端代码部署3.2 短信验证码扩展配置3.3 登录页面配置四、测试SuperMap iServer 12.1.0.0 增强登录认证扩展能力支持在用户名密码基础上集成短信验证码等自定义校验方式。下面本文以使用阿里短信登录为例演示完整的配置过程带您为 iServer 登录加上短信验证这道安全锁。一、开发环境配置添加阿里短信服务SDK在 Maven 项目中的 pom.xml 文件添加如下依赖dependencygroupIdcom.aliyun/groupIdartifactIddypnsapi20170525/artifactIdversion2.0.0/version/dependency具体参考阿里文档https://help.aliyun.com/document_detail/378657.html添加iServer依赖在项目中按需引入 iServer 的webapps\iserver\WEB-INF\lib 目录中的文件或者整体拷贝引入需要注意检测是否会与项目中的其他jar冲突。二、具体实现iServer 实现一个扩展来说明登录认证方式的扩展流程详见iServer帮助文档扩展短信验证码登录模块文件说明2.1 扩展“短信验证码”方式实现类需要实现了UserCaptchaServiceHandler、UserCaptchaServiceApplication、UserCaptchaServiceServlet、UserCaptchaResource四个类具体作用如下UserCaptchaServiceHandler用于验证码服务基础环境的初始化建立请求路由机制;UserCaptchaServiceApplication完成REST服务框架的初始化UserCaptchaServiceServlet实现验证码服务与iServer Web容器的初始化集成UserCaptchaResource负责验证码校验业务逻辑的实现接收验证码参数执行具体的校验判断并返回验证结果。Path(“/security/userCaptcha”) 定义了扩展资源的URIPOST 短信验证码校验GET 获取验证码。其中前三个直接使用帮助文档中的代码即可只有UserCaptchaResource需要去自己去编写具体的验证码相关的逻辑因此文中仅以编写UserCaptchaResource 做说明介绍。UserCaptchaResource 编写设置阿里管理访问凭据在使用阿里云SDK时凭据信息例如AccessKey、STS Token等由Credentials工具统一管理。具体详见帮助文档https://help.aliyun.com/zh/sdk/developer-reference/v2-manage-access-credentialsStringaccessKeyId访问凭据ID;StringaccessKeySecret访问凭据密钥;publicClientcreateClient()throwsException{try{ConfigcredentialConfignewConfig();credentialConfig.setType(access_key);// 必填参数设置 AccessKey IDcredentialConfig.setAccessKeyId(accessKeyId);// 必填参数设置 AccessKey SecretcredentialConfig.setAccessKeySecret(accessKeySecret);credentialConfig.endpointdypnsapi.aliyuncs.com;com.aliyun.dypnsapi20170525.ClientcredentialClientnewcom.aliyun.dypnsapi20170525.Client(credentialConfig);returncredentialClient;}catch(Exceptione){e.printStackTrace();}returnnull;}获取验证码接口UserCaptchaResource中的GET函数用于在登录界面前端通过GET请求触发验证码的生成与发送逻辑主动获取验证信息。GETpublicStringgetCaptcha(ContextHttpServletRequestrequest,ContextHttpServletResponseresponse)throwsIOException{Stringphonerequest.getParameterValues(phone)[0];Clientclient;try{clientthis.createClient();ParamsparamsnewParams().setAction(SendSmsVerifyCode).setVersion(2017-05-25).setProtocol(HTTPS).setMethod(POST).setAuthType(AK).setStyle(RPC).setPathname(/).setReqBodyType(json).setBodyType(json);java.util.MapString,Objectqueriesnewjava.util.HashMap();queries.put(PhoneNumber,phone);// \u901f\u901a\u4e92\u8054\u9a8c\u8bc1\u7801 速通互联验证码utf-8编码防止解译错误导致前面匹配不上queries.put(SignName,\u901f\u901a\u4e92\u8054\u9a8c\u8bc1\u7801);queries.put(TemplateCode,100001);queries.put(TemplateParam,{\code\:\##code##\,\min\:\5\});// runtime optionsRuntimeOptionsruntimeOptionsnewRuntimeOptions();OpenApiRequestopenApiRequestnewOpenApiRequest().setQuery(com.aliyun.openapiutil.Client.query(queries));// 返回值实际为 Map 类型可从 Map 中获得三类数据响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。Objectrespclient.callApi(params,openApiRequest,runtimeOptions);returnSuccess;}catch(Exceptione){thrownewRuntimeException(发送验证码失败,e);}}验证验证码接口UserCaptchaResource中的GET函数用于在登录界面前端通过GET请求触发验证码的生成与发送逻辑主动获取验证信息。POSTpublicStringcheckCaptcha(ContextHttpServletRequestrequest,ContextHttpServletResponseresponse,Stringcaptcha){// 在该处实现校验逻辑captcha为请求体中传入的检验参数String[]parascaptcha.split();Stringphone;StringsmsVerifyCode;for(Stringstring:paras){if(string.contains()){String[]tmpsstring.split();if(phone.equals(tmps[0]))phonetmps[1];if(captcha.equals(tmps[0]))smsVerifyCodetmps[1];}}if(Objects.isNull(phone)||Objects.isNull(smsVerifyCode)||.equals(phone)||.equals(smsVerifyCode)){System.out.println(checkCaptcha Err: 请检测输入手机号和验证码);returnError;}else{com.aliyun.dypnsapi20170525.Clientclient;try{System.out.println(CheckSmsVerifyCode手机号phone);System.out.println(CheckSmsVerifyCode验证码smsVerifyCode);ParamsparamsnewParams()// 接口名称.setAction(CheckSmsVerifyCode)// 接口版本.setVersion(2017-05-25)// 接口协议.setProtocol(HTTPS).setMethod(POST).setAuthType(AK).setStyle(RPC).setPathname(/).setReqBodyType(json).setBodyType(json);clientthis.createClient();java.util.MapString,Objectqueriesnewjava.util.HashMap();queries.put(PhoneNumber,phone);queries.put(VerifyCode,smsVerifyCode);RuntimeOptionsruntimenewRuntimeOptions();OpenApiRequestopenApiRequestnewOpenApiRequest().setQuery(Client.query(queries));// 返回值实际为 Map 类型可从 Map 中获得三类数据响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。Objectrespclient.callApi(params,openApiRequest,runtime);System.out.println(SMS 验证码核验响应newcom.google.gson.Gson().toJson(resp));returnSuccess;}catch(Exceptione){System.err.println(SMS 验证验证码异常: e.getCause().getMessage());thrownewRuntimeException(验证验证码失败,e);}}}2.2 iServer登录页面修改通过定制登录界面增加按钮来实现发送验证码及验证机制。以基于“图形验证码”改造扩展发送“短信验证码”方式为例。在产品包根目录 %SuperMap iServer_HOME%webapps/iserver/WEB-INF/lib 的iserver-all-{版本号}.jar下位于 templates/ 下的 login_security*.ftl 文件的节点中文页面login_security_zh_CN.ftl。1、新增登录页面显示和逻辑// 页面divaligncenterwidth100%stylemargin-top:24px;position:relative;dividcaptcha-trdivstylemargin-right:auto;inputclassform-control logininputidcaptcha-phonetypetextnamephoneplaceholder请输入手机号/divbuttonidgetCaptchaButtonclassbtnonclickgetCaptcha();typebutton获取短信验证码/button/div/divdivaligncenterwidth100%stylemargin-top:24px;position:relative;display:none;idcaptcha-divdividcaptcha-trdivstylemargin-right:auto;inputclassform-control logininputidcaptcha-inputtypetextnamecaptchaplaceholder请输入验证码/div/div/div// js function getCaptcha(){ var url ${resource.rootPath}.replace(/services, ) /userCaptcha.rjson; var phone document.getElementById(captcha-phone).value; var captchadiv document.getElementById(captcha-div) $.ajax({ type: GET, url: url, async: false, dataType: text, data: { phone: phone}, success: function (msg) { console.log(msg); if (msg Success) { console.log(请求成功); captchadiv.style.display block } else { console.log(请求失败); } }, error: function (xhr, status, error) { console.error(请求失败:, error); } }); console.log(getCaptcha()) }页面效果修改建议可直接在浏览器中通过“开发者工具”调整样式待效果确认后再将修改后的样式同步至对应的 login_security*.ftl 文件中。具体参考如下2、修改ready方法... $(document).ready(function () { var captchaConfig {}; captchaConfig.enable true captchaConfig.length 6 //配置预期要获取的验证码长度 initVerificationCode(captchaConfig) //processCaptcha(); }); ...“captchaConfig.enable”处控制是否启用短信验证码登录true表示启用false不启用“captchaConfig.length”处配置获取验证码预期字符长度。3、移除原图形验证码机制相关内容... function initVerificationCode(imageCaptchaConfig) { ... // var image document.getElementById(captcha-img); // image.src getRootUrl().replace(/manager, ) security/captcha.json ?t new Date().getTime(); ... //image.onclick function () { // imageOnclick(imageCaptchaConfig, captchaInput, captchaItem, image); //}; //image.onload function () { // lastRefreshTime Date.now(); //}; }); loadLoginPage(); } ... function verifyCaptcha(captchaInput, captchaItem) { ... // var image document.getElementById(captcha-img); // image.src getRootUrl().replace(/manager, ) security/captcha.json ?t new Date().getTime(); } ...注注释/删除后需根据实际情况在函数声明“verifyCaptcha”下添加短信验证码机制相关内容。三、部署3.1 后端代码部署通过开发者工具将编写的java编译成class文件然后将其拷贝到 iserver-all-*.jar中具体位置如下图3.2 短信验证码扩展配置在产品包根目录 %SuperMap iServer_HOME%/webapps/iserver/WEB-INF/lib 的server-host-model-{版本号}.jar下位于 com/supermap/server/host/webapp 下的 handlers.xml 文件的节点util:list中添加如下内容并新增相应配置开启短信验证码扩展。util:listidbaseHandlerList...valueuserCaptchaServiceHandler/value//新增/util:list...beaniduserCaptchaServiceHandlerclasscom.supermap.server.host.webapp.handlers.HandlerInfopropertynametypevaluecom.supermap.services.security.captcha.handlers.UserCaptchaServiceHandler/propertynamepriorityvalue984//bean注priority设值时须唯一不能与已有配置重复。CaptchaServiceJaxrsResourceConfig.xml在产品包根目录 %SuperMap iServer_HOME%webapps/iserver/WEB-INF/lib 的iserver-all-{版本号}.jar下位于com/supermap/services/security/captcha/rest 下新建一个 CaptchaServiceJaxrsResourceConfig.xml 文件里面的内容如下所示?xml version1.0 encodingUTF-8?beansxmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:aophttp://www.springframework.org/schema/aopxmlns:txhttp://www.springframework.org/schema/txxmlns:jdbchttp://www.springframework.org/schema/jdbcxmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsddefault-lazy-inittrue!-- 开启注解配置 --context:annotation-config/!-- 扫描用到spring注解的包自动装配bean --context:component-scanbase-packagecom.supermap.services.security.captcha/beanidindexResourceclasscom.supermap.services.security.captcha.rest.UserCaptchaResource/beanidwebResourceConfigclassorg.glassfish.jersey.server.ResourceConfigfactory-methodforApplicationconstructor-argvalue#{new com.supermap.services.security.captcha.rest.UserCaptchaServiceApplication().register(indexResource)}//bean/beans配置文件中为 Spring 框架的配置根元素用于定义验证码服务组件的初始化配置可包含多个标签。3.3 登录页面配置打开 %SuperMap iServer_HOME%webapps/iserver/WEB-INF/lib 的iserver-all-{版本号}.jar将修改下后的ftl文件拷贝到该 jar 的 templates/ 目录中。四、测试短信认证代码https://download.csdn.net/download/qq_29109799/93058981