The_Chud
The_Chud

Reputation: 1091

403 Forbidden/500 Internal Server Error after deploying .net core api AWS Serverless application

I can only guess that it is to do with http / https here.

Controller for Authentication:

 public class AuthenticationController : Controller
    {
        [HttpPost]
        [Route("api/signin")]
        public async Task<ActionResult<string>> SignIn(User user)
        {
            var cognito = new AmazonCognitoIdentityProviderClient(RegionEndpoint.APSoutheast2);

            var request = new AdminInitiateAuthRequest
            {
                UserPoolId = "ap-southeast-2_MYPOOLID",
                ClientId = "MYCLIENTID",
                AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH
            };

            request.AuthParameters.Add("USERNAME", user.Username);
            request.AuthParameters.Add("PASSWORD", user.Password);

            var response = await cognito.AdminInitiateAuthAsync(request);
            return Ok(response.AuthenticationResult);

        }
    }

Startup.ConfigureServices

 services.AddSingleton<IAuthorizationHandler, CognitoGroupAuthorisationHandler>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = "https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_MYPOOL",
                        ValidateIssuerSigningKey = true,
                        ValidateIssuer = true,
                        ValidateLifetime = true,
                        ValidAudience = "MYKEY",
                        ValidateAudience = true
                    };
                });

EDIT #1 It appears I resolved the forbidden msg but am now getting a 500 error.

Postman yields: 500 Internal Server Error

Testing with API Gateway (Api Gateway->Resources-> /{proxy+}->Any->Test->Post)

Method: POST Proxy is set to : /api/signin Request Body:

{
    "username": "xxx",
    "password":"yyy"
}

yields:

{"Strict-Transport-Security":"max-age=2592000","ErrorType":"AmazonCognitoIdentityProviderException","X-Amzn-Trace-Id":"Root=xxxxx;Sampled=0","Content-Type":""}

Upvotes: 1

Views: 1501

Answers (1)

The_Chud
The_Chud

Reputation: 1091

Ok - This may help someone at some stage

  1. The initial "Forbidden" error was not actually a permissions issue. When the API is deployed via the wizard it actually adds the "staging" directory at the end of the URL. I did not add this to my postman request. It's simple to do and overlook. It's a bit misleading - It should really be a 404.

  2. The second part (Edit #1) 500 Internal Server error. There's no real "easy" way to solve this except for enabling cloudwatch logs against your API and then scouring.

Follow this YouTube video on how to set this up: https://www.youtube.com/watch?v=R67huNjk88w

After looking through the logs I found that it was an permissions issue:

Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderException: User: arn:aws:sts::xxxxx:assumed-role/xxx-AspNetCoreFunctionRole-xxx/xxx-AspNetCoreFunction-xxxx is not authorized to perform: cognito-idp:AdminInitiateAuth on resource: arn:aws:cognito-idp:ap-southeast-2:xxxx:userpool/ap-southeast-2_xxxxx ---> 

Credit goes to the following article:

https://medium.com/@fcavalcantirj/tutorial-aws-api-gateway-cognito-userpool-8cc5838eac0

Step 2.2.4.4 Specifically. As I found the Visual Studio Wizard takes care of pretty much everything else, I just needed to add these extra policies.

{
   "Version":"2012–10–17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
         ],
         "Resource":"arn:aws:logs:*:*:*"
      },
      {
         "Effect":"Allow",
         "Action":[
            "cognito-identity:*",
            "cognito-idp:*",
            "cognito-sync:*",
            "iam:ListRoles",
            "iam:ListOpenIdConnectProviders",
            "sns:ListPratformApplications"
         ],
         "Resource":"*"
      }
   ]
}

Policy is created and applied by:

  1. Services->IAM->Policies->Create Policy->Json->
  2. Paste the policy above. (If you get an error about malformed JSON, use the existing JSON in the JSON box and copy only the content between curly braces under Statement from the above policy - including the curly braces themselves obviously).

    { "Version": "2012-10-17", "Statement": [] }

  3. Go to Review Policy and Finish off creation

  4. Go to Roles Click on the AspNetCoreFunctionRole User that was logged and shown in Cloudwatch Log

  5. Under Permissions Click Attach Policies
  6. Type in the name of your newly create policy
  7. Post to your login page and Voila

Upvotes: 1

Related Questions