DEV Community

Cover image for Setup role based access with AWS IAM
Pavithra Sandamini
Pavithra Sandamini

Posted on

Setup role based access with AWS IAM

Step 1: Understanding AWS IAM
AWS IAM enables you to securely manage access to AWS services and resources. With RBAC, you can assign specific roles to users based on their access needs, and grant permissions through policies. This allows your application to control what actions users can perform within your web app, depending on their roles.

Step 2: Set Up IAM Roles and Policies

  1. Create IAM Policies IAM policies define what actions (like read, write, etc.) a user is allowed or denied. These policies are JSON documents attached to roles or users.

Example JSON Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::your-bucket-name",
"arn:aws:s3:::your-bucket-name/*"
]
}
]
}

This policy allows a user with this role to read objects from an S3 bucket.

  1. Create IAM Roles Roles are groups of permissions that can be assigned to IAM users or services.

Admin Role: Full access to all resources.
Read-Only Role: Permission to view certain resources.
Manager Role: Permissions to modify specific resources.

aws iam create-role --role-name AdminRole --assume-role-policy-document file://trust-policy.json
aws iam create-role --role-name ReadOnlyRole --assume-role-policy-document file://trust-policy.json

The trust policy defines which entities can assume the role.

  1. Assign Roles to Users You can attach these roles directly to specific IAM users or through groups. When users log in, their access is determined by the role they have.

aws iam add-user-to-group --user-name john_doe --group-name AdminGroup

Step 3: Configure Web Application for Role-Based Access
Now that your roles and policies are set up, you can implement role-based access in your web application using AWS SDK for programmatic access to IAM.

Backend: Setting Up AWS SDK
Install AWS SDK in your application backend:

npm install aws-sdk

Configure AWS credentials and permissions in your web app:

`const AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: 'us-west-2'
});

const sts = new AWS.STS();

function assumeRole(roleArn) {
return sts.assumeRole({
RoleArn: roleArn,
RoleSessionName: 'webAppSession'
}).promise();
}

assumeRole('arn:aws:iam::123456789012:role/AdminRole').then(data => {
console.log('Assumed Role: ', data);
}).catch(error => {
console.error('Error assuming role: ', error);
});`

This script authenticates the user, assumes a specific role, and grants the corresponding permissions.

Backend: Authorization Middleware
Next, implement a middleware that checks user roles and grants access accordingly.

`
function checkRole(requiredRole) {
return (req, res, next) => {
const userRole = req.user.role; // This comes from your auth system

if (userRole !== requiredRole) {
  return res.status(403).json({ error: 'Access Denied: Insufficient permissions' });
}

next();
Enter fullscreen mode Exit fullscreen mode

};
}

app.get('/admin', checkRole('Admin'), (req, res) => {
res.send('Welcome Admin');
});

app.get('/reports', checkRole('Manager'), (req, res) => {
res.send('Manager Reports');
});`

This middleware checks the user's role before allowing access to routes.

Step 4: Frontend Integration
For the frontend, restrict UI components based on user roles. Assuming you’re using React, this can be achieved with role-based rendering:

function AdminDashboard({ user }) {
if (user.role !== 'Admin') {
return

Access Denied

;
}

return (


Admin Dashboard


{/* Admin functionality */}

);
}

function App() {
const user = { role: 'Admin' }; // User role comes from auth

return (




);
}

Here, the AdminDashboard is only accessible if the logged-in user has the Admin role.

Step 5: Securing API Requests with Signed AWS Requests
For sensitive operations like interacting with AWS services, sign your API requests using the user's role. AWS provides signature version 4 signing for secure requests.

`const AWS = require('aws-sdk');

const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});

function listS3Buckets() {
return s3.listBuckets().promise();
}

listS3Buckets().then(buckets => {
console.log('S3 Buckets: ', buckets);
}).catch(err => {
console.error('Error listing buckets: ', err);
});`

If your application needs to allow access to external users (outside of AWS IAM), you can use AWS Cognito or other identity providers for federated access. AWS Cognito integrates with IAM roles, enabling you to assign AWS permissions to external users based on their role.

Conclusion
With AWS IAM and role-based access control, you can manage and secure your web application’s users based on their roles, ensuring that they only have access to the resources they need. By setting up IAM roles and policies, integrating AWS SDK in your backend, and enforcing role-based access in both the frontend and backend, you can create a secure and scalable web application.

Make sure to follow security best practices by using environment variables for sensitive credentials and employing least privilege principles when assigning permissions.

Top comments (0)