本文是介紹aws 作為api gateway,用asp.net core用web應用,.net core作為aws lambda function。
api gateway和asp.net core的用處不廢話,直接上操作步驟。
首先在asw的憑據管理中添加操作的使用者和角色,步驟如下:
注意選擇的政策名稱 下載下傳csv備用 安裝aws的visual studio插件 加載備用csv檔案 建立asw lambda funcation項目 代碼如下:1 using System;
2
3 using Amazon.Lambda.APIGatewayEvents;
4
5 using Amazon.Lambda.Core;
6
7 using Microsoft.IdentityModel.Tokens;
8
9 using System.Collections.Generic;
10
11 using System.IdentityModel.Tokens.Jwt;
12
13 using System.Linq;
14
15 using System.Security.Claims;
16
17 using System.Text;
18
19
20
21
22
23 [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
24
25 namespace API01AWSLambda
26
27 {
28
29 public class Function
30
31 {
32
33
34
35 /// <summary>
36
37 ///驗證Token的Lambda函數
38
39 /// </summary>
40
41 /// <param name="apigAuthRequest">請求</param>
42
43 /// <param name="context">上下文</param>
44
45 /// <returns></returns>
46
47 public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest apigAuthRequest, ILambdaContext context)
48
49 {
50
51 LambdaLogger.Log($"AWS Lambda函數驗證Token開始");
52
53 var TokenValidationParameters = new TokenValidationParameters
54
55 {
56
57 ValidateIssuer = true,
58
59 ValidateIssuerSigningKey = true,
60
61 ValidIssuer = SecurityConstants.Issuer,
62
63 ValidateAudience = true,
64
65 ValidAudience = SecurityConstants.Audience,
66
67 ValidateLifetime = true,
68
69 IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecurityConstants.SecurityKey)),
70
71 ClockSkew = TimeSpan.Zero,
72
73 };
74
75 var authorized = false;
76
77 //删除Bearer再來驗證
78
79 var token = apigAuthRequest.AuthorizationToken?.Replace("Bearer ", "");
80
81 if (!string.IsNullOrWhiteSpace(token))
82
83 {
84
85 try
86
87 {
88
89 SecurityToken validatedToken;
90
91 var handler = new JwtSecurityTokenHandler();
92
93 var user = handler.ValidateToken(token, TokenValidationParameters, out validatedToken);
94
95 var claim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
96
97 if (claim != null)
98
99 {
100
101 authorized = claim.Value == SecurityConstants.ClaimName;
102
103 }
104
105 }
106
107 catch (Exception ex)
108
109 {
110
111 LambdaLogger.Log($"Error occurred validating token: {ex.Message}");
112
113 }
114
115 }
116
117 var policy = new APIGatewayCustomAuthorizerPolicy
118
119 {
120
121 Version = "2012-10-17",
122
123 Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>(),
124
125
126
127 };
128
129 policy.Statement.Add(new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
130
131 {
132
133 Action = new HashSet<string>(new string[] { "execute-api:Invoke" }),
134
135 Effect = authorized ? "Allow" : "Deny",
136
137 Resource = new HashSet<string>(new string[] { apigAuthRequest.MethodArn })
138
139
140
141 });
142
143 var contextOutput = new APIGatewayCustomAuthorizerContextOutput();
144
145 contextOutput["User"] = authorized ? SecurityConstants.ClaimName : "User";
146
147 contextOutput["Path"] = apigAuthRequest.MethodArn;
148
149 LambdaLogger.Log($"AWS Lambda函數驗證Token結束");
150
151 return new APIGatewayCustomAuthorizerResponse
152
153 {
154
155 PrincipalID = authorized ? SecurityConstants.ClaimName : "User",
156
157 Context = contextOutput,
158
159 PolicyDocument = policy,
160
161 };
162
163 }
164
165 }
166
167 /// <summary>
168
169 /// 測試用,正式環境可以放在雲配置中
170
171 /// </summary>
172
173 public class SecurityConstants
174
175 {
176
177 public const string Issuer = "gsw";
178
179 public const string SecurityKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
180
181 public const string Audience = "everone";
182
183 public const string Password = "111111";
184
185 public const string ClaimName = "gsw";
186
187 }
188
189 }
190
191
View Code
釋出asw lambda funcation
選擇建立的asw角色
在管理平台上檢視上傳的lambda funcation
api gatewayr背景被通路的web api應用有兩個:api01,api02,他們最終釋出到aws api gateway能通路到的地方,我的api01是:http://helpyou.cloudapp.net:4567/abc,pai02是:http://helpyou.cloudapp.net:4568/abc,源碼見https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/AWS,AuthenticationService項目是用來産生Token的,關于這部門參看我之前的博文。
建立asw api gateway
建立授權
關聯api01項目和api02項目的資源檔案
給資源添加通路方法,并關聯api01的url
添加Token的鍵Authorzation
添加傳回狀态碼
添加api02的查詢參數和header
部署API(如果資源和方法變更後,一定要重新部署API)
複制調用URL(api gateway是有限流的作用的)
本地啟動AuthenticationService,使用者名gsw,密碼111111,這個使用者的角色是能通路api01,和api01的
測試通路無token的api01,完整位址是部署的url加上資源名字,結果是401傳回碼
通路正确token的api02,結果正确傳回
更多asw api gateway功能請參考官方文檔。
****歡迎關注我的asp.net core系統課程****《asp.net core精要講解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core項目實戰》 https://ke.qq.com/course/291868
《基于.net core微服務》 https://ke.qq.com/course/299524