首页 > 编程语言 >C# 实现身份验证之WebApi篇

C# 实现身份验证之WebApi篇

时间:2023-08-03 18:55:11浏览次数:53  
标签:WebApi string C# 身份验证 System new using response public

【转】https://www.cnblogs.com/zhaoshujie/p/9761005.html

今天再来总结关于如何实现WebApi的身份验证,以完成该系列所有文章,WebApi常见的实现方式有:FORM身份验证、集成WINDOWS验证、Basic基础认证、Digest摘要认证

 第一种:FORM身份验证(若在ASP.NET应用程序使用,则该验证方式不支持跨域,因为cookie无法跨域访问)

1.定义一个FormAuthenticationFilterAttribute,该类继承自AuthorizationFilterAttribute,并重写其OnAuthorization,在该方法中添加从请求头中获取有无登录的Cookie,若有则表示登录成功,否则失败,代码如下:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Security;
using System.Net.Http;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Threading;
using System.Security.Principal;
using System.Net;
using System.Text;
 
namespace WebApplication1.Models
{
    public class FormAuthenticationFilterAttribute : AuthorizationFilterAttribute
    {
        private const string UnauthorizedMessage = "请求未授权,拒绝访问。";
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)
            {
                base.OnAuthorization(actionContext);
                return;
            }
 
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.OnAuthorization(actionContext);
                return;
            }
 
            var cookies = actionContext.Request.Headers.GetCookies();
            if (cookies == null || cookies.Count < 1)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(UnauthorizedMessage, Encoding.UTF8) };
                return;
            }
 
            FormsAuthenticationTicket ticket = GetTicket(cookies);
            if (ticket == null)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(UnauthorizedMessage, Encoding.UTF8) };
                return;
            }
 
            //这里可以对FormsAuthenticationTicket对象进行进一步验证
 
            var principal = new GenericPrincipal(new FormsIdentity(ticket), null);
            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = principal;
 
            base.OnAuthorization(actionContext);
        }
 
        private FormsAuthenticationTicket GetTicket(Collection<CookieHeaderValue> cookies)
        {
            FormsAuthenticationTicket ticket = null;
            foreach (var item in cookies)
            {
                var cookie = item.Cookies.SingleOrDefault(c => c.Name == FormsAuthentication.FormsCookieName);
                if (cookie != null)
                {
                    ticket = FormsAuthentication.Decrypt(cookie.Value);
                    break;
                }
            }
            return ticket;
        }
    }
}
复制代码

2.在需要认证授权后才能访问的Controller中类或ACTION方法上添加上述授权过滤器FormAuthenticationFilterAttribute,也可在global文件中将该类添加到全局过滤器中,同时定义一个登录ACTION,用于登录入口,示例代码如下:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using WebApplication1.Models;
 
namespace WebApplication1.Controllers
{
    [FormAuthenticationFilter]
    public class TestController : ApiController
    {
 
        [AllowAnonymous]
        [AcceptVerbs("Get")]
        [Route("Api/Test/Login")]
        public HttpResponseMessage Login(string uname, string pwd)
        {
            if ("admin".Equals(uname, StringComparison.OrdinalIgnoreCase) && "api.admin".Equals(pwd))
            {
                //创建票据
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, uname, DateTime.Now, DateTime.Now.AddMinutes(30), false, string.Empty);
                //加密票据
                string authTicket = FormsAuthentication.Encrypt(ticket);
                //存储为cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);
                cookie.Path = FormsAuthentication.FormsCookiePath;
                HttpContext.Current.Response.AppendCookie(cookie);
 
                //或者
                //FormsAuthentication.SetAuthCookie(uname, false, "/");
 
                return Request.CreateResponse(HttpStatusCode.OK, "登录成功!");
            }
            else
            {
                HttpContext.Current.Response.AppendCookie(new HttpCookie(FormsAuthentication.FormsCookieName) { Expires = DateTime.Now.AddDays(-10) });//测试用:当登录失败时,清除可能存在的身份验证Cookie
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "登录失败,无效的用户名或密码!");
            }
 
        }
 
        // GET api/test
        public IEnumerable<string> GetValues()
        {
            return new string[] { "value1", "value2" };
        }
 
        // GET api/test/5
        public string GetValue(int id)
        {
            return "value";
        }
    }
}
复制代码

测试用法一:可直接在浏览器中访问需要授权的方法(即:Login除外),如:http://localhost:11099/api/test/,响应结果如下:

请求头信息如下:

若成功调用Login方法后(http://localhost:11099/api/test/login?uname=admin&pwd=api.admin),再调用上述方法,则可以获得正常的结果,如下图示:

看一下请求时附带的Cookie,如下图示:

测试用法二:采用HttpClient来调用Api的相关方法,示例代码如下:

复制代码
public async static void TestLoginApi()
{
    HttpClientHandler handler = new HttpClientHandler();
    handler.UseCookies = true;//因为采用Form验证,所以需要使用Cookie来记录身份登录信息
    HttpClient client = new HttpClient(handler);
 
    Console.WriteLine("Login>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    var response = await client.GetAsync("http://localhost:11099/api/test/login/?uname=admin&pwd=api.admin");
    var r = await response.Content.ReadAsAsync<dynamic>();
    Console.WriteLine("StatusCode:{0}", response.StatusCode);
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine("Msg:{1}", response.StatusCode, r.Message);
        return;
    }
    Console.WriteLine("Msg:{1}", response.StatusCode, r);
 
    var getCookies = handler.CookieContainer.GetCookies(new Uri("http://localhost:11099/"));
    Console.WriteLine("获取到的cookie数量:" + getCookies.Count);
    Console.WriteLine("获取到的cookie:");
    for (int i = 0; i < getCookies.Count; i++)
    {
        Console.WriteLine(getCookies[i].Name + ":" + getCookies[i].Value);
    }
 
 
    Console.WriteLine("GetValues>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    response = await client.GetAsync("http://localhost:11099/api/test/");
    var r2 = await response.Content.ReadAsAsync<IEnumerable<string>>();
    foreach (string item in r2)
    {
        Console.WriteLine("GetValues - Item Value:{0}", item);
    }
 
    Console.WriteLine("GetValue>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    response = await client.GetAsync("http://localhost:11099/api/test/8");
    var r3 = await response.Content.ReadAsAsync<string>();
    Console.WriteLine("GetValue - Item Value:{0}", r3);
}
复制代码

结果如下图示:

 如果Web Api作为ASP.NET 或MVC的一部份使用,那么完全可以采用基于默认的FORM身份验证授权特性(Authorize),或采用web.config中配置,这个很简单,就不作说明了,大家可以网上参考关于ASP.NET 或ASP.NET MVC的FORM身份验证。

第二种:集成WINDOWS验证

首先在WEB.CONFIG文件中,增加如下配置,以开启WINDOWS身份验证,配置如下:

<authentication mode="Windows">
</authentication>

然后在需要认证授权后才能访问的Controller中类或ACTION方法上添加Authorize特性,Controller与上文相同不再贴出,当然也可以在WEB.CONFIG中配置:

<authorization>
  <deny users="?"/>
</authorization>

最后将WEB API寄宿到(或者说发布到)IIS,且需要在IIS中启用WINDOWS身份验证,如下图示:

这样就完成了该身份验证模式(理论上WEB服务、WCF若都以IIS为宿主,都可以采用集成WINDOWS身份验证模式),测试方法很简单,第一种直接在浏览器中访问,第二种采用HttpClient来调用WEB API,示例代码如下:

复制代码
public async static void TestLoginApi2()
{
    HttpClientHandler handler = new HttpClientHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.Credentials = new NetworkCredential("admin", "www.zuowenjun.cn");
    HttpClient client = new HttpClient(handler);
 
    var response = await client.GetAsync("http://localhost:8010/api/test/");
    var r2 = await response.Content.ReadAsAsync<IEnumerable<string>>();
    foreach (string item in r2)
    {
        Console.WriteLine("GetValues - Item Value:{0}", item);
    }
 
    response = await client.GetAsync("http://localhost:8010/api/test/8");
    var r3 = await response.Content.ReadAsAsync<string>();
    Console.WriteLine("GetValue - Item Value:{0}", r3);
}
复制代码

第三种:Basic基础认证

1.定义一个继承自AuthorizationFilterAttribute的HttpBasicAuthenticationFilter类,用于实现Basic基础认证,实现代码如下:

复制代码
using System;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
using System.Web.Http;
using System.Security.Principal;
using System.Threading;
using System.Net.Http.Headers;
 
namespace WebApplication1.Models
{
    public class HttpBasicAuthenticationFilter : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)
            {
                base.OnAuthorization(actionContext);
                return;
            }
 
            if (Thread.CurrentPrincipal != null && Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                base.OnAuthorization(actionContext);
                return;
            }
 
            string authParameter = null;
 
            var authValue = actionContext.Request.Headers.Authorization;
            if (authValue != null && authValue.Scheme == "Basic")
            {
                authParameter = authValue.Parameter;  //authparameter:获取请求中经过Base64编码的(用户:密码)
            }
 
            if (string.IsNullOrEmpty(authParameter))
            {
                Challenge(actionContext);
                return;
            }
 
            authParameter = Encoding.Default.GetString(Convert.FromBase64String(authParameter));
 
            var authToken = authParameter.Split(':');
            if (authToken.Length < 2)
            {
                Challenge(actionContext);
                return;
            }
 
            if (!ValidateUser(authToken[0], authToken[1]))
            {
                Challenge(actionContext);
                return;
            }
 
            var principal = new GenericPrincipal(new GenericIdentity(authToken[0]), null);
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
 
            base.OnAuthorization(actionContext);
        }
 
        private void Challenge(HttpActionContext actionContext)
        {
            var host = actionContext.Request.RequestUri.DnsSafeHost;
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "请求未授权,拒绝访问。");
            //actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host));//可以使用如下语句
            actionContext.Response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", string.Format("realm=\"{0}\"", host)));
        }
 
        protected virtual bool ValidateUser(string userName, string password)
        {
            if (userName.Equals("admin", StringComparison.OrdinalIgnoreCase) && password.Equals("api.admin")) //判断用户名及密码,实际可从数据库查询验证,可重写
            {
                return true;
            }
            return false;
        }
 
    }
}
复制代码

2.在需要认证授权后才能访问的Controller中类或ACTION方法上添加上述定义的类HttpBasicAuthenticationFilter,也可在global文件中将该类添加到全局过滤器中,即可

测试方法很简单,第一种直接在浏览器中访问(同上),第二种采用HttpClient来调用WEB API,示例代码如下:

复制代码
public async static void TestLoginApi3()
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = CreateBasicHeader("admin", "api.admin");
 
    var response = await client.GetAsync("http://localhost:11099/api/test/");
    var r2 = await response.Content.ReadAsAsync<IEnumerable<string>>();
    foreach (string item in r2)
    {
        Console.WriteLine("GetValues - Item Value:{0}", item);
    }
 
    response = await client.GetAsync("http://localhost:11099/api/test/8");
    var r3 = await response.Content.ReadAsAsync<string>();
    Console.WriteLine("GetValue - Item Value:{0}", r3);
}
 
public static AuthenticationHeaderValue CreateBasicHeader(string username, string password)
{
    return new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));
}
复制代码

实现Basic基础认证,除了通过继承自AuthorizationFilterAttribute来实现自定义的验证授权过滤器外,还可以通过继承自DelegatingHandler来实现自定义的消息处理管道类,具体的实现方式可参见园子里的这篇文章:

http://www.cnblogs.com/CreateMyself/p/4857799.html

 第四种:Digest摘要认证

 1.定义一个继承自DelegatingHandler的HttpDigestAuthenticationHandler类,用于实现在消息管道中实现Digest摘要认证,同时定义该类所需关联或依赖的其它类,源代码如下:

复制代码
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
 
namespace WebApplication1.Models
{
 
    public class HttpDigestAuthenticationHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                HttpRequestHeaders headers = request.Headers;
                if (headers.Authorization != null)
                {
                    Header header = new Header(request.Headers.Authorization.Parameter, request.Method.Method);
 
                    if (Nonce.IsValid(header.Nonce, header.NounceCounter))
                    {
                        string password = "www.zuowenjun.cn";//默认值
 
                        //根据用户名获取正确的密码,实际情况应该从数据库查询
                        if (header.UserName.Equals("admin", StringComparison.OrdinalIgnoreCase))
                        {
                            password = "api.admin";//这里模拟获取到的正确的密码
                        }
 
                        #region 计算正确的可授权的Hash值
 
                        string ha1 = String.Format("{0}:{1}:{2}", header.UserName, header.Realm, password).ToMD5Hash();
 
                        string ha2 = String.Format("{0}:{1}", header.Method, header.Uri).ToMD5Hash();
 
                        string computedResponse = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
                                            ha1, header.Nonce, header.NounceCounter, header.Cnonce, "auth", ha2).ToMD5Hash();
                        #endregion
 
                        if (String.CompareOrdinal(header.Response, computedResponse) == 0) //比较请求的Hash值与正确的可授权的Hash值是否相同,相则则表示验证通过,否则失败
                        {
                            // digest computed matches the value sent by client in the response field.
                            // Looks like an authentic client! Create a principal.
                            //    var claims = new List<Claim>
                            //{
                            //                new Claim(ClaimTypes.Name, header.UserName),
                            //                new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)
                            //};
 
                            //    ClaimsPrincipal principal = new ClaimsPrincipal(new[] { new ClaimsIdentity(claims, "Digest") });
 
                            //    Thread.CurrentPrincipal = principal;
 
                            //    if (HttpContext.Current != null)
                            //        HttpContext.Current.User = principal;
 
                            var principal = new GenericPrincipal(new GenericIdentity(header.UserName), null);
                            Thread.CurrentPrincipal = principal;
                            if (HttpContext.Current != null)
                            {
                                HttpContext.Current.User = principal;
                            }
                        }
                    }
                }
 
                HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
 
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Digest", Header.GetUnauthorizedResponseHeader(request).ToString()));
                }
 
                return response;
            }
            catch (Exception)
            {
                var response = request.CreateResponse(HttpStatusCode.Unauthorized);
                response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Digest", Header.GetUnauthorizedResponseHeader(request).ToString()));
 
                return response;
            }
        }
    }
 
 
 
 
    public class Header
    {
        public Header() { }
 
        public Header(string header, string method)
        {
            string keyValuePairs = header.Replace("\"", String.Empty);
 
            foreach (string keyValuePair in keyValuePairs.Split(','))
            {
                int index = keyValuePair.IndexOf("=", System.StringComparison.Ordinal);
                string key = keyValuePair.Substring(0, index).Trim();
                string value = keyValuePair.Substring(index + 1).Trim();
 
                switch (key)
                {
                    case "username": this.UserName = value; break;
                    case "realm": this.Realm = value; break;
                    case "nonce": this.Nonce = value; break;
                    case "uri": this.Uri = value; break;
                    case "nc": this.NounceCounter = value; break;
                    case "cnonce": this.Cnonce = value; break;
                    case "response": this.Response = value; break;
                    case "method": this.Method = value; break;
                }
            }
 
            if (String.IsNullOrEmpty(this.Method))
                this.Method = method;
        }
 
        public string Cnonce { get; private set; }
        public string Nonce { get; private set; }
        public string Realm { get; private set; }
        public string UserName { get; private set; }
        public string Uri { get; private set; }
        public string Response { get; private set; }
        public string Method { get; private set; }
        public string NounceCounter { get; private set; }
 
        // This property is used by the handler to generate a
        // nonce and get it ready to be packaged in the
        // WWW-Authenticate header, as part of 401 response
        public static Header GetUnauthorizedResponseHeader(HttpRequestMessage request)
        {
            var host = request.RequestUri.DnsSafeHost;
            return new Header()
            {
                Realm = host,
                Nonce = WebApplication1.Models.Nonce.Generate()
            };
        }
 
        public override string ToString()
        {
            StringBuilder header = new StringBuilder();
            header.AppendFormat("realm=\"{0}\"", Realm);
            header.AppendFormat(",nonce=\"{0}\"", Nonce);
            header.AppendFormat(",qop=\"{0}\"", "auth");
            return header.ToString();
        }
    }
 
 
 
    public class Nonce
    {
        private static ConcurrentDictionary<string, Tuple<int, DateTime>>
        nonces = new ConcurrentDictionary<string, Tuple<int, DateTime>>();
 
        public static string Generate()
        {
            byte[] bytes = new byte[16];
 
            using (var rngProvider = new RNGCryptoServiceProvider())
            {
                rngProvider.GetBytes(bytes);
            }
 
            string nonce = bytes.ToMD5Hash();
 
            nonces.TryAdd(nonce, new Tuple<int, DateTime>(0, DateTime.Now.AddMinutes(10)));
 
            return nonce;
        }
 
        public static bool IsValid(string nonce, string nonceCount)
        {
            Tuple<int, DateTime> cachedNonce = null;
            //nonces.TryGetValue(nonce, out cachedNonce);
            nonces.TryRemove(nonce, out cachedNonce);//每个nonce只允许使用一次
 
            if (cachedNonce != null) // nonce is found
            {
                // nonce count is greater than the one in record
                if (Int32.Parse(nonceCount) > cachedNonce.Item1)
                {
                    // nonce has not expired yet
                    if (cachedNonce.Item2 > DateTime.Now)
                    {
                        // update the dictionary to reflect the nonce count just received in this request
                        //nonces[nonce] = new Tuple<int, DateTime>(Int32.Parse(nonceCount), cachedNonce.Item2);
 
                        // Every thing looks ok - server nonce is fresh and nonce count seems to be
                        // incremented. Does not look like replay.
                        return true;
                    }
 
                }
            }
 
            return false;
        }
    }
}
复制代码

 

复制代码
using System.Linq;
using System.Security.Cryptography;
using System.Text;
 
namespace WebApplication1.Models
{
    public static class HashHelper
    {
        public static string ToMD5Hash(this byte[] bytes)
        {
            StringBuilder hash = new StringBuilder();
            MD5 md5 = MD5.Create();
 
            md5.ComputeHash(bytes)
                  .ToList()
                  .ForEach(b => hash.AppendFormat("{0:x2}", b));
 
            return hash.ToString();
        }
 
        public static string ToMD5Hash(this string inputString)
        {
            return Encoding.UTF8.GetBytes(inputString).ToMD5Hash();
        }
    }
 
}
复制代码

2.将上述自定义的HttpDigestAuthenticationHandler类添加到全局消息处理管道中,代码如下:

复制代码
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
 
        config.MapHttpAttributeRoutes();
 
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
 
        config.MessageHandlers.Add(new HttpDigestAuthenticationHandler());//添加到消息处理管道中
    }
}
复制代码

3.在需要认证授权后才能访问的Controller中类或ACTION方法上添加Authorize特性即可。

测试方法很简单,第一种直接在浏览器中访问(同上),第二种采用HttpClient来调用WEB API,示例代码如下:

复制代码
public async static void TestLoginApi4()
{
    HttpClientHandler handler = new HttpClientHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.Credentials = new NetworkCredential("admin", "api.admin");
 
    HttpClient client = new HttpClient(handler);
 
    var response = await client.GetAsync("http://localhost:11099/api/test/");
    var r2 = await response.Content.ReadAsAsync<IEnumerable<string>>();
    foreach (string item in r2)
    {
        Console.WriteLine("GetValues - Item Value:{0}", item);
    }
 
    response = await client.GetAsync("http://localhost:11099/api/test/8");
    var r3 = await response.Content.ReadAsAsync<string>();
    Console.WriteLine("GetValue - Item Value:{0}", r3); 
}
复制代码

该实现方法,参考了该篇文章:http://zrj-software.iteye.com/blog/2163487

实现Digest摘要认证,除了上述通过继承自DelegatingHandler来实现自定义的消息处理管道类外,也可以通过继承自AuthorizationFilterAttribute来实现自定义的验证授权过滤器,Basic基础认证与Digest摘要认证流程基本相同,区别在于:Basic是将密码直接base64编码(明文),而Digest是用MD5进行加密后传输,所以两者实现认证方式上,也基本相同。

最后说明一下,WEB SERVICE、WCF、WEB API实现身份验证的方法有很多,每种方法都有他所适用的场景,我这个系列文章仅是列举一些常见的实见身份验证的方法,一是给自己复习并备忘,二是给大家以参考,文中可能有不足之处,若发现问题,可以在下面评论指出,谢谢!

标签:WebApi,string,C#,身份验证,System,new,using,response,public
From: https://www.cnblogs.com/wohenxinwei/p/17604192.html

相关文章

  • 记录一下Linux下远程访问Mysql连接不上,报错The driver has not received any packets
    问题所在远程服务器已经提前安装好了MySQL,版本也是对应的。在ssh上可以正常进入MySQL数据库。但是其他地方无法连接上,例如navicat和IDE内部都发生报错。排查1.首先排查了一下远程服务器上mysql服务状态是否处于正常运行状态sudoservicemysqldstatus没有发生问题。2.检......
  • filelock-文件锁的使用
    filelock用于文件锁定用于多进程或多线程对同一文件的操作用法:fromfilelockimportFileLocklock=FileLock("file.lock")withlock:#Dosomethingwiththefile说明:1.如果文件不存在,会自动创建2.如果文件已经被锁定,会等待锁定释放后再执行3.如果文件已经被......
  • spring-mvc系列:简介和基本使用
    目录一、简介1、什么是MVC2、什么是SpringMVC3、SpringMVC的特点二、基本使用1、开发环境2、创建maven工程3、配置web.xml4、创建SpringMVC的配置文件5、创建请求控制器6、创建html页面7、总结一、简介1、什么是MVCMVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分......
  • 【SpringBoot学习】7、SpringBoot 整合 JDBC Templete 实现 CRUD 案例
    准备工作数据库CREATETABLE`tb_user`(`id`bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'主键ID',`username`varchar(255)DEFAULTNULLCOMMENT'用户名',`password`varchar(255)DEFAULTNULLCOMMENT'密码',`ctime`datetimeDEFAULT......
  • t113-c-i2s学习篇(cards)
    学习一下t113的i2s驱动1.模块功能规格介绍一堆看不懂的名词,处于半看懂半看不懂的状态2.模块源码结构介绍又是一堆看不懂的文件名字,还是不懂怎么用3.模块配置介绍3.1DeviceTree配置介绍什么是dmic?硬件接口之DMIC 举例,以i2s为例子:3.2board.dts板级配置介绍......
  • 解决Tomcat数据连接池无法释放
    近段时间,公司的检测中心报表系统(SMC)的开发人员时不时找到我,说用户老是出现无法登录的情况。前些日子因为手头上有Jboss集群的测试工作,发现用户不能登录时,都是在Tomcat中将这个项目Reload一下就好了,不过只是治标而已,因为大概几个小时之后又会再次出现无法登录的情况。今天上午,开......
  • VScode 中golang 基准测试 go test -bench .
    目的:基准测试的主要目的是比较不同实现方式之间的性能差异,找出性能瓶颈。1准备以_test.go结尾文件和导入testing包在命名文件时需要让文件必须以_test结尾,在文件中导入testing包。基准测试可以测试一段程序的运行性能及耗费CPU的程度,获得代码内存占用和运行效率的性能数据。G......
  • Latex在VScode中的安装
    Latex在VScode中的安装和使用VScode+texlive+SumatraPDF1.texlive下载安装华为镜像https://mirrors.huaweicloud.com/CTAN/systems/texlive/Images/阿里镜像https://mirrors.aliyun.com/CTAN/systems/texlive/Images/下载后对其进行解压得到以下文件右键install-tl-wind......
  • k8s 基于角色的访问控制 RBAC
    RBAC介绍DAC(自主访问控制)、MAC(强制访问控制)、RBAC(基于角色的访问控制)和ABAC(基于属性的访问控制)这4种主流的权限管理模型中,Kubernetes支持使用后两种完成普通账户和服务账户的权限管理,另外支持的权限管理模型还有Node和Webhook两种。RBAC是一种新型、灵活且使用广泛的访问控制机......
  • 通过docker构建nginx alpine镜像
    第一步:创建Dockerfile文件到data目录,创建docker目录,再创建Dockerfile文件。//到data目录cd/data//创建docker目录mkdirdocker//创建Dockerfile文件touchDockerfile//编辑Dockerfile文件viDockerfile 第二步:构建镜像//不要忘了最后的.,表示的是在指定镜像......