基於aws api gateway的asp.net core驗證

本文是介紹aws 做爲api gateway,用asp.net core用web應用,.net core做爲aws lambda function。git

api gateway和asp.net core的用處不廢話,直接上操做步驟。github

首先在asw的憑據管理中添加操做的用戶和角色,步驟以下:web

 

注意選擇的策略名稱api

 

下載csv備用app

 

 

 

 安裝aws的visual studio插件asp.net

 

 加載備用csv文件ide

 

 

 建立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 funcationurl

  

 

選擇建立的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功能請參考官方文檔。

相關文章
相關標籤/搜索