sum91
sum91

Reputation: 385

AWS-Cognito: How to assign user roles in the user pool?

I have an user management system where I am using AWS-Cognito userPool for signup/sign-in process.I need to assign roles to these users.
For example: Super admin, Referral and so on.

The super admin role is responsible for adding/deleting/editing the users. Is there any way to do this just by using userPool features ? Also, is it possible to assign roles through AWS console and not through an API ?

Upvotes: 4

Views: 9212

Answers (3)

Stephen Erdman
Stephen Erdman

Reputation: 1

I just ran into this for a Spring Boot project and didn't find an up to date answer. Everything I came across was for earlier versions than Spring Security 5.4. So I figured I'd put this out there to help anyone else who is looking for an answer.

Roles in cognito seems to be oriented around IAM access. To set roles for users in my application, I added groups in the Users and Groups section to handle metadata like roles.

So, I had groups like "ROLE:ADMIN", "ROLE:PREMIUM", etc.

Then I set up an OAuth2 login security configuration in my spring boot app. Put these dependencies in your maven file:

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-oauth2-jose</artifactId>
    </dependency>

You'll need these properties:

app.url=http://localhost:8080
cognito.region=<aws region>
cognito.poolId=<your pool id>
cognito.poolName=<your pool name>
cognito.rooturl=https://${cognito.poolName}.auth.${cognito.region}.amazoncognito.com
spring.security.oauth2.client.registration.cognito.provider=cognito
spring.security.oauth2.client.registration.cognito.client-id=<your client id>
spring.security.oauth2.client.registration.cognito.client-secret=<your client secret>
spring.security.oauth2.client.registration.cognito.client-name=${cognito.poolName}
spring.security.oauth2.client.registration.cognito.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.cognito.scope=email,openid
spring.security.oauth2.client.registration.cognito.redirect-uri=${app.url}/login/oauth2/code/cognito

spring.security.oauth2.client.provider.cognito.authorizationUri=${cognito.rooturl}/oauth2/authorize
spring.security.oauth2.client.provider.cognito.tokenUri=${cognito.rooturl}/oauth2/token
spring.security.oauth2.client.provider.cognito.jwkSetUri=https://cognito-idp.${cognito.region}.amazonaws.com/${cognito.poolId}/.well-known/jwks.json
spring.security.oauth2.client.provider.cognito.user-info-uri=${cognito.rooturl}/oauth2/userInfo
spring.security.oauth2.client.provider.cognito.userNameAttribute=username

That'll give you login and your token will have a "cognito:groups" list in its claims. To pull that out and put it into the authorities, you need to create an implementation of OAuth2UserService<OidcUserRequest, OidcUser> like so:

public class CognitoOIDCUserService implements OAuth2UserService<OidcUserRequest, OidcUser> {

    private static final String ROLE_PREFIX = "ROLE:";

    @Override
    public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
        Map<String, Object> parameters = userRequest.getIdToken().getClaims();
        List<String> groups = (List<String>) parameters.get("cognito:groups");
        List<GrantedAuthority> authorities =
                groups.stream().filter(group -> group.startsWith(ROLE_PREFIX))
                        .map(group -> group.substring(ROLE_PREFIX.length()))
                        .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                        .collect(Collectors.toList());

        return new DefaultOidcUser(authorities, userRequest.getIdToken(), "cognito:username");
    }
}

and then add it into your security config:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CognitoAuthenticationSuccessHandler successHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .and()
                .authorizeRequests(authz -> authz.mvcMatchers("/")
                        .permitAll()
                        .anyRequest()
                        .authenticated())
                .oauth2Login()
                .userInfoEndpoint(userInfo -> userInfo.oidcUserService(new CognitoOIDCUserService()))
                .successHandler(successHandler)
                .and()
                .logout()
                .logoutSuccessUrl("/");
    }
}

and then you'll have it.

Upvotes: 0

matsev
matsev

Reputation: 33789

The super admin role is responsible for adding/deleting/editing the users. Is there any way to do this just by using userPool features ?

You can assign IAM roles to groups. For example, if you create a superadminrole that you assign to the superadmingroup group, then the super admins have the appropriate actions according to the Actions for Amazon Cognito User Pools, e.g. cognito-idp:AdminCreateUser, cognito-idp:AdminDeleteUser, cognito-idp:AdminAddUserToGroup, cognito-idp:ListUsers, cognito-idp:ListUsersInGroup, etc. Then, a signed in super admin can execute the corresponding user task. Please also read the list of Developers and administrators can perform the following tasks to see what actions are available.


Also, is it possible to assign roles through AWS console and not through an API ?

Yes, copied from the Viewing User Attributes section in the AWS Cognito Developer guide (emphasis mine):

From the Amazon Cognito home page in the AWS Management Console, choose Manage your user identities.

Choose your user pool from the Your User Pools page.

Choose User and Groups to view user information.

Choose a user name to show more information about an individual user. From this screen, you can perform any of the following actions:

  1. Add user to group
  2. Reset user password
  3. Confirm user
  4. Enable or disable MFA
  5. Delete user

Upvotes: 5

Vladyslav Usenko
Vladyslav Usenko

Reputation: 2386

AWS Cognito supports role based access control, which may be your use case.

See: https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html

Upvotes: -1

Related Questions