基于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项目

代码如下:
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功能请参考官方文档。
基于aws api gateway的asp.net core验证的更多相关文章
- AWS API Gateway Swagger定义
导出Swagger接口定义文件 在AWS API Gateway界面上,可以导出swagger接口定义文件. 而后利用Node js swagger-ui 依赖,生成swagger接口地址 Cloud ...
- Aws api gateway Domain name
Set Up a Custom Domain Name for an API Gateway API The following procedure describes how to set up a ...
- 理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文
这篇英文博文是 Andrew Lock 写的 Introduction to Authentication with ASP.NET Core . 以下是简单的阅读笔记: -------------- ...
- 【转】理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文
这篇英文博文是 Andrew Lock 写的 Introduction to Authentication with ASP.NET Core . 以下是简单的阅读笔记: -------------- ...
- Asp.net core验证类ModelStateDictionary的bug
在使用.net core 3.1 时发现明明没有验证请求类属性,甚至已经加了默认值 但是验证类时依然会报错 经过网上百度等搜索,尝试使用可空类型赋值默认值 果然验证类没有报错 不清楚是微软的bug还是 ...
- 理解ASP.NET Core验证模型 Claim, ClaimsIdentity, ClaimsPrincipal
Claim, ClaimsIdentity, ClaimsPrincipal: Claim:姓名:xxx,领证日期:xxx ClaimsIdentity:身份证/驾照 ClaimsPrincipal: ...
- ASP.NET Core 6 Minimal API的模拟实现
Minimal API仅仅是在基于IHost/IHostBuilder的服务承载系统上作了小小的封装而已,它利用WebApplication和WebApplicationBuilder这两个类型提供了 ...
- 支持多个版本的ASP.NET Core Web API
基本配置及说明 版本控制有助于及时推出功能,而不会破坏现有系统. 它还可以帮助为选定的客户提供额外的功能. API版本可以通过不同的方式完成,例如在URL中添加版本或通过自定义标头和通过Accept- ...
- ASP.NET Core的身份认证框架IdentityServer4(7)- 使用客户端证书控制API访问
前言 今天(2017-9-8,写于9.8,今天才发布)一口气连续把最后几篇IdentityServer4相关理论全部翻译完了,终于可以进入写代码的过程了,比较累.目前官方的文档和Demo以及一些相关组 ...
随机推荐
- sql数据库快照与恢复 规则绑定
存在数据库快照的话我发进行数据库分离 CREATE DATABASE <快照名称> ON (NAME=<数据库文件名>,FILENAME='<存放地址>') AS ...
- Eclipse工具常用快捷键
Eclipse工具常用快捷键 一丶文件菜单常用快捷键 新建 Alt + shift + N 关闭当前编辑器 Ctrl +W 全部关闭 Ctrl + shift + w 保存 Ctrl + s 刷新 ...
- 权限管理系统之LayUI实现页面增删改查和弹出层交互
由于对LayUI框架不太熟悉,昨天抽空看了下LayUI的文档,今天在网上找了使用LayUI进行增删改查相关内容,自己照葫芦画了个瓢,画瓢部分不是很难,主要是下午遇到了一个弹出层的问题耗时比较久. 同一 ...
- Python3+Selenium2完整的自动化测试实现之旅(五):自动化测试框架、Python面向对象以及POM设计模型简介
前言 之前的系列博客,陆续学习整理了自动化测试环境的搭建.IE和Chrome浏览器驱动的配置.selenium-webdriver模块封装的元素定位以及控制浏览器.处理警示框.鼠标键盘等方法的使用,这 ...
- shell编程练习(三): 笔试21-30
笔试练习(三): 21.编写shell程序,实现自动删除30个账号的功能. 账号名为std01至std30. [root@VM_0_5_centos test]# vi 21.sh [root@VM_ ...
- c#中的Unity容器
DIP是依赖倒置原则:一种软件架构设计的原则(抽象概念).依赖于抽象不依赖于细节 IOC即为控制反转(Inversion of Control):传统开发,上端依赖(调用/指定)下端对象,会有依赖,把 ...
- 浅谈_依赖注入 asp.net core
1.1什么是依赖 我们先看下图 可以简单理解,一个HomeController类使用到了DBContext类,而这种关系是有偶然性,临时性,弱关系的,但是DBContext的变化会影响到HomeCon ...
- Web.config中customErrors异常信息配置
开发工具:Visual Studio 2017 15.7.5 开发平台:Windows 10 新建WebApi项目,Web.config配置文件中,system.web下级节点中默认没有customE ...
- rocketmq 发送时异常:system busy 和 broker busy 解决方案
记一次 rocketmq 使用时的异常. 这里就不说什么rocketmq 源码啥的了,因为没看过.网上一搜这两个异常 大部分都是什么源码解读,也没说出现后的解决办法(蓝瘦香菇). 大量测试发现: 1. ...
- alibaba fastjson 使用
// 对象转 json 字符串 User user1 = new User("Marry", 30, new Date()); String str1 = JSON.toJSONS ...