正文转自:http://www.cnblogs.com/catcher1994/p/6021046.html

Web
API,是一个能叫前后端分离、解放前后端生产力的好东西。不过大部分合作社该都无能好了的内外端分离。API的兑现方式产生坏

基本上,可以就此ASP.NET Core、也足以用ASP.NET Web API、ASP.NET
MVC、NancyFx等。说到Web API,不同之食指闹两样的做法,可能前台、

中台和后台各一个api站点,也发或一个模块一个api站点,也时有发生或各个系统共用一个api站点,当然这跟作业有得的牵连。

  安全顺其自然的成Web API关注之严重性之一。现在风行的OAuth
2.0是单深是的事物,不过本文是小尚未涉嫌到的,只是以最极致极致

原来之思绪做的一个授权验证。在前头的MVC中,我们可能是透过过滤器来拍卖者地位的说明,在Core中,我本就是拣Middleware来处

张罗这证明。

  下面开始本文的主题:

  先编制一个克健康运转的api,不进行其它的权杖过滤。

图片 1😉

 1 using Dapper;
 2 using Microsoft.AspNetCore.Mvc;
 3 using System.Data;
 4 using System.Linq;
 5 using System.Threading.Tasks;
 6 using WebApi.CommandText;
 7 using WebApi.Common;
 8 using Common;
 9 
10 namespace WebApi.Controllers
11 {
12     [Route("api/[controller]")]
13     public class BookController : Controller
14     {
15 
16         private DapperHelper _helper;
17         public BookController(DapperHelper helper)
18         {
19             this._helper = helper;
20         }
21 
22         // GET: api/book
23         [HttpGet]
24         public async Task<IActionResult> Get()
25         {
26             var res = await _helper.QueryAsync(BookCommandText.GetBooks);
27             CommonResult<Book> json = new CommonResult<Book>
28             {
29                 Code = "000",
30                 Message = "ok",
31                 Data = res
32             };
33             return Ok(json);
34         }
35 
36         // GET api/book/5
37         [HttpGet("{id}")]
38         public IActionResult Get(int id)
39         {
40             DynamicParameters dp = new DynamicParameters();
41             dp.Add("@Id", id, DbType.Int32, ParameterDirection.Input);
42             var res = _helper.Query<Book>(BookCommandText.GetBookById, dp, null, true, null, CommandType.StoredProcedure).FirstOrDefault();
43             CommonResult<Book> json = new CommonResult<Book>
44             {
45                 Code = "000",
46                 Message = "ok",
47                 Data = res
48             };
49             return Ok(json);
50         }
51 
52         // POST api/book        
53         [HttpPost]
54         public IActionResult Post([FromForm]PostForm form)
55         {
56             DynamicParameters dp = new DynamicParameters();
57             dp.Add("@Id", form.Id, DbType.Int32, ParameterDirection.Input);
58             var res = _helper.Query<Book>(BookCommandText.GetBookById, dp, null, true, null, CommandType.StoredProcedure).FirstOrDefault();
59             CommonResult<Book> json = new CommonResult<Book>
60             {
61                 Code = "000",
62                 Message = "ok",
63                 Data = res
64             };
65             return Ok(json);
66         }
67 
68     }
69 
70     public class PostForm
71     {
72         public string Id { get; set; }
73     }
74 
75 }

图片 2😉

  api这边当没什么好说的,都是有的常规的操作,会MVC的当都得领略。主要是依据id获取图书信息的办法(GET和POST)。这是我们后

迎拓展单元测试的少数单重要方式。这样安排得的一个API站点,是其它一个口犹好拜http://[yourapidomain.com](http://api.yourapidomain.com/)/api/book
来得到有关

的数额。现在我们如果对准这个api进行一定之处理,让仅仅生权力的站点才会访问它。

  下面就是编写自定义之授权验证中间件了。

  Middleware这个东西大家应还不见面生了,OWIN出来的早晚就是出中件这样的定义了,这里虽未开展说明,在ASP.NET
Core中是怎样

兑现这中间件的好参照官方文档
Middleware。 

  我们事先定义一个我们设就此到之option,ApiAuthorizedOptions

图片 3😉

 1 namespace WebApi.Middlewares
 2 {
 3     public class ApiAuthorizedOptions
 4     {
 5         //public string Name { get; set; }
 6 
 7         public string EncryptKey { get; set; }
 8         
 9         public int ExpiredSecond { get; set; }
10     }
11 }

图片 4😉

  option内容比较简单,一个是EncryptKey
,用于对我们的请参数进行签约,另一个是ExpiredSecond
,用于检验我们的乞求是否过。

和的相应的凡以appsettings.json中安的ApiKey节点

图片 5😉

1   "ApiKey": {
2     //"username": "123",
3     //"password": "123",
4     "EncryptKey": "@*api#%^@",
5     "ExpiredSecond": "300"
6   }

图片 6😉

  有矣option,下面就可编写middleware的情了

  我们的api中就是兑现了get和post的法,所以这里为就是本着get和post做了处理,其他http
method,有需要的得好补。

  这里的说明主要是底下的几个点:

  1.参数是否被篡改

  2.呼吁是否曾经晚点

  3.伸手的利用是否合法

  主检查方式:Check

图片 7😉

 1          /// <summary>
 2         /// the main check method
 3         /// </summary>
 4         /// <param name="context"></param>
 5         /// <param name="requestInfo"></param>
 6         /// <returns></returns>
 7         private async Task Check(HttpContext context, RequestInfo requestInfo)
 8         {
 9             string computeSinature = HMACMD5Helper.GetEncryptResult($"{requestInfo.ApplicationId}-{requestInfo.Timestamp}-{requestInfo.Nonce}", _options.EncryptKey);
10             double tmpTimestamp;
11             if (computeSinature.Equals(requestInfo.Sinature) &&
12                 double.TryParse(requestInfo.Timestamp, out tmpTimestamp))
13             {
14                 if (CheckExpiredTime(tmpTimestamp, _options.ExpiredSecond))
15                 {
16                     await ReturnTimeOut(context);
17                 }
18                 else
19                 {
20                     await CheckApplication(context, requestInfo.ApplicationId, requestInfo.ApplicationPassword);
21                 }
22             }
23             else
24             {
25                 await ReturnNoAuthorized(context);
26             }
27         }

图片 8😉

  Check方法带了2独参数,一个凡现阶段之httpcontext对象与乞求的内容信息,当签名一致,并且时间戳能转化成double时才去校验是否过期

及Applicatioin的相关消息。这里的签名用了比较简单的HMACMD5加密,同样是可转移成SHA等加密来进行这无异步的拍卖,加密的参数与规则是

随便定的,要发生一个约定的长河,缺少灵活性(就如与银行交接那样,银行说您虽设这样污染参数为自身,不这么就是挺,只好乖乖从命)。

  Check方法还因此到了底的4独处理

  1.子反省方式–超时判断CheckExpiredTime

图片 9😉

 1          /// <summary>
 2         /// check the expired time
 3         /// </summary>
 4         /// <param name="timestamp"></param>
 5         /// <param name="expiredSecond"></param>
 6         /// <returns></returns>
 7         private bool CheckExpiredTime(double timestamp, double expiredSecond)
 8         {
 9             double now_timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
10             return (now_timestamp - timestamp) > expiredSecond;
11         }

图片 10😉

  这里获得了当前时间和1970年1月1日底间距和请求参数中染过来的年华戳进行比较,是否超越我们于appsettings中装置的深值,超过就是

逾期了,没越就可以连续下一个步骤。

  2.子检查方–应用程序判断CheckApplication

  应用程序要说明什么也?我们见面吃每个应用程序创建一个ID和一个访api的密码,所以我们要验证这个应用程序的真实性身份,是否是那些

出权力的应用程序。

图片 11😉

 1         /// <summary>
 2         /// check the application
 3         /// </summary>
 4         /// <param name="context"></param>
 5         /// <param name="applicationId"></param>
 6         /// <param name="applicationPassword"></param>
 7         /// <returns></returns>
 8         private async Task CheckApplication(HttpContext context, string applicationId, string applicationPassword)
 9         {
10             var application = GetAllApplications().Where(x => x.ApplicationId == applicationId).FirstOrDefault();
11             if (application != null)
12             {
13                 if (application.ApplicationPassword != applicationPassword)
14                 {
15                     await ReturnNoAuthorized(context);
16                 }
17             }
18             else
19             {
20                 await ReturnNoAuthorized(context);
21             }
22         }

图片 12😉

  先根据请求参数中的应用程序id去找到相应的应用程序,不可知找到就说明不是合法的应用程序,能找到更错过证明其密码是否是,最后才真的

毫无疑问其是否取得api中的数量。

  下面两主意是拍卖没有授权和过处理的落实:

  没有授权的回方法ReturnNoAuthorized

图片 13😉

 1         /// <summary>
 2         /// not authorized request
 3         /// </summary>
 4         /// <param name="context"></param>
 5         /// <returns></returns>
 6         private async Task ReturnNoAuthorized(HttpContext context)
 7         {
 8             BaseResponseResult response = new BaseResponseResult
 9             {
10                 Code = "401",
11                 Message = "You are not authorized!"
12             };
13             context.Response.StatusCode = 401;
14             await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
15         }

图片 14😉

  这里开的拍卖是拿响应的状态码设置成401(Unauthorized)。

  超时的返方法ReturnTimeOut

图片 15😉

 1         /// <summary>
 2         /// timeout request 
 3         /// </summary>
 4         /// <param name="context"></param>
 5         /// <returns></returns>
 6         private async Task ReturnTimeOut(HttpContext context)
 7         {
 8             BaseResponseResult response = new BaseResponseResult
 9             {
10                 Code = "408",
11                 Message = "Time Out!"
12             };
13             context.Response.StatusCode = 408;
14             await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
15         }

图片 16😉

  这里召开的拍卖是拿响应的状态码设置成408(Time Out)。

  下面将处理Http的GET请求与POST请求了。

  HTTP GET请求的拍卖方式GetInvoke

图片 17😉

 1         /// <summary>
 2         /// http get invoke
 3         /// </summary>
 4         /// <param name="context"></param>
 5         /// <returns></returns>
 6         private async Task GetInvoke(HttpContext context)
 7         {
 8             var queryStrings = context.Request.Query;
 9             RequestInfo requestInfo = new RequestInfo
10             {
11                 ApplicationId = queryStrings["applicationId"].ToString(),
12                 ApplicationPassword = queryStrings["applicationPassword"].ToString(),
13                 Timestamp = queryStrings["timestamp"].ToString(),
14                 Nonce = queryStrings["nonce"].ToString(),
15                 Sinature = queryStrings["signature"].ToString()
16             };
17             await Check(context, requestInfo);
18         }

图片 18😉

  处理比较简单,将呼吁的参数赋值给RequestInfo,然后用手上的httpcontext和夫requestinfo交由我们的兆检查方式Check去校验

本条要的合法性。

  同理,HTTP POST请求的拍卖措施PostInvoke,也是千篇一律的处理。

图片 19😉

 1         /// <summary>
 2         /// http post invoke
 3         /// </summary>
 4         /// <param name="context"></param>
 5         /// <returns></returns>
 6         private async Task PostInvoke(HttpContext context)
 7         {
 8             var formCollection = context.Request.Form;
 9             RequestInfo requestInfo = new RequestInfo
10             {
11                 ApplicationId = formCollection["applicationId"].ToString(),
12                 ApplicationPassword = formCollection["applicationPassword"].ToString(),
13                 Timestamp = formCollection["timestamp"].ToString(),
14                 Nonce = formCollection["nonce"].ToString(),
15                 Sinature = formCollection["signature"].ToString()
16             };
17             await Check(context, requestInfo);
18         }

图片 20😉

  最后是Middleware的构造函数和Invoke方法。

图片 21😉

 1        public ApiAuthorizedMiddleware(RequestDelegate next, IOptions<ApiAuthorizedOptions> options)
 2         {
 3             this._next = next;
 4             this._options = options.Value;
 5         }
 6 
 7         public async Task Invoke(HttpContext context)
 8         {
 9             switch (context.Request.Method.ToUpper())
10             {
11                 case "POST":
12                     if (context.Request.HasFormContentType)
13                     {
14                         await PostInvoke(context);
15                     }
16                     else
17                     {
18                         await ReturnNoAuthorized(context);
19                     }
20                     break;
21                 case "GET":
22                     await GetInvoke(context);
23                     break;
24                 default:
25                     await GetInvoke(context);
26                     break;
27             }
28             await _next.Invoke(context);
29         }

图片 22😉

  到此处,Middleware是早已修好了,要以Startup中使用,还要长一个进行方法ApiAuthorizedExtensions

图片 23😉

 1 using Microsoft.AspNetCore.Builder;
 2 using Microsoft.Extensions.Options;
 3 using System;
 4 
 5 namespace WebApi.Middlewares
 6 {
 7     public static class ApiAuthorizedExtensions
 8     {
 9         public static IApplicationBuilder UseApiAuthorized(this IApplicationBuilder builder)
10         {
11             if (builder == null)
12             {
13                 throw new ArgumentNullException(nameof(builder));
14             }
15 
16             return builder.UseMiddleware<ApiAuthorizedMiddleware>();
17         }
18 
19         public static IApplicationBuilder UseApiAuthorized(this IApplicationBuilder builder, ApiAuthorizedOptions options)
20         {
21             if (builder == null)
22             {
23                 throw new ArgumentNullException(nameof(builder));
24             }
25 
26             if (options == null)
27             {
28                 throw new ArgumentNullException(nameof(options));
29             }
30             
31             return builder.UseMiddleware<ApiAuthorizedMiddleware>(Options.Create(options));
32         }
33     }
34 }

图片 24😉

  到此地我们已经足以当Startup的Configure和ConfigureServices方法被配备是当中件了

  这里还有一个非自然不要是兑现的拓展方法ApiAuthorizedServicesExtensions,但自个人要支持被实现之ServicesExtensions。

图片 25图片 26

 1 using Microsoft.Extensions.DependencyInjection;
 2 using System;
 3 
 4 namespace WebApi.Middlewares
 5 {
 6     public static class ApiAuthorizedServicesExtensions
 7     {
 8 
 9         /// <summary>
10         /// Add response compression services.
11         /// </summary>
12         /// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
13         /// <returns></returns>
14         public static IServiceCollection AddApiAuthorized(this IServiceCollection services)
15         {
16             if (services == null)
17             {
18                 throw new ArgumentNullException(nameof(services));
19             }
20 
21             return services;
22         }
23 
24         /// <summary>
25         /// Add response compression services and configure the related options.
26         /// </summary>
27         /// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
28         /// <param name="configureOptions">A delegate to configure the <see cref="ResponseCompressionOptions"/>.</param>
29         /// <returns></returns>
30         public static IServiceCollection AddApiAuthorized(this IServiceCollection services, Action<ApiAuthorizedOptions> configureOptions)
31         {
32             if (services == null)
33             {
34                 throw new ArgumentNullException(nameof(services));
35             }
36             if (configureOptions == null)
37             {
38                 throw new ArgumentNullException(nameof(configureOptions));
39             }
40 
41             services.Configure(configureOptions);
42             return services;
43         }
44     }
45 }

ApiAuthorizedServicesExtensions

  为什么而促成者进行方法吗?个人认为

  Options、Middleware、Extensions、ServicesExtensions这四单凡是贯彻一个中间件的标配(除去简单到特别的那些中间件)

  Options给咱们的中件提供了一部分可选的拍卖,提高了中间件的八面玲珑;

  Middleware是咱们当中件最极端紧要的实现;

  Extensions是咱要当Startup的Configure去表明我们设运用是当中件;

  ServicesExtensions是咱们只要于Startup的ConfigureServices去表明我们管这个当中件添加至容器中。

  下面是一体化的Startup

图片 27😉

 1 using Microsoft.AspNetCore.Builder;
 2 using Microsoft.AspNetCore.Hosting;
 3 using Microsoft.Extensions.Configuration;
 4 using Microsoft.Extensions.DependencyInjection;
 5 using Microsoft.Extensions.Logging;
 6 using System;
 7 using WebApi.Common;
 8 using WebApi.Middlewares;
 9 
10 namespace WebApi
11 {
12     public class Startup
13     {
14         public Startup(IHostingEnvironment env)
15         {
16             var builder = new ConfigurationBuilder()
17                 .SetBasePath(env.ContentRootPath)
18                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
19                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
20 
21             if (env.IsEnvironment("Development"))
22             {
23                 // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
24                 builder.AddApplicationInsightsSettings(developerMode: true);
25             }
26 
27             builder.AddEnvironmentVariables();
28             Configuration = builder.Build();
29         }
30 
31         public IConfigurationRoot Configuration { get; }
32 
33         // This method gets called by the runtime. Use this method to add services to the container
34         public void ConfigureServices(IServiceCollection services)
35         {
36             // Add framework services.
37             services.AddApplicationInsightsTelemetry(Configuration);
38             services.Configure<IISOptions>(options =>
39             {
40 
41             });
42 
43             services.Configure<DapperOptions>(options =>
44             {
45                 options.ConnectionString = Configuration.GetConnectionString("DapperConnection");
46             });
47 
48             //api authorized middleware
49             services.AddApiAuthorized(options =>
50             {
51                 options.EncryptKey = Configuration.GetSection("ApiKey")["EncryptKey"];
52                 options.ExpiredSecond = Convert.ToInt32(Configuration.GetSection("ApiKey")["ExpiredSecond"]);
53             });
54 
55 
56             services.AddMvc();
57 
58             services.AddSingleton<DapperHelper>();
59         }
60 
61         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
62         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
63         {
64 
65             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
66             loggerFactory.AddDebug();
67 
68             app.UseDapper();
69 
70             //api authorized middleware
71             app.UseApiAuthorized();
72 
73             app.UseApplicationInsightsRequestTelemetry();
74 
75             app.UseApplicationInsightsExceptionTelemetry();
76 
77             app.UseMvc();
78         }
79     }
80 }

图片 28😉

  万事具备,只欠测试!!

  建个类库项目,写个单元测试看看。

图片 29😉

 1 using Common;
 2 using Newtonsoft.Json;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Net.Http;
 6 using System.Threading.Tasks;
 7 using Xunit;
 8 
 9 namespace WebApiTest
10 {
11     public class BookApiTest
12     {
13         private HttpClient _client;
14         private string applicationId = "1";
15         private string applicationPassword = "123";
16         private string timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds.ToString();
17         private string nonce = new Random().Next(1000, 9999).ToString();
18         private string signature = string.Empty;
19 
20         public BookApiTest()
21         {
22             _client = new HttpClient();
23             _client.BaseAddress = new Uri("http://localhost:8091/");
24             _client.DefaultRequestHeaders.Clear();
25             signature = HMACMD5Helper.GetEncryptResult($"{applicationId}-{timestamp}-{nonce}", "@*api#%^@");
26         }
27 
28         [Fact]
29         public async Task book_api_get_by_id_should_success()
30         {
31             string queryString = $"applicationId={applicationId}&timestamp={timestamp}&nonce={nonce}&signature={signature}&applicationPassword={applicationPassword}";
32             
33             HttpResponseMessage message = await _client.GetAsync($"api/book/4939?{queryString}");
34             var result = JsonConvert.DeserializeObject<CommonResult<Book>>(message.Content.ReadAsStringAsync().Result);
35 
36             Assert.Equal("000", result.Code);
37             Assert.Equal(4939, result.Data.Id);
38             Assert.True(message.IsSuccessStatusCode);
39         }
40 
41         [Fact]
42         public async Task book_api_get_by_id_should_failure()
43         {
44             string inValidSignature = Guid.NewGuid().ToString();
45             string queryString = $"applicationId={applicationId}&timestamp={timestamp}&nonce={nonce}&signature={inValidSignature}&applicationPassword={applicationPassword}";
46 
47             HttpResponseMessage message = await _client.GetAsync($"api/book/4939?{queryString}");
48             var result = JsonConvert.DeserializeObject<CommonResult<Book>>(message.Content.ReadAsStringAsync().Result);
49 
50             Assert.Equal("401", result.Code);
51             Assert.Equal(System.Net.HttpStatusCode.Unauthorized, message.StatusCode);            
52         }
53 
54         [Fact]
55         public async Task book_api_post_by_id_should_success()
56         {              
57             var data = new Dictionary<string, string>();
58             data.Add("applicationId", applicationId);
59             data.Add("applicationPassword", applicationPassword);
60             data.Add("timestamp", timestamp);
61             data.Add("nonce", nonce);
62             data.Add("signature", signature);
63             data.Add("Id", "4939");
64             HttpContent ct = new FormUrlEncodedContent(data);
65 
66             HttpResponseMessage message = await _client.PostAsync("api/book", ct);
67             var result = JsonConvert.DeserializeObject<CommonResult<Book>>(message.Content.ReadAsStringAsync().Result);
68 
69             Assert.Equal("000", result.Code);
70             Assert.Equal(4939, result.Data.Id);
71             Assert.True(message.IsSuccessStatusCode);

相关文章

网站地图xml地图