Use email domain to auto assign user as admin during initial sign in
Problem
Let’s consider this scenario.
We have a web app where our users can login to it. For authentication, we have setup Amazon Cognito with federated sign-in for Google.
Now, we have a need to allow the admin users as well to login. All our admin users have email with domain @some-company.com. This @some-company.com domain is managed through Google Workspace.
All our admin users have same access, features and capability. We do not need a fine-grain access mechanism.
Solution
Pre-requisites
Understanding of Amazon Cognito
Working setup of Cognito with Federated identity pool
Some working understanding of OAuth2
Since all the admin have same level of access, there is no need to setup an exhaustive authorization mechanism. All we need is a special claim on JWT token to identify the user as admin.
To do this, we will be leveraging Cognito UserPool Group capability.
When an user signs into the app for the first time, we will look at the domain part of the email and if it matches our company domain, we will add the user to the user group that we have created for admin users.
Create UserPool Group
We will first create a group in our Cognito User Pool.
Cloudformation for creating group
1
2
3
4
5
6
AdminUserPoolGroup:Type:AWS::Cognito::UserPoolGroupProperties:Description:Group which contains admin users.GroupName:!Ref AdminGroupNameUserPoolId:!Ref UserPool
constAWS=require('aws-sdk');exports.handler=async(event,context,callback)=>{const{userPoolId,userName}=event;constemail=event.request.userAttributes.email;constgroupName=process.env.ADMIN_GROUP_NAME;try{if(doesEmailBelongToAdminDomain(email)){awaitaddUserToGroup({userPoolId,username: userName,groupName,});}returncallback(null,event);}catch(error){returncallback(error,event);}};constdoesEmailBelongToAdminDomain=(email)=>{constadminEmailDomainName=process.env.ADMIN_EMAIL_DOMAIN_NAME;// Split the email address so we can compare domains
constaddress=email.split("@");if(adminEmailDomainName===address[1]){returntrue;}returnfalse;};constaddUserToGroup=({userPoolId,username,groupName,})=>{constparams={GroupName: groupName,UserPoolId: userPoolId,Username: username,};constcognitoIdp=newAWS.CognitoIdentityServiceProvider();returncognitoIdp.adminAddUserToGroup(params).promise();};
Token
After this setup, if you login with the company domain email, you will get a token that looks like the one below:
You will find that the cognito:groups claim will contain the name of the UserPool group you create above. This would indicate that the user belongs to admin group and you can use for authorization.