首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将安全验证码存储在Redis中

将安全验证码存储在Redis中
EN

Stack Overflow用户
提问于 2021-11-23 03:06:48
回答 1查看 29关注 0票数 1

我有一个WebApi项目。由于项目要求,我需要一个图形验证码注册用户。有什么有用的建议吗?此外,如何结合Redis存储在Redis.Like这个,但我需要的是数字和4 digits.Thank你的时间。enter image description here

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-23 07:49:32

我根据你的需求写了一个Demo,你可以参考它。

首先,我使用Bitmap库生成图形验证码,代码如下:

代码语言:javascript
复制
public class VerifyCodeHelper
    {
        public static Bitmap CreateVerifyCode(out string code)
        {
            //Create a Bitmap object and draw
            Bitmap bitmap = new Bitmap(200, 60);
            Graphics graph = Graphics.FromImage(bitmap);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            Random r = new Random();
            string letters = "0123456789";

            StringBuilder sb = new StringBuilder();

            //Add random 4 numbers
            for (int x = 0; x < 4; x++)
            {
                string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                sb.Append(letter);
                graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
            }
            code = sb.ToString();

            //Confuse the background
            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
                graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
            return bitmap;
        }

    }

然后创建控制器,调用API生成图形验证码。然后配置Redis:

代码语言:javascript
复制
Package Manager:
Install-Package Microsoft.Extensions.Caching.StackExchangeRedis

要集成Redis功能,请在启动文件中配置'AddStackExchangeRedisCache()‘服务。

代码语言:javascript
复制
services.AddStackExchangeRedisCache(options => {
 options.Configuration = "localhost:6379";
});

然后将IDistributedCache接口注入我们的端点控制器。

然后使用_distributedCache.SetString接收到的4位随机数将其存储在数据库中,所有代码如下:

代码语言:javascript
复制
[ApiController]
    public class VerifyCodeController : Controller
    {

        private readonly IDistributedCache _distributedCache;

        public VerifyCodeController(IDistributedCache distributedCache)
        {
            _distributedCache = distributedCache;
        }

        [Route("get_captcha")]
        public Object VerifyCode()
        {
            string code = "";
            Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out code);
           _distributedCache.SetString("code",code);

            base.HttpContext.Session.SetString("CheckCode",code);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            return File(stream.ToArray(), "image/gif");
        }

    }

整体Startup.cs配置如下所示。如果您在调用API时出错,请记得仔细检查以下配置:

代码语言:javascript
复制
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddStackExchangeRedisCache(options => {
                options.Configuration = "localhost:6379";
            });

            services.AddControllers();

            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);
            });
            // Add framework services.
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            
            app.UseRouting();

            app.UseAuthorization();
            app.UseStaticFiles();
            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

最终结果:

生成的图形验证码:

Redis数据:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70074939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档