1、自定义中间件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace WebApplication29 { public class AuthenticationMiddleware { private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { string authHeader = context.Request.Headers[ "Authorization" ]; if (authHeader != null && authHeader.StartsWith( "Basic" )) { //Extract credentials string encodedUsernamePassword = authHeader.Substring( "Basic " .Length).Trim(); Encoding encoding = Encoding.GetEncoding( "iso-8859-1" ); string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword)); int seperatorIndex = usernamePassword.IndexOf( ‘:‘ ); var username = usernamePassword.Substring(0, seperatorIndex); var password = usernamePassword.Substring(seperatorIndex + 1); if (IsAuthorized(username,password)) { await _next.Invoke(context); } else { context.Response.StatusCode = 401; //Unauthorized return ; } } else { // no authorization header context.Response.StatusCode = 401; //Unauthorized return ; } } public bool IsAuthorized( string username, string password) { IConfiguration Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile( "appsettings.json" , true ) .Build(); var basicAuthUserName = Configuration[ "BasicAuth:UserName" ]; var basicAuthPassword = Configuration[ "BasicAuth:Password" ]; // Check that username and password are correct return username.Equals(basicAuthUserName, StringComparison.InvariantCultureIgnoreCase) && password.Equals(basicAuthPassword); } } } |
2、startup添加自定义中间件
3、 可配置
原文:https://www.cnblogs.com/itjeff/p/15184302.html