Monday, January 23, 2023

Handler Authorizers:

These are essential AWS mechanisms to enforce only certain roles to have permissions to access cloud resources. It is helpful to both APIs and APPs because it separates the concerns for the Lambda from the admission that those two entities request. This fits in with the general pattern of authorizing access to aws services and resources using identity pools and allowing the APIs and APPs to focus on the user pools for authenticating the user.

Separation of authentication and authorization concerns is similarly maintained between cloud (AWS) and identity provider (IdP) where the part of the authorizers is played by the Cognito offering. While services within the cloud leverage the identity pool, the IDPs are forced to make the individual users visible to the cloud via the user pool. 


For example, the following S3 create-update-delete (CRUD) operations can be authorized with a Cognito identity pool:

using Amazon;

using Amazon.S3;

using Amazon.S3.Model;

using System;

using System.Threading.Tasks;


namespace AuthNAuthZ.Demo.Controllers

{

    public class S3Controller: Controller

    {

        private const string bucketName = "bkt-upload-docs";

        private const string keyName = "key1";

        private const string filePath = @".\test.txt";

        private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;

        private static AmazonS3Client client = new AmazonS3Client(bucketName);


        // PUT: /<controller>/upload

        [Authorize]

        [HttpPut]

        public IActionResult Upload()

        {

Return WritingAnObjectAsync().Wait(); 

        }


        async Task<IActionResult> WritingAnObjectAsync()

        {

            try

            {

                var putRequest = new PutObjectRequest

                {

                    BucketName = bucketName,

                    Key = keyName,

                    FilePath = filePath,

                    ContentType = "text/plain"

                };

                

                putRequest.Metadata.Add("x-amz-meta-title", "sample-title);

                PutObjectResponse response = await client.PutObjectAsync(putRequest);

                Return Ok(response);

            }

            catch (AmazonS3Exception e)

            {

                Console.WriteLine(

                        "Error encountered: Message:'{0}' when writing an object"

                        , e.Message);

            }

            catch (Exception e)

            {

                Console.WriteLine(

                    "Unknown encountered on server. Message:'{0}' when writing an object"

                    , e.Message);

            }

            Return BadRequest();

        }

    }

}


    public class Startup

    {

        :

        :

        public void ConfigureServices(IServiceCollection services)

        {

            services.AddControllersWithViews();

            services.AddAuthentication(options =>

            {

                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;

            })

            .AddCookie()

            .AddOpenIdConnect(options =>

            {

                options.ResponseType = Configuration["Authentication:Cognito:ResponseType"];

                options.MetadataAddress = Configuration["Authentication:Cognito:MetadataAddress"];

                options.ClientId = Configuration["Authentication:Cognito:ClientId"];

                options.Events = new OpenIdConnectEvents()

                {

                    OnRedirectToIdentityProviderForSignOut = OnRedirectToIdentityProviderForSignOut

                };


                //this code block must be leveraged to enable Role Based Authorization

                //options.TokenValidationParameters = new TokenValidationParameters

                //{

                //    ValidateIssuer = options.TokenValidationParameters.ValidateIssuer,

                //    RoleClaimType = "cognito:groups"

                //};

            });


            //this code block must be enabled to leverage Policy Based Authorization

            //Amazon Cognito users attributes are used to support claim-based authorization.

            /* One can use [Authorize] to ensure that only logged-in users can access the Page/Controller/Route.

             * or for more fine-grained control than authenticated users, they can be added to Cognito Groups. 

             * Those groups are sent as part of the user Claims. Then authorization polices can be created during the Startup.Configure method as follows:

             */

            services.AddAuthorization(options =>

            {

                options.AddPolicy("AdminOnly", policy =>

                    policy.RequireAssertion(context =>

                        context.User.HasClaim(c => c.Type == "cognito:groups" && c.Value == "Admin")));

            });

        }


No comments:

Post a Comment