本文是介绍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项目
代码如下:
using System; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Microsoft.IdentityModel.Tokens; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace API01AWSLambda { public class Function { /// <summary> ///验证Token的Lambda函数 /// </summary> /// <param name="apigAuthRequest">请求</param> /// <param name="context">上下文</param> /// <returns></returns> public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest apigAuthRequest, ILambdaContext context) { LambdaLogger.Log($"AWS Lambda函数验证Token开始"); var TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateIssuerSigningKey = true, ValidIssuer = SecurityConstants.Issuer, ValidateAudience = true, ValidAudience = SecurityConstants.Audience, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecurityConstants.SecurityKey)), ClockSkew = TimeSpan.Zero, }; var authorized = false; //删除Bearer再来验证 var token = apigAuthRequest.AuthorizationToken?.Replace("Bearer ", ""); if (!string.IsNullOrWhiteSpace(token)) { try { SecurityToken validatedToken; var handler = new JwtSecurityTokenHandler(); var user = handler.ValidateToken(token, TokenValidationParameters, out validatedToken); var claim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name); if (claim != null) { authorized = claim.Value == SecurityConstants.ClaimName; } } catch (Exception ex) { LambdaLogger.Log($"Error occurred validating token: {ex.Message}"); } } var policy = new APIGatewayCustomAuthorizerPolicy { Version = "2012-10-17", Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>(), }; policy.Statement.Add(new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement { Action = new HashSet<string>(new string[] { "execute-api:Invoke" }), Effect = authorized ? "Allow" : "Deny", Resource = new HashSet<string>(new string[] { apigAuthRequest.MethodArn }) }); var contextOutput = new APIGatewayCustomAuthorizerContextOutput(); contextOutput["User"] = authorized ? SecurityConstants.ClaimName : "User"; contextOutput["Path"] = apigAuthRequest.MethodArn; LambdaLogger.Log($"AWS Lambda函数验证Token结束"); return new APIGatewayCustomAuthorizerResponse { PrincipalID = authorized ? SecurityConstants.ClaimName : "User", Context = contextOutput, PolicyDocument = policy, }; } } /// <summary> /// 测试用,正式环境可以放在云配置中 /// </summary> public class SecurityConstants { public const string Issuer = "gsw"; public const string SecurityKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; public const string Audience = "everone"; public const string Password = ""; public const string ClaimName = "gsw"; } }
发布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功能请参考官方文档。