Search code examples
amazon-web-servicesaws-sdkrole-base-authorization

AWS Authentication in JavaScript


I am developing a single page application with a REST backend that uses AWS Cognito for user management and authentication.

I have structured it such that when the user enters the page without a token, the following series of steps occur:

  1. Redirect to Cognito's default login page
  2. The user logs in and is redirected to host/authenticate.html
  3. An AJAX call is sent to Cognito's token endpoint, which returns the user's tokens. These are stored in sessionStorage
  4. The user is redirected to the web application and is now authenticated

I want to have two user roles in my application: Users and Admins. Users should not be allowed to call any AWS services, where as Admins should be allowed to create/invite and promote other users to admins on behalf of his company.

Currently I have set up an Identity Pool for the User Pool and web application, that enables the admin permissions. I authenticate with the Identity pool using the following code:

AWS.config.region = "eu-central-1";
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'eu-central-1:<my-indentitypool-id>',
    Logins: {
        'cognito-idp.eu-central-1.amazonaws.com/<my-userpool-id>':
            sessionStorage.getItem('id_token')
    }
});

AWS.config.credentials.get(function(err){
    if (err) {
        console.error(err);
    }
    console.log("Authenticated");
    cisp = new AWS.CognitoIdentityServiceProvider();

});

And when the admin wants to create a user:

cisp.adminCreateUser(params, function(err, data) {
    if (err) 
        console.log(err, err.stack);
    else
        console.log(data);
});

However, from my understanding of it this would allow all users of the web application to have Admin privileges, as the IAM role is associated with the Identity Pool and not the users per se.

Are there any simple way of achieving this?

Please feel free to ask questions in case anything is unclear and thanks in advance for your help.


Solution

  • I managed to find the solution in the end. In case anyone experiences the same issues as me you can go to the dashboard for your Cognito Identity Pool and edit it.

    There is a section called Authentication providers, where you can specify conditions for claims and give roles based on that. On the same page you can also edit which role is given to users who are not authenticated and default roles to users who are authenticated, but do not satisfy any of the conditions you specify.

    In my case I gave all authenticated users the role of User and created the condition shown in the picture below, which grants all users that have a value of "admin" in "custom:role" the role of Admin.

    Identity Pool control panel