ASP验证码代码
ASP.NETWebApi实现Token验证

WebApi实现Token验证基于令牌的认证我们知道WEB⽹站的⾝份验证⼀般通过session或者cookie完成的,登录成功后客户端发送的任何请求都带上cookie,服务端根据客户端发送来的cookie来识别⽤户。
WEB API使⽤这样的⽅法不是很适合,于是就有了基于令牌的认证,使⽤令牌认证有⼏个好处:可扩展性、松散耦合、移动终端调⽤⽐较简单等等,别⼈都⽤上了,你还有理由不⽤吗?下⾯我们花个20分钟的时间来实现⼀个简单的WEB API token认证:Step 1:安装所需的NuGet包:打开NuGet包管理器控制台,然后输⼊如下指令:Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1Install-Package Microsoft.Owin.Cors -Version 2.1.0Install-Package EntityFramework -Version 6.0.0Step 2 在项⽬根⽬录下添加Owin“Startup”类1using System;2using System.Web.Http;34using Owin;5using Microsoft.Owin;6using Microsoft.Owin.Security.OAuth;7using SqlSugar.WebApi;89 [assembly: OwinStartup(typeof(WebApi.Startup))]10namespace WebApi11 {12public class Startup13 {14public void Configuration(IAppBuilder app)15 {16 HttpConfiguration config = new HttpConfiguration();17 ConfigureOAuth(app);1819 WebApiConfig.Register(config);20 eCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);21 eWebApi(config);22 }2324public void ConfigureOAuth(IAppBuilder app)25 {26 OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()27 {28 AllowInsecureHttp = true,29 TokenEndpointPath = new PathString("/token"),30 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),31 Provider = new SimpleAuthorizationServerProvider()32 };33 eOAuthAuthorizationServer(OAuthServerOptions);34 eOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());35 }36 }37 }View CodeStep 3:在项⽬根⽬录下添加验证类 SimpleAuthorizationServerProvider,为了简单⽤户的验证部分我们省略掉;1using System.Threading.Tasks;2using System.Security.Claims;3using Microsoft.Owin.Security.OAuth;45namespace WebApi6 {7///<summary>8/// Token验证9///</summary>10public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider11 {12public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)13 {14await Task.Factory.StartNew(() => context.Validated());15 }1617public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)18 {19await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));20/*21 * 对⽤户名、密码进⾏数据校验22 using (AuthRepository _repo = new AuthRepository())23 {24 IdentityUser user = await _repo.FindUser(erName, context.Password);2526 if (user == null)27 {28 context.SetError("invalid_grant", "The user name or password is incorrect.");29 return;30 }31 }*/3233var identity = new ClaimsIdentity(context.Options.AuthenticationType);34 identity.AddClaim(new Claim("sub", erName));35 identity.AddClaim(new Claim("role", "user"));3637 context.Validated(identity);3839 }40 }41 }View CodeStep 4:让CORS起作⽤在 Web API中启⽤OAuth的Access Token验证⾮常简单,只需在相应的Controller或Action加上[Authorize]标记1 [Authorize]2 [HttpGet, Route("product/getList")]3public List<Entity.Sys_User> GetProductList()4 {5throw new NotImplementedException();6 }View CodeStep 5 : 请求 Token获取token, POST http://localhost:23477/token参数BODY x-www-form-urlencoded 格式:grant_type=passwordusername=adminpassword=123456返回状态200 结果为Step 5 调⽤api只要在http请求头中加上Authorization:bearer Token就可以成功访问API就成功了:GET http://localhost:58192/api/testapi/testapiAuthorization : bearer T5jF97t5n-rBkWcwpiVDAlhzXtOvV7Jw2NnN1Aldc--xtDrvWtqLAN9hxJN3Fy7piIqNWeLMNm2IKVOqmmC0X5_s8MwQ6zufUDbvF4Bg5OHoHTKHX6NmZGNrU4mjpCuPLtSbT5bh_gFOZHoIXXIKmqD3Wu1MyyKKNhj9XPEIkd9bl4E9AZ1wAt4dyUxmPV结果为:。
ASP验证码生成

在Web系统中很多时候需要用到校验码,例如我们经常遇到不少电子邮件、论坛的注册过程需要我们输入校验码,这是为了提高安全性。
今天我们就来讲讲如何生成校验码。
使用来生成校验码图像很方便,网上也有不少教程与文章有介绍,但是都讲的太简单了,不够实用。
我来介绍一点自己的思路,算是抛砖引玉吧。
首先我们来看看,生成校验码的一种常见方式:1.生成校验码的字符串2.将该字符串输出为图像具体步骤下面我们就开始简单的例子来介绍这个过程,首先打开,新建一个Web Site,添加一个新的Web Form,取名为VCode.aspx,在其代码文件(VCode.aspx.vb)中添加一个函数generateVCode,此函数用于生成校验码的字符串,具体代码如下:''' <summary>''' 产生随机数(包含字母与数字)用于校验码''' </summary>''' <param name="CodeLength"></param>''' <returns></returns>''' <remarks></remarks>Private Function generateVCode(ByVal CodeLength As Integer) As StringDim VCode As String = String.EmptyDim randObj As New Random()Dim c As Integer = 63For i As Byte = 1 To CodeLengthc = randObj.Next(35)If c >= 10 Thenc += 7End Ifc += 48VCode += Chr(c)NextReturn VCodeEnd Function上面的的函数使用随机数来代表需要产生的校验码,包含数字与大写的字母。
ASP登录代码介绍

ASP登录代码介绍1(index.asp 用户登录页面)<!-- #include file="conn.asp" --><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>会员</title><style type="text/css"><!--body,td,th {font-family: 宋体;font-size: 14px;}--></style></head><body><center><p>会员注册系统</p><form name="form1" method="post" action="login.asp"><table width="34%" border="0"><tr><td width="33%" height="30">用户名:</td><td width="67%" height="30"><input name="username" type="text" id="username" size="15"></td></tr><tr><td height="30">密码:</td><td height="30"><input name="password" type="password" id="password" size="15"></td></tr><tr><td colspan="2" align="center"><input type="submit" name="Submit" value="确定"><input type="reset" name="Submit" value="重置"></td></tr><tr><td colspan="2"><a href="reg.asp" target="_self">注册</a></td></tr></table></form></center></body></html>2(login.asp 用户数据处理文件)<!-- #include file="conn.asp" --><%'打开数据库判断用户是否存在,info为表名,username为字段名set rsc=server.createobject("adodb.recordset")sqlc="select * from info where username='"&request.Form("username")&"' and password='"&request.Form("password")&"'"rsc.open sqlc,conn,1,1session("username")=rsc("username")session("password")=rsc("password")session.Timeout=30set rsc=nothingresponse.Redirect("change.asp")'如果用户不存在,session("username")为空%>3(change.asp 用户信息修改页面)<!-- #include file="conn.asp" --><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>修改</title><style type="text/css"><!--body,td,th {font-size: 14px;}--></style></head><center><body><br><%set rsc=server.createobject("adodb.recordset")sqlc="select * from info where username='"&session("username")&"' and password='"&session("password")&"'"rsc.open sqlc,conn,1,1nr=rsc("password")username=rsc("username")password=rsc("password")sex=rsc("sex")qq=rsc("qq")mail=rsc("mail")add=rsc("add")personalinfo=rsc("personalinfo")vv=rsc("ntime")set rsc=nothingif nr="" thenresponse.Redirect("index.asp")end ifif strcomp(nr,request.Form("password"))=0 thenresponse.Write("欢迎你!"&request.Form("username"))response.Write("你是在"&vv&"注册的")session("username")=request.Form("username")end ifif session("username")="" thenresponse.Redirect("index.asp")end if%><form name="form1" method="post" action="change.asp?ac=ch"><table width="39%" height="105" border="0" ><tr><td width="27%" height="30">用户名:</td><td width="73%" height="30"><input name="username" type="text" id="username" value="<%=username%>">*</td></tr><tr><td height="30">密码:</td><td height="30"><input name="password" type="text" id="password" value="<%=password%>">*</td></tr><tr><td height="30">性别:</td><td height="30"><input name="sex" type="text" id="sex" value="<%=sex%>"></td></tr><tr><td height="30">QQ:</td><td height="30"><input name="qq" type="text" id="qq" value="<%=qq%>"></td></tr><tr><td height="30">Mail:</td><td height="30"><input name="mail" type="text" id="mail" value="<%=mail%>"></td></tr><tr><td height="30">地址:</td><td height="30"><input name="add" type="text" id="add" value="<%=add%>"></td></tr><tr><td>介绍</td><td><textarea name="personalinfo" cols="30" rows="6" id="personalinfo"><%=personalinfo%></textarea></td></tr><tr><td> </td><td><input type="submit" name="Submit" value="修改"><a href="change.asp?se=y" target="_self">退出系统</a></td><% if strcomp(request.QueryString("se"),"y")=0 thensession("username")=""response.Redirect("index.asp")end if%></tr></table></form><%if strcomp(request.QueryString("ac"),"ch")=0 thenset rs=server.createobject("adodb.recordset")sql="select * from info where username='"&session("username")&"'"rs.open sql,conn,1,3rs("username")=request.Form("username")rs("password")=request.Form("password")rs("mail")=request.Form("mail")rs("sex")=request.Form("sex")rs("qq")=request.Form("qq")rs("add")=request.Form("add")rs("personalinfo")=request.Form("personalinfo")rs.updateset rs=nothingresponse.Write("修改完成!")end if%></body></center></html>4(reg.asp 新用户注册页面)<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>用户注册</title><style type="text/css"><!--body,td,th {font-family: 宋体;font-size: 14px;}--></style></head><body><center>用户注册<br><%=request.QueryString("msg")%><form name="form1" method="post" action="addnewdata.asp?ac=adduser"><table width="39%" height="105" border="0" ><tr><td width="27%" height="30">用户名:</td><td width="73%" height="30"><input name="username" type="text" id="username"> *</td></tr><tr><td height="30">密码:</td><td height="30"><input name="password" type="password" id="password">*</td></tr><tr><td height="30">确定密码:</td><td height="30"><input name="password2" type="password" id="password2">*</td></tr><tr><td height="30">性别:</td><td height="30"><input name="sex" type="text" id="sex"></td></tr><tr><td height="30">QQ:</td><td height="30"><input name="qq" type="text" id="qq"></td></tr><tr><td height="30">Mail:</td><td height="30"><input name="mail" type="text" id="mail"></td></tr><tr><td height="30">地址:</td><td height="30"><input name="add" type="text" id="add"></td></tr><tr><td>个人介绍</td><td><textarea name="personalinfo" cols="30" rows="6" id="personalinfo"></textarea></td> </tr><tr><td> </td><td><input type="submit" name="Submit" value="提交"></td></tr></table></form></center></body></html>5(addnewdata.asp 新用户注册数据处理文件)<!-- #include file="conn.asp" --><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>成功</title></head><body><%ac=request.QueryString("ac")msg="注册错误信息"if request.Form("username")="" thenmsg=msg&"<br>"&"用户名不能为空"end ifif strcomp(cstr(request.Form("password")),cstr(request.Form("password2")))<>0 thenmsg=msg&"<br>"&"两次密码输入不同"end ifif len(request.Form("password"))<6 thenmsg=msg&"<br>"&"密码太简单"end ifif strcomp(msg,"注册错误信息")>0 thenresponse.Redirect("reg.asp?msg="&msg)end ifif ac="adduser" thenset rsc=server.createobject("adodb.recordset")sql="select * from info where username='"&request.Form("username")&"'" rsc.open sql,conn,1,1ck=rsc("username")set rsc=nothingif ck<>"" thenmsg=msg&"<br>"&"用户名被人注册"response.Redirect("reg.asp?msg="&msg)end ifdsql="select * from info where id is null"set rs=server.createobject("adodb.recordset")rs.open dsql,conn,1,3rs.addnewrs("username")=request.Form("username")rs("password")=request.Form("password")rs("mail")=request.Form("mail")rs("sex")=request.Form("sex")rs("qq")=request.Form("qq")rs("add")=request.Form("add")rs("personalinfo")=request.Form("personalinfo")rs("ntime")=nowrs.updateset rs=nothing%><center><a href="index.asp" target="_self">注册成功,点击登陆</a></center><%end if%></body></html>6(conn.asp 数据库连接文件)<%'连接数据库开始dim conn,rs,sqlon error resume nextdbpath=server.mappath("userinfo.mdb")set conn=server.createobject("adodb.connection")conn.open "PROVIDER=Microsoft.jet.OLEDB.4.0;data source="&dbpath '创建记录对象set rs=server.createobject("adodb.recordset")%>7(userinfo.mdb ACCESS 数据库)在ACCESS中建一个表,然后在这个表中建立字段名称表名:info字段名称数据类型id 自动编号username 文本password 文本sex 文本quest 文本qq 文本mail 文本personalinfo 文本ntime 文本。
提取验证码 正则

提取验证码正则现如今,验证码被广泛应用于各种网络场景,用于确认用户的身份及防止恶意行为。
而在自动化程序中提取验证码也是一个常见的任务,可以通过使用正则表达式来实现。
正则表达式是一种强大的文本模式匹配工具,通过使用特定的模式来提取所需的验证码。
下面是一种常用的正则表达式,用于提取验证码:```(\d{4,6})```在这个正则表达式中,`\d`表示匹配任意一个数字,`{4,6}`表示匹配连续出现4到6个数字。
这个正则表达式可以匹配4到6位的验证码。
根据具体的情况,你可以根据验证码的长度进行相应的调整。
在使用正则表达式提取验证码时,你需要将待匹配的文本通过代码获取或者从网页中抓取,并将其存储在一个字符串中。
然后,使用编程语言中的正则表达式函数(比如Python中的re模块)进行匹配。
以下是一个使用Python实现的示例代码:```pythonimport redef extract_verification_code(text):pattern = r'(\d{4,6})'match = re.search(pattern, text)if match:return match.group(1)else:return None# 假设待匹配的文本为texttext = "验证码:123456"verification_code = extract_verification_code(text)if verification_code:print("提取到的验证码为:" + verification_code)else:print("未能提取到验证码")```通过以上代码,你可以提取文本中的验证码并进行相应的处理。
如果匹配成功,该代码将打印出提取到的验证码;否则,会输出未能提取到验证码的提示。
希望以上内容对你有所帮助,如果有任何疑问,请随时提问。
php手机短信验证代码(共9篇)

php手机短信验证代码(共9篇)篇一:短信验证码PHP代码篇二:用维泰SDK实现发送短信验证码php源码phprequire "httprequest.php";/*' 该示范程序通过:88/ 发送短信''返回值:'返回值大于0表示成功,小于0表示失败。
如果失败,返回信息还包括失败原因的文字描述。
'说明:'返回成功仅表示服务器已经成功接收客户提交的任务,并不表示对方已经收到短信。
'因移动公司对短信内容审核严格,如测试未收到,请及时联系客服'请不要发送"测试","你好","abc"等无意义的内容*/function smsend($strMobile,$strText){//发送短信的服务器地址$strServerURL = ":88/cgi/sendsmsbatch.asp";// 短信账号:免费申请,如有问题请联系QQ732055019// :88/mis/user_reg_form.asp?interest=sms.api $strUser= "username";// 验证密码: 初始密码由平台通过短信发送, 用户可登录平台自己修改$strPass= "userpass";if($strUser==""){echo ("短信帐号没有设定!");return;}if($strPass==""){echo ("短信验证密码没有设定!");return;}if($strMobile==""){echo ("短信接收号码无效!");return;}if($strText=="undefined|| $strText==""){echo ("短信内容不能为空!");return;}if(strlen($strText)69){echo ("短信内容不能超过69个字");return;}//准备表单:使用urlencode对参数进行编码,字符集gb2312 $strForm = "User=. urlencode($strUser);$strForm .= "&Pass=. urlencode($strPass);$strForm .= "&Mobile=. urlencode($strMobile);$strForm .= "&Text=. urlencode($strText);$h= new HttpRequest();$s= $h-request("GET",$strServerURL."?".$strFor m,"");if (strpos($s,"SUCCESS")===false){//出现错误echo ("短信通知发送失败!br.$s);}else {//发送成功echo("短信通知发送成功!");}}htmlheadtitle发送短信通知/titlemeta http-equiv="Content-Typecontent="text/html; charset=gb2312"/headbodybrdiv class="title1"发送短信通知/divdiv class="content1"$strMobile="132****9999";//接收短信的手机号码 $strText="Test SMS";//短信内容(不要超过69个字) smsend($strMobile,$strText);/div/body/htmlphp //httprequest.phpclass HttpRequest{var $_host;var $_uri;var $_port;var $_response;function parseURL($url){$req = $url;$pos = strpos($req, '://');$this-_protocol = strtolower(substr($req, 0, $pos));$req = substr($req, $pos+3);$pos = strpos($req, '/');if($pos === false)$pos = strlen($req);$host = substr($req, 0, $pos);if(strpos($host, ':') === false){$this-_host = $host;$this-_port = ($this-_protocol == 'https') ? 443 : 80;}else{list($this-_host, $this-_port) = explode(':', $host);}$this-_uri = substr($req, $pos);if($this-_uri == '')$this-_uri = '/';}function request($method , $url, $sPostData){$this-parseURL($url);$fp = pfsockopen( $this-_host, $this-_port, &$errno, &$errstr, 120); if( !$fp ) {echo "$errstr ($errno)br\n";return "";}if( strtoupper($method) == "GET"){fputs( $fp, "GET ".$this-_uri.HTTP/1.0\r\n"); }else if( strtoupper($method) == "POST) {fputs( $fp, "POST ".$this-_uri.HTTP/1.0\r\n"); }fputs( $fp, "Accept: */*\n");fputs( $fp, "Host: ".$this-_host."\r\n");fputs( $fp, "Connection: Close\r\n");if( strtoupper($method) == "POST) {$strlength = strlen( $data);fputs( $fp, "Content-type:application/x-www-form-urlencoded\r\n); fputs( $fp, "Content-length: ".$strlength."\r\n");fputs($fp, "\r\n");fputs( $fp, $data."\r\n");}else{fputs($fp, "\r\n");}$this-_response = "";while( !feof( $fp ) ) {$this-_response .= fgets( $fp, 4096);}fclose( $fp);$s = $this-getResponseBody();return $s;}function getResponse(){return $this-_response;}function getResponseBody(){$sKey = "\r\n\r\n";$pos = strpos($this-_response,$sKey);if($pos===false) return "";$str= substr($this-_response,$pos + 4);return $str;}}篇三:用免费短信验证码SDK实现手机注册验证功能用免费短信验证码SDK实现手机注册验证功能第一步获取短信SDK请到Mob官网下载最新版本的SDK,下载回来后解压,可以看到下面的文件结构:其中SMS_SDK.framework 为依赖库文件SMS_SDKDemo 为示例demo ,其中保存了短信SDK的演示项目代码。
PHP开发调用阿里云短信验证码的代码-直接可用

PHP开发调⽤阿⾥云短信验证码的代码-直接可⽤1:最低要求 PHP 5.62:安装了composer3:阿⾥云composer镜像地址命令(如果设置过就不需要):composer config -g repo.packagist composer https:///composer/4:安装 SDK 核⼼库 OpenAPI : Alibaba Cloud SDK for PHP 作为依赖项:composer require alibabacloud/darabonba-openapi5:阿⾥云短信SDK安装包命令(官⽅地址:https:///api-tools/sdk/Dysmsapi):composer require alibabacloud/dysmsapi-20170525 2.0.8<?php// This file is auto-generated, don't edit it. Thanks.namespace lib;use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;use Darabonba\OpenApi\Models\Config;class aliyunSms{private static $accessKeyId = 'LTAI5t7AC3RH3333pZTDCaA3';//accessKeyIdprivate static $accessKeySecret = 'ihDUcyqNZvNYXASfLtijI33333NSk';//accessKeySecretprivate static $signName = 'xxxx技有限公司';//签名private static $templateCode = 'SMS_228533331';//模板代码/*** 使⽤AK&SK初始化账号Client* @param string $accessKeyId* @param string $accessKeySecret* @return Dysmsapi Client*/private static function createClient($accessKeyId, $accessKeySecret){$config = new Config([// 您的AccessKey ID"accessKeyId" => $accessKeyId,// 您的AccessKey Secret"accessKeySecret" => $accessKeySecret]);// 访问的域名$config->endpoint = "";return new Dysmsapi($config);}/*** @param string $phoneNumbers ⼿机号* @param string $code 验证码* @return void*/// public static function main($args)private static function main($phoneNumbers, $code){$client = self::createClient(self::$accessKeyId, self::$accessKeySecret);$sendSmsRequest = new SendSmsRequest(["templateParam" => "{\"code\":\"{$code}\"}","phoneNumbers" => "{$phoneNumbers}","signName" => self::$signName,"templateCode" => self::$templateCode]);$ali_res = $client->sendSms($sendSmsRequest);if ($ali_res->body->code == 'OK' && $ali_res->body->bizId != NULL) {return true;}switch ($ali_res->body->code) {case 'isv.BUSINESS_LIMIT_CONTROL':exception('短信发送频繁,请稍候再试');//tp的抛出错误,换成你⾃⼰的报错break;case 'isv.TEMPLATE_PARAMS_ILLEGAL':exception('短信验证码不符合变量规范');//tp的抛出错误,换成你⾃⼰的报错break;case 'isv.MOBILE_NUMBER_ILLEGAL':exception('⼿机号不正确,⽆法发送短信');//tp的抛出错误,换成你⾃⼰的报错break;}//少见的错误,记录下来//log_err($ali_res->body, '发送短信发⽣错误', 'ali_sms');//换成你的exception($ali_res->body->message);//tp的抛出错误,换成你⾃⼰的报错// 以下是阿⾥云短信正确和失败返回的数据,以作参考// 失败演⽰返回数据/* object(AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponseBody)#81 (6) {["bizId"] => NULL["code"] => string(24) "isv.SMS_TEMPLATE_ILLEGAL"["message"] => string(38) "模板不合法(不存在或被拉⿊)"["requestId"] => string(36) "21A90D61-2D5E-533D-BFE7-9D16F8312A0E"["_name":protected] => array(4) {["bizId"] => string(5) "BizId"["code"] => string(4) "Code"["message"] => string(7) "Message"["requestId"] => string(9) "RequestId"}["_required":protected] => array(0) {}}*/// 成功返回数据演⽰/* object(AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponseBody)#81 (6) {["bizId"] => string(20) "839015438514162136^0"["code"] => string(2) "OK"["message"] => string(2) "OK"["requestId"] => string(36) "EA37C2B7-E427-59F8-8B7C-06AD846A5439"["_name":protected] => array(4) {["bizId"] => string(5) "BizId"["code"] => string(4) "Code"["message"] => string(7) "Message"["requestId"] => string(9) "RequestId"}["_required":protected] => array(0) {}}*/}//发短信public static function sendSms($phoneNumbers, $code){$res = self::main($phoneNumbers, $code);return $res;}}此代码只需要修改命名空间和阿⾥云accessKeyId等相关信息,即可使⽤~exception是TP的错误异常抛出,我是做了全局的异常托管,并且在所有报错的地⽅调⽤此⽅法就能终端代码,报出错误,你只需要换成你的中断代码返回错误即可。
微信企业号主动推送文本消息的ASP代码

'ASP文件需要以UTF-8的格式保存,否则乱码.'以下两行代码是为了通过微信接口验证的。
'response.write request("echostr")'response.enddim signature '微信加密签名dim timestamp '时间戳dim nonce '随机数'dim echostr '随机字符串dim Tokendim signaturetmptoken="xxxxxxxxxxxxxxxx" '您在后台添写的tokensignature = Request("signature")nonce = Request("nonce")timestamp = Request("timestamp")dim ToUserName '开发者微信号dim FromUserName'发送方帐号(一个OpenID)dim CreateTime '消息创建时间(整型)dim MsgType 'textdim Content '文本消息内容dim MsgId '消息id,64位整型set xml_dom = Server.CreateObject("MSXML2.DOMDocument")'此处根据您的实际服务器情况改写xml_dom.load requestToUserName=xml_dom.getElementsByTagName_r("ToUserName").item(0).text FromUserName=xml_dom.getElementsByTagName_r("FromUserName").item(0).text MsgType=xml_dom.getElementsByTagName_r("MsgType").item(0).textif MsgType="text" thenContent=xml_dom.getElementsByTagName_r("Content").item(0).textend ifset xml_dom=Nothingdim mingling,mlidmingling=replace(content,chr(13),"")mingling=trim(replace(mingling,chr(10),""))If IsNumeric(mingling) Then'如果是数字returnstr= FromUserName'这里添加您的回复代码else '非数字if mingling="Hello2BizUser" then '表示为新的用户关注,被关注后发布returnstr="欢迎关注<我的工资条>"&VBCrLf &_"快告诉你的Boss,下载“飞信工资条”软件可以将工资条群发到手机上啦!"elsereturnstr="快告诉你的Boss,下载“飞信工资条”软件可以将工资条群发到手机上啦!" end ifend ifif len(returnstr)=0 thenreturnstr="个人微信号/QQ:35491331"&VBCrLfend if'returnstr=returnstr&"帮助回复数字0 "strresponse="" &_""&fromusername&"" &_""&tousername&"" &_""&now&"" &_"text" &_"" & returnstr & "" &_"0" &_""response.write strresponse。
asp.netcore配合vue实现后端验证码逻辑

core配合vue实现后端验证码逻辑⽬录概述部分原理源码概述⽹上的前端验证码逻辑总感觉不安全,验证码建议还是使⽤后端配合验证。
如果产品确定可以上⽹的话,就可以使⽤腾讯,百度等第三⽅验证,对接⽅便。
但是产品可能内⽹部署,就必须⾃⼰写了。
本⽂章就是基于这⼀点来实现的。
前端验证码显⽰⼀个图⽚,后端⽣成图⽚。
部分原理1.前端调⽤⽣端获取图⽚时,传⼊⼀个roomID,后端⽣成⼀个4位验征码,放⼊redis中。
然后⽣成⼀个图⽚返回。
2.前端显⽰图⽚,登录时将roomID和填写的验证码,⼀并提交,登录接⼝根据roomId从redis中取出验证码判断是否正确。
这样就相当于后端验证了。
⼤家觉得有问题什么,可以进⾏评论。
谢谢。
源码前端部分代码<template><div class="login-container"><vue-particlescolor="#ffffff":particleOpacity="0.7":particlesNumber="50"shapeType="circle":particleSize="4"linesColor="#dedede":linesWidth="1":lineLinked="true":lineOpacity="0.4":linesDistance="150":moveSpeed="2":hoverEffect="true"hoverMode="grab":clickEffect="true"clickMode="push"></vue-particles><el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left"><div class="title-container"><h3 class="title">智能综合管理系统</h3></div><el-form-item prop="username"><span class="svg-container"><svg-icon icon-class="user" /></span><el-input ref="username" v-model="ername" placeholder="⽤户名" name="username" type="text" tabindex="1" autocomplete="on" /> </el-form-item><el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual><el-form-item prop="password"><span class="svg-container"><svg-icon icon-class="password" /></span><el-input:key="passwordType"ref="password"v-model="loginForm.password":type="passwordType"placeholder="密码"name="password"tabindex="2"autocomplete="on"@keyup.native="checkCapslock"@blur="capsTooltip = false"@keyup.enter.native="handleLogin"/><span class="show-pwd" @click="showPwd"><svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /></span></el-form-item></el-tooltip><el-form-item prop="yzm"><span class="svg-container"><svg-icon icon-class="password" /></span><el-input type="text" v-model="loginForm.verifyCode" maxlength="4" placeholder="验证码" /><div class="identifyCode" @click="refreshCode"><el-image :src="verifyImageUrl"></el-image></div></el-form-item><el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px" @click.native.prevent="handleLogin">登录</el-button> </el-form></div></template><script>import { validUsername } from '@/utils/validate'import Identify from './components/Identify'import { uuid } from 'vue-uuid'; // uuid object is also exported to things// outside Vue instance.export default {name: 'Login',components: { Identify },data() {const validateUsername = (rule, value, callback) => {if (!validUsername(value)) {callback(new Error('请输⼊正确的⽤户名'))} else {callback()}}const validatePassword = (rule, value, callback) => {if (value.length < 6) {callback(new Error('密码最少6位'))} else {callback()}}return {loginForm: {username: 'admin',password: '111111',roomId: '',verifyCode: ''},loginRules: {username: [{ required: true, trigger: 'blur', validator: validateUsername }],password: [{ required: true, trigger: 'blur', validator: validatePassword }]},passwordType: 'password',capsTooltip: false,loading: false,showDialog: false,redirect: undefined,otherQuery: {},identifyCodes: '1234567890',identifyCode: '',// verifyImageRoomId: '',verifyImageUrl: '',}},watch: {$route: {handler: function (route) {const query = route.queryif (query) {this.redirect = query.redirectthis.otherQuery = this.getOtherQuery(query)}},immediate: true}},created() {// window.addEventListener('storage', this.afterQRScan)// this.identifyCode = ''// this.makeCode(this.identifyCodes, 4)this.refreshCode()},mounted() {if (ername === '') {this.$ername.focus()} else if (this.loginForm.password === '') {this.$refs.password.focus()}},destroyed() {// window.removeEventListener('storage', this.afterQRScan)},methods: {checkCapslock(e) {const { key } = ethis.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')},showPwd() {if (this.passwordType === 'password') {this.passwordType = ''} else {this.passwordType = 'password'}this.$nextTick(() => {this.$refs.password.focus()})},createUuid() {let uuidV4 = uuid.v4().replace('-', '').replace('-', '').replace('-', '').replace('-', '')this.verifyImageRoomId = uuidV4this.verifyImageUrl = '/api/Operator/getCaptchaImage/120/40/' + this.verifyImageRoomId console.log(uuidV4)},handleLogin() {this.$refs.loginForm.validate(valid => {if (valid) {this.loading = truethis.$store.dispatch('user/login', this.loginForm).then(() => {this.$router.push({ path: this.redirect || '/', query: this.otherQuery })this.loading = false}).catch(() => {this.loading = false})} else {console.log('error submit!!')return false}})},getOtherQuery(query) {return Object.keys(query).reduce((acc, cur) => {if (cur !== 'redirect') {acc[cur] = query[cur]}return acc}, {})},// ⽣成随机数randomNum(min, max) {return Math.floor(Math.random() * (max - min) + min)},// 切换验证码refreshCode() {let uuidV4 = uuid.v4().replace('-', '').replace('-', '').replace('-', '').replace('-', '')this.loginForm.roomId = uuidV4this.verifyImageUrl = '/api/Operator/getCaptchaImage/120/40/' + this.loginForm.roomId console.log(uuidV4)},// ⽣成四位随机验证码makeCode(o, l) {for (let i = 0; i < l; i++) {this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]}console.log(this.identifyCode)}}}</script><style lang="scss">/* 修复input 背景不协调和光标变⾊ *//* Detail see https:///PanJiaChen/vue-element-admin/pull/927 */ $bg: #283443;$light_gray: #fff;$cursor: #fff;@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {.login-container .el-input input {color: $cursor;}}/* reset element-ui css */.login-container {background: url("~@/assets/background.jpg") no-repeat;min-height: 100vh;.el-input {display: inline-block;height: 47px;width: 85%;input {background: transparent;border: 0px;-webkit-appearance: none;border-radius: 0px;padding: 12px 5px 12px 15px;color: $light_gray;height: 47px;caret-color: $cursor;&:-webkit-autofill {box-shadow: 0 0 0px 1000px $bg inset !important;-webkit-text-fill-color: $cursor !important;}}}.el-form-item {border: 1px solid rgba(255, 255, 255, 0.1);background: rgba(0, 0, 0, 0.1);border-radius: 5px;color: #454545;.el-form-item__error {color: rgb(223, 223, 176);}}}</style><style lang="scss" scoped>$bg: #2d3a4b;$dark_gray: #889aa4;$light_gray: #eee;.login-container {min-height: 100%;width: 100%;background-color: $bg;overflow: hidden;.login-form {position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;width: 520px;max-width: 100%;padding: 160px 35px 0;margin: 0 auto;overflow: hidden;}.tips {font-size: 14px;color: #fff;margin-bottom: 10px;span {&:first-of-type {margin-right: 16px;}}}.svg-container {padding: 6px 5px 6px 15px;color: $dark_gray;vertical-align: middle;width: 30px;display: inline-block;}.title-container {position: relative;.title {font-size: 42px;color: $light_gray;margin: 0px auto 40px auto;text-align: center;font-weight: bold;}}.show-pwd {position: absolute;right: 10px;top: 7px;font-size: 16px;color: $dark_gray;cursor: pointer;user-select: none;}.identifyCode {position: absolute;right: 10px;top: 5px;}.thirdparty-button {position: absolute;right: 0;bottom: 6px;}@media only screen and (max-width: 470px) {.thirdparty-button {display: none;}}}</style>后端接⼝/// <summary>/// 获取验证码/// </summary>/// <returns></returns>[HttpGet("getCaptchaImage/{width:int}/{height:int}/{roomId}")]public IActionResult GetCaptchaImage(int width, int height, string roomId){Console.WriteLine(roomId);//int width = 100;//int height = 36;var captchaCode = Captcha.GenerateCaptchaCode();var result = Captcha.GenerateCaptchaImage(width, height, captchaCode);string redisKey = "VerifyCode_" + roomId;Startup.redisDb.StringSet(redisKey, captchaCode, new TimeSpan(0, 5, 0));Stream s = new MemoryStream(result.CaptchaByteData);return new FileStreamResult(s, "image/png");}/// <summary>/// 登录/// </summary>/// <returns></returns>[HttpPost("login")]public ApiResponseData Login(LoginDto loginInfo){if (string.IsNullOrWhiteSpace(ername))return ApiResponse.Error("⽤户名不能为空");if (string.IsNullOrWhiteSpace(loginInfo.password))return ApiResponse.Error("密码不能为空");Entity.BaseOperator operInfo = Db.Select<BaseOperator>().Where(a => a.OperatorCode == ername && a.Password == loginInfo.password.ToLower() && a.Status == 1 && a.IsDel == false).ToOne(); if (operInfo == null)return ApiResponse.Error("⽤户名或者密码不正确");bool verifyResult = Captcha.ValidateCaptchaCode(loginInfo.RoomId, loginInfo.VerifyCode);if(verifyResult == false)return ApiResponse.Error("验证码不正确");//登录时重新⽣成token,⼀个⽤户只能在⼀个地⽅登录string token = System.Guid.NewGuid().ToString().Replace("-", "");Db.Update<BaseOperator>(operInfo.OperatorId).Set(a => a.Token, token).ExecuteAffrows();dynamic outJson = new ExpandoObject();//初始化⼀个不包含任何成员的ExpandoObjectoutJson.token = token;//存⼊redisstring redisKey = "UserInfo_" + token;Startup.redisDb.StringSet(redisKey, operInfo.OperatorId, new TimeSpan(24, 0, 0));return ApiResponse.Succ(outJson);}到此这篇关于 core配合vue实现后端验证码逻辑的⽂章就介绍到这了,更多相关 core验证码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
g.DrawString(R.rand, font, blackbrush, 20, 10);
Response.ContentType = "image/jpeg";
image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//输出图片;
public int x,y,p,q;
public int r, g, b;
protected void draw()
{
Rand R = new Rand();
Session["image"] = R.rand;
Bitmap image = new Bitmap(100, 50);//创建画布;
Graphics g = Graphics.FromImage(image);//创建画图对象;
g.Clear(Color.Black);
SolidBrush blackbrush = new SolidBrush(Color.White);
Font font = new Font("Verdana", 14);
for (int i = 0; i < 100; i++)
{
this.x = ran.Next(0, 100);
<html xmlns="/1999/xhtml">
<head runat="server">
<title>CheckImage</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="CreateImage.aspx" align="middle" />
this.y = ran.Next(0, 50);
this.p = ran.Next(0, 100);
this.q = ran.Next(0, 50);
this.r = ran.Next(0, 256);
this.g = ran.Next(0, 256);
this.b = ran.Next(0, 256);
/// <returns></returns>
public string CreateCode(int codeLength)
{
string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
blackbrush.Dispose();//释放画笔;
g.Dispose();//释放绘图对象;
image.Dispose();//释放图形对象;
}
protected void Page_Load(object sender, EventArgs e)
{
draw();
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateImage.aspx.cs" Inherits="CreateImage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd">
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HTMLControls;
using System.Web.UI.WebControls;
int x2 = rand.Next(image.Height);
int y1 = rand.Next(image.Width);
int y2 = rand.Next(image.Height);
g.DrawLine(new Pen(Color.LightGray), x1, y1, x2, y2);
g.DrawString(code, font, brush, 0, 0);
//画图片的前景噪音
for (int i = 0; i < 10; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
image.SetPixel(x, y, Color.White);
}
//新建字体
Font font = new Font("Arial", 15, FontStyle.Bold | FontStyle.Italic);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Gray, 1.2f, true);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
#region Web窗体设计器生成的代码
override protected void OnInit(EventArgs e)
public void CreateImages(string code)
{
//创建一个Bitmap新实例
Bitmap image = new Bitmap(60, 20);
Graphics g = Graphics.FromImage(image);
WebColorConverter ww = new WebColorConverter();
</div>
</form>
</body>
</html>
using System;
usinSystem.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
{
this.rand += ran.Next(0, 16).ToString("x1");
}
HttpContext.Current.Session.Add("code",this.rand);
}
}
public partial class image : System.Web.UI.Page
{
Random ran = new Random(lisecond);//加个随机数种子
在ASP页面中生成图片验证码,需要用到System.Drawing命名空间下的很多类,首先我们需要新建一个CreateImage.aspx页面,在后台代码中定义用于生成验证码图片的方法,如下:
using System;
using System.Collections;
using System.Configuration;
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Pen pen = new Pen(Color.FromArgb(this.r, this.g, this.b));
g.DrawLine(pen, this.x, this.y, this.x, this.y + 1);
//g.DrawLine(pen, this.x, this.y, this.x + this.p, this.y + this.q);
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
以上是CreateImage.aspx文件的后台代码,完成上述方法后,在页面里调用方法,只需要添加<img src="CreateImage.aspx" align="middle" />,即可显示生成的验证码图片,每次刷新都会随机产生不同的验证码,如下:
{
//
// CODEGEN:该调用是 Web窗体设计器所必需的。