-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunction.cs
More file actions
73 lines (62 loc) · 2.53 KB
/
Function.cs
File metadata and controls
73 lines (62 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Microsoft.IdentityModel.Tokens;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace lambda_authorizer_dotnet_core
{
public class Function
{
private readonly string Key;
private readonly TokenValidationParameters ValidationParameters;
public Function()
{
Key = Environment.GetEnvironmentVariable("Key");
ValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key)),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false
};
}
public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest authEvent, ILambdaContext context)
{
var token = authEvent.AuthorizationToken;
var authorized = ValidateToken(token);
var resource = authEvent.MethodArn;
return authorized ? SetResponse("Allow", resource) : SetResponse("Deny", resource);
}
public bool ValidateToken(string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
tokenHandler.ValidateToken(token, ValidationParameters, out var validatedToken);
return true;
}
catch
{
return false;
}
}
private APIGatewayCustomAuthorizerResponse SetResponse(string effect, string resource)
{
var response = new APIGatewayCustomAuthorizerResponse();
response.PrincipalID = "user";
var policyDocument = new APIGatewayCustomAuthorizerPolicy();
var statement = new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement();
statement.Action = new HashSet<string> { "execute-api:Invoke" };
statement.Resource = new HashSet<string> { resource };
statement.Effect = effect;
policyDocument.Statement.Add(statement);
response.PolicyDocument = policyDocument;
return response;
}
}
}