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

本文是介绍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 APIGatewayCustomAuthorizerPolicy118 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.IAMPolicyStatement130 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 APIGatewayCustomAuthorizerResponse152 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 SecurityConstants174 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功能请参考官方文档。

相关文章