public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest apigAuthRequest, ILambdaContext context) { var TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = SecurityConstants.Issuer, ValidateAudience = true, ValidAudience = SecurityConstants.Issuer, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityConstants.SecurityKey)), ClockSkew = TimeSpan.FromMinutes(5), ValidateIssuerSigningKey = true }; SecurityToken validatedToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); bool authorized = false; if (!string.IsNullOrWhiteSpace(apigAuthRequest.AuthorizationToken)) { try { var user = handler.ValidateToken(apigAuthRequest.AuthorizationToken, TokenValidationParameters, out validatedToken); var claim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name); if (claim != null) { authorized = claim.Value == SecurityConstants.ClaimName; // Ensure that the claim value matches the assertion } } catch (Exception ex) { LambdaLogger.Log($"Error occurred validating token: {ex.Message}"); } } APIGatewayCustomAuthorizerPolicy 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 }) }); APIGatewayCustomAuthorizerContextOutput contextOutput = new APIGatewayCustomAuthorizerContextOutput(); contextOutput["User"] = authorized ? SecurityConstants.ClaimName : "User"; contextOutput["Path"] = apigAuthRequest.MethodArn; return(new APIGatewayCustomAuthorizerResponse { PrincipalID = authorized ? SecurityConstants.ClaimName : "User", Context = contextOutput, PolicyDocument = policy }); }
/// <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> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest apiRequest, ILambdaContext context) { bool authorized = false; if (!string.IsNullOrWhiteSpace(apiRequest.AuthorizationToken)) { authorized = ValidateToken(apiRequest.AuthorizationToken, context); } var policy = new APIGatewayCustomAuthorizerPolicy { Version = "2012-10-17", Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement> { new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement { Action = new HashSet <string>(new string[] { "execute-api:Invoke" }), Effect = authorized ? "Allow" : "Deny", Resource = new HashSet <string>(new string[] { apiRequest.MethodArn }) // api gateway endpoint arn } } }; var contextOutput = new APIGatewayCustomAuthorizerContextOutput(); contextOutput["User"] = authorized ? AllowedUserName : "******"; contextOutput["Path"] = apiRequest.MethodArn; var response = new APIGatewayCustomAuthorizerResponse { Context = contextOutput, PolicyDocument = policy }; return(response); }
/// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The list of blogs</returns> public APIGatewayCustomAuthorizerResponse Get(APIGatewayCustomAuthorizerRequest request, ILambdaContext context) { context.Logger.LogLine("Get Request\n"); context.Logger.LogLine(request.AuthorizationToken.ToString()); context.Logger.LogLine(ablUrl); var accessToken = request.AuthorizationToken.Substring("Bearer ".Length).Trim(); context.Logger.LogLine(accessToken); RSA publicRsa = RSA.Create(); publicRsa.FromXmlString("<RSAKeyValue><Modulus>niwszppYY81jN+LO9riMlDVFXCuChYK4NpmnhV7SjRksFfs397jYu07fcGNVWEBppeJ1WZEFILypPjRRfARgwKa4Lu0633cPYG+amyKRYgTGyvbEjvWJ/yvyqimuPrbrI8Bv6FemwCrOoxYIST0pwEHPx6f8SMxKAE9nXP5xcshrudNUZkK9/B17T1HLk9uAzg52cPIM0SChrhfsklcToaycrUQgtFLYWdVEacaSXNo4q1G2ItgHqhM6vHQ5SMcrQ7O+7hlyD5dXkIXItHY4KlHx6yhBp6o0C2237cjIpP1bJaaarFYkHIyWnJ4BET5JXhgVx8j4N6T4S5cNsuy0Rw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"); RsaSecurityKey signingKey = new RsaSecurityKey(publicRsa); bool authorized = false; var tokenHandler = new JwtSecurityTokenHandler(); try { tokenHandler.ValidateToken(accessToken, new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = false, ValidateAudience = true, ValidAudience = "api", IssuerSigningKey = signingKey, ClockSkew = TimeSpan.FromMinutes(5), }, out SecurityToken validatedToken); authorized = true; } catch (Exception ex) { context.Logger.LogLine(ex.Message); } // var TokenValidationParams = new TokenValidationParameters // { // //IssuerSigningKey=signingKey, // ValidateIssuer=false, // ValidIssuer=ablUrl, // ValidateAudience=false, // ValidAudience="api", // ClockSkew=TimeSpan.FromMinutes(5), // }; // SecurityToken validatedToken; // JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); // try // { // var token = handler.ValidateToken(accessToken, TokenValidationParams, out validatedToken); // foreach (Claim claim in token.Claims){ // context.Logger.LogLine($"CLAIM TYPE: {claim.Type} CLAIM VALUE: {claim.Value}"); // } // var getClaimIss = token.Claims.FirstOrDefault(c => c.Type == "iss"); // context.Logger.LogLine($"{getClaimIss}"); // if (getClaimIss != null){ // authorized = true; // } // } // catch (Exception ex) // { // context.Logger.LogLine($"Error occurred validating token: {ex.Message}"); // } context.Logger.LogLine($"{authorized}"); APIGatewayCustomAuthorizerPolicy 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[] { request.MethodArn }) }); APIGatewayCustomAuthorizerContextOutput contextOutput = new APIGatewayCustomAuthorizerContextOutput(); contextOutput["User"] = "******"; contextOutput["Path"] = request.MethodArn; return(new APIGatewayCustomAuthorizerResponse { PrincipalID = "User", Context = contextOutput, PolicyDocument = policy }); }
public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest apigAuthRequest, ILambdaContext context) { string auth0Domain = context.ClientContext.Environment["Auth0Domain"]; string auth0Audience = context.ClientContext.Environment["Auth0Audience"]; IConfigurationManager <OpenIdConnectConfiguration> configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>($"{auth0Domain}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); OpenIdConnectConfiguration openIdConfig = AsyncHelper.RunSync(async() => await configurationManager.GetConfigurationAsync(CancellationToken.None)); var tokenValidationParameters = new TokenValidationParameters { ValidIssuer = auth0Domain, ValidAudiences = new[] { auth0Audience }, IssuerSigningKeys = openIdConfig.SigningKeys }; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); bool authorized = false; Claim subject = null; string[] scopes = null; if (!string.IsNullOrWhiteSpace(apigAuthRequest.AuthorizationToken)) { try { var user = handler.ValidateToken(apigAuthRequest.AuthorizationToken, tokenValidationParameters, out _); var audience = user.Claims.FirstOrDefault(c => c.Type == "aud"); var issuer = user.Claims.FirstOrDefault(c => c.Type == "iss"); subject = user.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (user.Claims.Any(c => c.Type == "scope")) { scopes = user.Claims.First(c => c.Type == "scope").Value.Split(" ").Where(x => x.Contains(":")).ToArray(); } if (audience != null && issuer != null) { authorized = issuer.Value == auth0Domain && audience.Value == auth0Audience; // Ensure that the claim value matches the assertion } } catch (Exception ex) { LambdaLogger.Log($"Error occurred validating token: {ex.Message}"); } } APIGatewayCustomAuthorizerPolicy 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 }) }); APIGatewayCustomAuthorizerContextOutput contextOutput = new APIGatewayCustomAuthorizerContextOutput(); contextOutput["User"] = authorized ? subject.Value : null; contextOutput["Path"] = apigAuthRequest.MethodArn; var permissions = scopes ?? new string[] {}; contextOutput["Permissions"] = string.Join(",", permissions); return(new APIGatewayCustomAuthorizerResponse { PrincipalID = authorized ? subject.Value : null, Context = contextOutput, PolicyDocument = policy }); }