本文是介绍aws 作为api gateway,用asp.net core用web应用,.net core作为aws lambda function。

api gateway和asp.net core的用处不废话,直接上操作步骤。

首先在asw的凭据管理中添加操作的用户和角色,步骤如下:

 基于aws api gateway的asp.net core验证

注意选择的策略名称

 基于aws api gateway的asp.net core验证

下载csv备用

 基于aws api gateway的asp.net core验证

 基于aws api gateway的asp.net core验证

 基于aws api gateway的asp.net core验证

 安装aws的visual studio插件

 基于aws api gateway的asp.net core验证

 加载备用csv文件

 基于aws api gateway的asp.net core验证

 基于aws api gateway的asp.net core验证

 创建asw lambda funcation项目

 基于aws api gateway的asp.net core验证

代码如下: 

  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

相关文章:

  • 2021-10-07
  • 2018-12-12
  • 2022-01-28
  • 2021-07-25
  • 2022-12-23
  • 2021-09-08
  • 2021-08-10
  • 2021-07-21
猜你喜欢
  • 2021-12-15
  • 2022-12-23
  • 2021-06-18
  • 2022-12-23
  • 2021-11-02
  • 2021-06-16
相关资源
相似解决方案